From 5bcee4933742af2525e5113dd54be92f8324e7db Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 13 Dec 2024 18:50:55 +0100 Subject: [PATCH 001/175] add builderprovider and sql implementation --- .../com/alpsbte/plotsystem/PlotSystem.java | 11 + .../admin/setup/CMD_Setup_BuildTeam.java | 3 +- .../plotsystem/core/data/BuilderProvider.java | 36 ++ .../plotsystem/core/data/DataException.java | 7 + .../plotsystem/core/data/DataProvider.java | 5 + .../core/database/BuilderProviderSql.java | 386 ++++++++++++++++++ .../core/database/DataProviderSql.java | 16 + .../core/holograms/PlotsLeaderboard.java | 11 +- .../core/holograms/ScoreLeaderboard.java | 18 +- .../core/menus/PlayerPlotsMenu.java | 5 +- .../plotsystem/core/menus/ReviewMenu.java | 3 +- .../plotsystem/core/system/Builder.java | 329 ++------------- .../plot/generator/DefaultPlotGenerator.java | 5 +- 13 files changed, 523 insertions(+), 312 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/DataException.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 51a263e1..e9e1522a 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -25,6 +25,8 @@ package com.alpsbte.plotsystem; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; +import com.alpsbte.plotsystem.core.data.DataProvider; +import com.alpsbte.plotsystem.core.database.DataProviderSql; import com.alpsbte.plotsystem.core.holograms.HologramRegister; import com.alpsbte.alpslib.io.YamlFileFactory; import com.alpsbte.alpslib.io.config.ConfigNotImplementedException; @@ -74,6 +76,7 @@ public class PlotSystem extends JavaPlugin { private static final String VERSION = "4.0"; private static PlotSystem plugin; + private static DataProvider dataProvider; private CommandManager commandManager; private boolean pluginEnabled = false; @@ -139,6 +142,10 @@ public void onEnable() { return; } + // Set data provider + //TODO: get from config + dataProvider = new DataProviderSql(); + // Register event listeners try { this.getServer().getPluginManager().registerEvents(new EventListener(), this); @@ -268,6 +275,10 @@ public static PlotSystem getPlugin() { return plugin; } + public static DataProvider getDataProvider() { + return dataProvider; + } + public CommandManager getCommandManager() { return commandManager; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index ace57dde..37b34997 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; @@ -103,7 +104,7 @@ public void onCommand(CommandSender sender, String[] args) { StringJoiner countriesAsString = new StringJoiner(", "); StringJoiner reviewersAsString = new StringJoiner(", "); b.getCountries().forEach(c -> countriesAsString.add(String.valueOf(c.getID()))); - b.getReviewers().forEach(r -> {try {reviewersAsString.add(r.getName());} catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);}}); + b.getReviewers().forEach(r -> {try {reviewersAsString.add(r.getName());} catch (DataException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex);}}); sender.sendMessage(" §6> §b" + b.getID() + " (" + b.getName() + ") §f- Country IDs: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString)); } catch (SQLException ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java new file mode 100644 index 00000000..3db26a33 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java @@ -0,0 +1,36 @@ +package com.alpsbte.plotsystem.core.data; + +import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; +import com.alpsbte.plotsystem.core.system.BuildTeam; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; +import com.alpsbte.plotsystem.utils.enums.Slot; + +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + + +public interface BuilderProvider { + String getName(UUID uuid) throws DataException; + int getScore(UUID uuid) throws DataException; + int getCompletedBuildsCount(UUID uuid) throws DataException; + Slot getFreeSlot(UUID uuid) throws DataException; + Plot getPlot(UUID uuid, Slot slot) throws DataException; + void addScore(UUID uuid, int score) throws DataException; + void addCompletedBuild(UUID uuid, int amount) throws DataException; + void setPlot(UUID uuid, int plotID, Slot slot) throws DataException; + void removePlot(UUID uuid, Slot slot) throws DataException; + Builder getBuilderByName(String name) throws DataException; + PlotType getPlotTypeSetting(UUID uuid); + void setPlotTypeSetting(UUID uuid, PlotType plotType); + boolean isReviewer(UUID uuid) throws DataException; + List getReviewerCountries(List buildTeams); + int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; + int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; + int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; + HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; + HashMap getLeaderboardEntriesByCompletedBuilds(int limit) throws DataException; +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/DataException.java b/src/main/java/com/alpsbte/plotsystem/core/data/DataException.java new file mode 100644 index 00000000..e7f7b59a --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/data/DataException.java @@ -0,0 +1,7 @@ +package com.alpsbte.plotsystem.core.data; + +public class DataException extends RuntimeException { + public DataException(String message) { + super(message); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java new file mode 100644 index 00000000..6f76febc --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java @@ -0,0 +1,5 @@ +package com.alpsbte.plotsystem.core.data; + +public interface DataProvider { + BuilderProvider getBuilderProvider(); +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java new file mode 100644 index 00000000..f2458881 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java @@ -0,0 +1,386 @@ +package com.alpsbte.plotsystem.core.database; + +import com.alpsbte.alpslib.hologram.DecentHologramDisplay; +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.DataException; +import com.alpsbte.plotsystem.core.holograms.PlotsLeaderboard; +import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; +import com.alpsbte.plotsystem.core.system.BuildTeam; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.data.BuilderProvider; +import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; +import com.alpsbte.plotsystem.utils.enums.Slot; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.stream.Collectors; + +import static net.kyori.adventure.text.Component.text; + +public class BuilderProviderSql implements BuilderProvider { + @Override + public String getName(UUID uuid) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_builders WHERE uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + if (rs.next()) { + String s = rs.getString(1); + DatabaseConnection.closeResultSet(rs); + return s; + } + + DatabaseConnection.closeResultSet(rs); + + Player p = Bukkit.getPlayer(uuid); + return p != null ? p.getName() : ""; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public int getScore(UUID uuid) { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT score FROM plotsystem_builders WHERE uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + if (rs.next()) { + int i = rs.getInt(1); + DatabaseConnection.closeResultSet(rs); + return i; + } + + DatabaseConnection.closeResultSet(rs); + return 0; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public int getCompletedBuildsCount(UUID uuid) { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT completed_plots FROM plotsystem_builders WHERE uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + if (rs.next()) { + int i = rs.getInt(1); + DatabaseConnection.closeResultSet(rs); + return i; + } + + DatabaseConnection.closeResultSet(rs); + return 0; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public Slot getFreeSlot(UUID uuid) { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT first_slot, second_slot, third_slot FROM plotsystem_builders WHERE uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + if (rs.next()) { + for (int i = 1; i <= 3; i++) { + if (rs.getString(i) == null) { + DatabaseConnection.closeResultSet(rs); + return Slot.values()[i - 1]; + } + } + } + + DatabaseConnection.closeResultSet(rs); + return null; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public Plot getPlot(UUID uuid, Slot slot) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT " + slot.name().toLowerCase() + " FROM plotsystem_builders WHERE uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + int plotID = -1; + if (rs.next()) plotID = rs.getInt(1); + + boolean boo = rs.wasNull(); + DatabaseConnection.closeResultSet(rs); + + return boo ? null : new Plot(plotID); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void addScore(UUID uuid, int score) throws DataException { + try { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET score = ? WHERE uuid = ?") + .setValue(getScore(uuid) + score).setValue(uuid.toString()) + .executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() + .filter(leaderboard -> leaderboard instanceof ScoreLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); + } + + @Override + public void addCompletedBuild(UUID uuid, int amount) throws DataException { + try { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET completed_plots = ? WHERE uuid = ?") + .setValue(getCompletedBuildsCount(uuid) + amount).setValue(uuid.toString()) + .executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() + .filter(leaderboard -> leaderboard instanceof PlotsLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); + } + + @Override + public void setPlot(UUID uuid, int plotID, Slot slot) throws DataException { + try { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = ? WHERE uuid = ?") + .setValue(plotID).setValue(uuid.toString()) + .executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void removePlot(UUID uuid, Slot slot) throws DataException { + if (slot != null) { // If not null, plot is already removed from player slot + try { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = DEFAULT(first_slot) WHERE uuid = ?") + .setValue(uuid.toString()) + .executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + } + + @Override + public Builder getBuilderByName(String name) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT uuid FROM plotsystem_builders WHERE name = ?") + .setValue(name).executeQuery()) { + + if (rs.next()) { + String s = rs.getString(1); + DatabaseConnection.closeResultSet(rs); + return Builder.byUUID(UUID.fromString(s)); + } + + DatabaseConnection.closeResultSet(rs); + return null; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public PlotType getPlotTypeSetting(UUID uuid) { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT setting_plot_type FROM plotsystem_builders WHERE uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + if (rs.next()) { + int id = rs.getInt(1); + PlotType plotType = PlotType.byId(id); + DatabaseConnection.closeResultSet(rs); + + return plotType; + } + DatabaseConnection.closeResultSet(rs); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while getting language setting from database"), ex); + } + return null; + } + + @Override + public void setPlotTypeSetting(UUID uuid, PlotType plotType) { + try { + if (plotType == null) { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET setting_plot_type = DEFAULT(setting_plot_type) WHERE uuid = ?") + .setValue(uuid.toString()).executeUpdate(); + } else { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET setting_plot_type = ? WHERE uuid = ?") + .setValue(plotType.getId()).setValue(uuid.toString()) + .executeUpdate(); + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while getting language setting from database"), ex); + } + } + + @Override + public boolean isReviewer(UUID uuid) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT COUNT(builder_uuid) FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") + .setValue(uuid.toString()).executeQuery()) { + + int count = 0; + if (rs.next()) count = rs.getInt(1); + DatabaseConnection.closeResultSet(rs); + return count > 0; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public List getReviewerCountries(List buildTeams) { + Set countries = new HashSet<>(); + buildTeams.forEach(b -> { + try { + countries.addAll(b.getCountries().stream().map(Country::getID).collect(Collectors.toList())); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } + }); + + return countries.stream().map(c -> { + try { + return new Country(c); + } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} + return null; + }).collect(Collectors.toList()); + } + + @Override + public int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + String query = getLeaderboardScoreQuery(sortBy, 0); + + try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { + boolean found = false; + int score = 0; + while (rs.next() && !found) { + if (rs.getString(3).equals(uuid.toString())) { + found = true; + score = rs.getInt(4); + } + } + + if (!found) score = -1; + + DatabaseConnection.closeResultSet(rs); + return score; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + String query = getLeaderboardScoreQuery(sortBy, 0); + + try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { + boolean found = false; + int position = 0; + while (rs.next() && !found) { + position++; + if (rs.getString(3).equals(uuid.toString())) { + found = true; + } + } + + if (!found) position = -1; + + DatabaseConnection.closeResultSet(rs); + return position; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + String query = "SELECT COUNT(*) FROM (" + getLeaderboardScoreQuery(sortBy, 0) + ") results"; + + try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { + rs.next(); + int position = rs.getInt(1); + + DatabaseConnection.closeResultSet(rs); + return position; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + String query = getLeaderboardScoreQuery(sortBy, 10); + + try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { + HashMap lines = new HashMap<>(); + + while (rs.next()) { + lines.put(rs.getString(2), rs.getInt(4)); + } + + DatabaseConnection.closeResultSet(rs); + return lines; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public HashMap getLeaderboardEntriesByCompletedBuilds(int limit) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT name, completed_plots FROM plotsystem_builders ORDER BY completed_plots DESC LIMIT ?") + .setValue(limit).executeQuery()) { + + HashMap results = new HashMap<>(); + while (rs.next()) { + results.put(rs.getString(1), rs.getInt(2)); + } + + DatabaseConnection.closeResultSet(rs); + return results; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + private String getLeaderboardScoreQuery(ScoreLeaderboard.LeaderboardTimeframe sortBy, int limit) { + String minimumDate = null; + switch (sortBy) { + case DAILY: + minimumDate = "(NOW() - INTERVAL 1 DAY)"; + break; + case WEEKLY: + minimumDate = "(NOW() - INTERVAL 1 WEEK)"; + break; + case MONTHLY: + minimumDate = "(NOW() - INTERVAL 1 MONTH)"; + break; + case YEARLY: + minimumDate = "(NOW() - INTERVAL 1 YEAR)"; + break; + default: + // no limits + break; + } + + // get plot id, owner username, owner uuid, score & date + // sort by score & limit (if set above) by timeframe + return "SELECT plots.id, builders.name, plots.owner_uuid, SUM(plots.score) AS score, reviews.review_date FROM plotsystem_plots AS plots\n" + + "INNER JOIN plotsystem_reviews AS reviews ON plots.review_id = reviews.id\n" + + "INNER JOIN plotsystem_builders AS builders ON builders.uuid = plots.owner_uuid\n" + + (minimumDate != null + ? "WHERE reviews.review_date BETWEEN " + minimumDate + " AND NOW()\n" + : "") + + "GROUP BY plots.owner_uuid \n" + + "ORDER BY score DESC, builders.name\n" + + (limit > 0 ? "LIMIT " + limit : ""); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java new file mode 100644 index 00000000..9e39986f --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java @@ -0,0 +1,16 @@ +package com.alpsbte.plotsystem.core.database; + +import com.alpsbte.plotsystem.core.data.BuilderProvider; +import com.alpsbte.plotsystem.core.data.DataProvider; + +public class DataProviderSql implements DataProvider { + private final BuilderProvider builderProvider; + + public DataProviderSql() { + builderProvider = new BuilderProviderSql(); + } + @Override + public BuilderProvider getBuilderProvider() { + return builderProvider; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java index 51d4e1e0..cdd7f87f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java @@ -26,13 +26,14 @@ import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.items.BaseItems; import org.bukkit.inventory.ItemStack; -import java.sql.SQLException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.UUID; import java.util.logging.Level; @@ -59,14 +60,14 @@ public List> getContent(UUID playerUUID) { try { ArrayList> lines = new ArrayList<>(); - List> entries = Builder.getBuildersByCompletedBuilds(10); + HashMap entries = Builder.getBuildersByCompletedBuilds(10); for (int i = 0; i < 10; i++) { - Builder.DatabaseEntry entry = i < entries.size() && entries.get(i).getValue() != 0 ? entries.get(i) : null; - lines.add(new HologramRegister.LeaderboardPositionLine(i + 1, entry != null ? entry.getKey() : null, entry != null ? entry.getValue() : 0)); + String key = i < entries.size() && entries.get((String) entries.keySet().toArray()[i]) != 0 ? (String) entries.keySet().toArray()[i] : null; + lines.add(new HologramRegister.LeaderboardPositionLine(i + 1, key, entries.get(key) != null ? entries.get(key) : 0)); } return lines; - } catch (SQLException ex) { + } catch (DataException ex) { PlotSystem.getPlugin().getLogger().log(Level.SEVERE, "An error occurred while reading leaderboard content", ex); } return new ArrayList<>(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java index 4625c69f..37ae1897 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.hologram.DecentHologramPagedDisplay; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Payout; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; @@ -48,10 +49,7 @@ import java.sql.SQLException; import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; +import java.util.*; import java.util.logging.Level; import java.util.stream.Collectors; @@ -124,14 +122,14 @@ public List> getContent(UUID playerUUID) { lines.add(new LeaderboardPositionLineWithPayout(index + 1, null, 0)); } - int index = 0; - for (Builder.DatabaseEntry entry : Builder.getBuildersByScore(sortByLeaderboard)) { - lines.set(index, new LeaderboardPositionLineWithPayout(index + 1, entry.getKey(), entry.getValue())); - index++; + HashMap leaderboardScores = Builder.getBuildersByScore(sortByLeaderboard); + for (int i = 0; i < leaderboardScores.size(); i++) { + String key = (String) leaderboardScores.keySet().toArray()[i]; + lines.set(i, new LeaderboardPositionLineWithPayout(i + 1, key, leaderboardScores.get(key))); } return lines; - } catch (SQLException ex) { + } catch (DataException ex) { PlotSystem.getPlugin().getLogger().log(Level.SEVERE, "An error occurred while reading leaderboard content", ex); } return new ArrayList<>(); @@ -143,7 +141,7 @@ private Component getRankingString(Player player) { position = Builder.getBuilderScorePosition(player.getUniqueId(), sortByLeaderboard); rows = Builder.getBuildersInSort(sortByLeaderboard); myScore = Builder.getBuilderScore(player.getUniqueId(), sortByLeaderboard); - } catch (SQLException ex) { + } catch (DataException ex) { PlotSystem.getPlugin().getComponentLogger().error(Component.text("A SQL error occurred!"), ex); return Component.empty(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 6903801e..d1f642c4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -88,8 +89,8 @@ protected void setMenuItemsAsync() { .append(text(builder.getCompletedBuilds(), WHITE))) .build()) .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } catch (DataException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex); getMenu().getSlot(4).setItem(MenuItems.errorItem(getMenuPlayer())); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 03b40ed7..0041ea73 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -94,7 +95,7 @@ protected void setPaginatedMenuItemsAsync(List source) { lines.add(""); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER) + ": §f" + plot.getPlotOwner().getName()); if (!plot.getPlotMembers().isEmpty()) lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBERS) + ": §f" + plot.getPlotMembers().stream().map(m -> { - try {return m.getName();} catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} + try {return m.getName();} catch (DataException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} return ""; }).collect(Collectors.joining(", ")) ); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index eb7da815..7d4d1753 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -24,12 +24,10 @@ package com.alpsbte.plotsystem.core.system; -import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.holograms.PlotsLeaderboard; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; @@ -44,15 +42,10 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; -import java.util.stream.Collectors; - -import static net.kyori.adventure.text.Component.text; public class Builder { - public static final HashMap builders = new HashMap<>(); private final UUID uuid; @@ -72,7 +65,6 @@ public static Builder byUUID(UUID uuid) { return builders.get(uuid); } - public Player getPlayer() { return Bukkit.getPlayer(uuid); } @@ -83,82 +75,24 @@ public java.util.UUID getUUID() { public boolean isOnline() {return Bukkit.getPlayer(uuid) != null;} - public String getName() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_builders WHERE uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return s; - } - - DatabaseConnection.closeResultSet(rs); - - return getPlayer() != null ? getPlayer().getName() : ""; - } + public String getName() throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getName(uuid); } - public int getScore() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT score FROM plotsystem_builders WHERE uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } + public int getScore() throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getScore(uuid); } - public int getCompletedBuilds() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT completed_plots FROM plotsystem_builders WHERE uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } + public int getCompletedBuilds() throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getCompletedBuildsCount(uuid); } - public Slot getFreeSlot() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT first_slot, second_slot, third_slot FROM plotsystem_builders WHERE uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - if (rs.next()) { - for (int i = 1; i <= 3; i++) { - if (rs.getString(i) == null) { - DatabaseConnection.closeResultSet(rs); - return Slot.values()[i - 1]; - } - } - } - - DatabaseConnection.closeResultSet(rs); - return null; - } + public Slot getFreeSlot() throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getFreeSlot(uuid); } - public Plot getPlot(Slot slot) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT " + slot.name().toLowerCase() + " FROM plotsystem_builders WHERE uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - int plotID = -1; - if (rs.next()) plotID = rs.getInt(1); - - boolean boo = rs.wasNull(); - DatabaseConnection.closeResultSet(rs); - - return boo ? null : new Plot(plotID); - } + public Plot getPlot(Slot slot) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getPlot(uuid, slot); } public ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) throws SQLException { @@ -193,186 +127,47 @@ public ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) th .build(); } - public void addScore(int score) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET score = ? WHERE uuid = ?") - .setValue(getScore() + score).setValue(getUUID().toString()) - .executeUpdate(); - - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() - .filter(leaderboard -> leaderboard instanceof ScoreLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); - } - - public void addCompletedBuild(int amount) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET completed_plots = ? WHERE uuid = ?") - .setValue(getCompletedBuilds() + amount).setValue(getUUID().toString()) - .executeUpdate(); - - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() - .filter(leaderboard -> leaderboard instanceof PlotsLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); - } - - public void setPlot(int plotID, Slot slot) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = ? WHERE uuid = ?") - .setValue(plotID).setValue(getUUID().toString()) - .executeUpdate(); + public void addScore(int score) throws DataException { + PlotSystem.getDataProvider().getBuilderProvider().addScore(uuid, score); } - public void removePlot(Slot slot) throws SQLException { - if (slot != null) { // If not null, plot is already removed from player slot - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = DEFAULT(first_slot) WHERE uuid = ?") - .setValue(getUUID().toString()) - .executeUpdate(); - } + public void addCompletedBuild(int amount) throws DataException { + PlotSystem.getDataProvider().getBuilderProvider().addCompletedBuild(uuid, amount); } - public static Builder getBuilderByName(String name) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT uuid FROM plotsystem_builders WHERE name = ?") - .setValue(name).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return Builder.byUUID(UUID.fromString(s)); - } - - DatabaseConnection.closeResultSet(rs); - return null; - } + public void setPlot(int plotID, Slot slot) throws DataException { + PlotSystem.getDataProvider().getBuilderProvider().setPlot(uuid, plotID, slot); } - private static String getBuildersByScoreQuery(ScoreLeaderboard.LeaderboardTimeframe sortBy, int limit) { - String minimumDate = null; - switch (sortBy) { - case DAILY: - minimumDate = "(NOW() - INTERVAL 1 DAY)"; - break; - case WEEKLY: - minimumDate = "(NOW() - INTERVAL 1 WEEK)"; - break; - case MONTHLY: - minimumDate = "(NOW() - INTERVAL 1 MONTH)"; - break; - case YEARLY: - minimumDate = "(NOW() - INTERVAL 1 YEAR)"; - break; - default: - // no limits - break; - } - - // get plot id, owner username, owner uuid, score & date - // sort by score & limit (if set above) by timeframe - return "SELECT plots.id, builders.name, plots.owner_uuid, SUM(plots.score) AS score, reviews.review_date FROM plotsystem_plots AS plots\n" + - "INNER JOIN plotsystem_reviews AS reviews ON plots.review_id = reviews.id\n" + - "INNER JOIN plotsystem_builders AS builders ON builders.uuid = plots.owner_uuid\n" + - (minimumDate != null - ? "WHERE reviews.review_date BETWEEN " + minimumDate + " AND NOW()\n" - : "") + - "GROUP BY plots.owner_uuid \n" + - "ORDER BY score DESC, builders.name\n" + - (limit > 0 ? "LIMIT " + limit : ""); + public void removePlot(Slot slot) throws DataException { + PlotSystem.getDataProvider().getBuilderProvider().removePlot(uuid, slot); } - public static int getBuilderScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = getBuildersByScoreQuery(sortBy, 0); - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - boolean found = false; - int score = 0; - while (rs.next() && !found) { - if (rs.getString(3).equals(uuid.toString())) { - found = true; - score = rs.getInt(4); - } - } - - if (!found) score = -1; - - DatabaseConnection.closeResultSet(rs); - return score; - } + public static Builder getBuilderByName(String name) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getBuilderByName(name); } - public static int getBuilderScorePosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = getBuildersByScoreQuery(sortBy, 0); - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - boolean found = false; - int position = 0; - while (rs.next() && !found) { - position++; - if (rs.getString(3).equals(uuid.toString())) { - found = true; - } - } - - if (!found) position = -1; - - DatabaseConnection.closeResultSet(rs); - return position; - } + public static int getBuilderScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardScore(uuid, sortBy); } - public static int getBuildersInSort(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = "SELECT COUNT(*) FROM (" + getBuildersByScoreQuery(sortBy, 0) + ") results"; - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - rs.next(); - int position = rs.getInt(1); - - DatabaseConnection.closeResultSet(rs); - return position; - } + public static int getBuilderScorePosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardPosition(uuid, sortBy); } - public static class DatabaseEntry { - private final K key; - private final V value; - - DatabaseEntry(K k, V v) { - this.key = k; - this.value = v; - } - - public K getKey() { - return key; - } - - public V getValue() { - return value; - } + public static int getBuildersInSort(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardEntryCount(sortBy); } - public static List> getBuildersByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = getBuildersByScoreQuery(sortBy, 10); - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - ArrayList> lines = new ArrayList<>(); - - while (rs.next()) { - lines.add(new DatabaseEntry<>(rs.getString(2), rs.getInt(4))); - } - - DatabaseConnection.closeResultSet(rs); - return lines; - } + public static HashMap getBuildersByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardEntriesByScore(sortBy); } - public static List> getBuildersByCompletedBuilds(int limit) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name, completed_plots FROM plotsystem_builders ORDER BY completed_plots DESC LIMIT ?") - .setValue(limit).executeQuery()) { - - ArrayList> results = new ArrayList<>(); - while (rs.next()) { - results.add(new DatabaseEntry<>(rs.getString(1), rs.getInt(2))); - } - - DatabaseConnection.closeResultSet(rs); - return results; - } + public static HashMap getBuildersByCompletedBuilds(int limit) throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardEntriesByCompletedBuilds(limit); } - public Slot getSlot(Plot plot) throws SQLException { + public Slot getSlot(Plot plot) throws DataException { for (Slot slot : Slot.values()) { Plot slotPlot = getPlot(slot); if (slotPlot != null && slotPlot.getID() == plot.getID()) { @@ -385,38 +180,12 @@ public Slot getSlot(Plot plot) throws SQLException { public PlotType getPlotTypeSetting() { if (plotType != null) return plotType; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT setting_plot_type FROM plotsystem_builders WHERE uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - if (rs.next()) { - int id = rs.getInt(1); - this.plotType = PlotType.byId(id); - DatabaseConnection.closeResultSet(rs); - - return plotType; - } - DatabaseConnection.closeResultSet(rs); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while getting language setting from database"), ex); - } - return null; + this.plotType = PlotSystem.getDataProvider().getBuilderProvider().getPlotTypeSetting(uuid); + return plotType; } public void setPlotTypeSetting(PlotType plotType) { - try { - if (plotType == null) { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET setting_plot_type = DEFAULT(setting_plot_type) WHERE uuid = ?") - .setValue(getUUID().toString()).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET setting_plot_type = ? WHERE uuid = ?") - .setValue(plotType.getId()).setValue(getUUID().toString()) - .executeUpdate(); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while getting language setting from database"), ex); - } - + PlotSystem.getDataProvider().getBuilderProvider().setPlotTypeSetting(uuid, plotType); this.plotType = plotType; } @@ -424,40 +193,18 @@ public Reviewer getAsReviewer() throws SQLException { return new Reviewer(getUUID()); } - public boolean isReviewer() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT COUNT(builder_uuid) FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") - .setValue(getUUID().toString()).executeQuery()) { - - int count = 0; - if (rs.next()) count = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return count > 0; - } + public boolean isReviewer() throws DataException { + return PlotSystem.getDataProvider().getBuilderProvider().isReviewer(uuid); } public static class Reviewer { private final List buildTeams; - public Reviewer(UUID reviewerUUID) throws SQLException { this.buildTeams = BuildTeam.getBuildTeamsByReviewer(reviewerUUID); } public List getCountries() { - Set countries = new HashSet<>(); - buildTeams.forEach(b -> { - try { - countries.addAll(b.getCountries().stream().map(Country::getID).collect(Collectors.toList())); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - }); - - return countries.stream().map(c -> { - try { - return new Country(c); - } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - return null; - }).collect(Collectors.toList()); + return PlotSystem.getDataProvider().getBuilderProvider().getReviewerCountries(buildTeams); } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 5ca98740..c7f99241 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -88,8 +89,8 @@ protected boolean init() { getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Error.ALL_SLOTS_OCCUPIED))); getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } catch (DataException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex); } return false; } From 17e3df13bcce6d82b9cfac8764446528ccfc74e0 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 13 Dec 2024 20:59:24 +0100 Subject: [PATCH 002/175] Add BuildTeamProvider and SQL implementation --- .../admin/setup/CMD_Setup_BuildTeam.java | 10 +- .../core/data/BuildTeamProvider.java | 23 +++ .../plotsystem/core/data/DataProvider.java | 1 + .../core/database/BuildTeamProviderSql.java | 162 ++++++++++++++++++ .../core/database/BuilderProviderSql.java | 2 +- .../core/database/DataProviderSql.java | 8 + .../plotsystem/core/system/BuildTeam.java | 106 ++++-------- 7 files changed, 229 insertions(+), 83 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 37b34997..070a12cd 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -106,7 +106,7 @@ public void onCommand(CommandSender sender, String[] args) { b.getCountries().forEach(c -> countriesAsString.add(String.valueOf(c.getID()))); b.getReviewers().forEach(r -> {try {reviewersAsString.add(r.getName());} catch (DataException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex);}}); sender.sendMessage(" §6> §b" + b.getID() + " (" + b.getName() + ") §f- Country IDs: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString)); - } catch (SQLException ex) { + } catch (DataException ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } @@ -152,7 +152,7 @@ public void onCommand(CommandSender sender, String[] args) { String name = CMD_Setup.appendArgs(args, 1); BuildTeam.addBuildTeam(name); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added build team with name '" + name + "'!")); - } catch (SQLException ex) { + } catch (Exception ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } @@ -197,7 +197,7 @@ public void onCommand(CommandSender sender, String[] args) { } BuildTeam.removeBuildTeam(Integer.parseInt(args[1])); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); - } catch (SQLException ex) { + } catch (Exception ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } @@ -244,7 +244,7 @@ public void onCommand(CommandSender sender, String[] args) { BuildTeam.setBuildTeamName(Integer.parseInt(args[1]), name); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed name of build team with ID " + args[1] + " to '" + name + "'!")); - } catch (SQLException ex) { + } catch (Exception ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } @@ -391,7 +391,7 @@ public void onCommand(CommandSender sender, String[] args) { } BuildTeam.addReviewer(Integer.parseInt(args[1]), builder.getUUID().toString()); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added '" + builder.getName() + "' as reviewer to build team with ID " + args[1] + "!")); - } catch (SQLException ex) { + } catch (Exception ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java new file mode 100644 index 00000000..d518d657 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java @@ -0,0 +1,23 @@ +package com.alpsbte.plotsystem.core.data; + +import com.alpsbte.plotsystem.core.system.BuildTeam; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.Country; + +import java.util.List; +import java.util.UUID; + +public interface BuildTeamProvider { + String getName(int id) throws DataException; + List getCountries(int id) throws DataException; + List getReviewers(int id) throws DataException; + List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataException; + List getBuildTeams(); + void addBuildTeam(String name) throws DataException; + void removeBuildTeam(int serverId) throws DataException; + void setBuildTeamName(int id, String newName) throws DataException; + void addCountry(int id, int countryId) throws DataException; + void removeCountry(int id, int countryId) throws DataException; + void addReviewer(int id, String reviewerUUID) throws DataException; + void removeReviewer(int id, String reviewerUUID) throws DataException; +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java index 6f76febc..d1dfe681 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java @@ -2,4 +2,5 @@ public interface DataProvider { BuilderProvider getBuilderProvider(); + BuildTeamProvider getBuildTeamProvider(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java new file mode 100644 index 00000000..a0512ba6 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java @@ -0,0 +1,162 @@ +package com.alpsbte.plotsystem.core.database; + +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.data.BuildTeamProvider; +import com.alpsbte.plotsystem.core.data.DataException; +import com.alpsbte.plotsystem.core.system.BuildTeam; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.Country; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static net.kyori.adventure.text.Component.text; + +public class BuildTeamProviderSql implements BuildTeamProvider { + @Override + public String getName(int id) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_buildteams WHERE id = ?") + .setValue(id).executeQuery()) { + + if (rs.next()) return rs.getString(1); + DatabaseConnection.closeResultSet(rs); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + return null; + } + + @Override + public List getCountries(int id) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT country_id FROM plotsystem_buildteam_has_countries WHERE buildteam_id = ?") + .setValue(id).executeQuery()) { + + List countries = new ArrayList<>(); + while (rs.next()) countries.add(new Country(rs.getInt(1))); + DatabaseConnection.closeResultSet(rs); + return countries; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public List getReviewers(int id) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT builder_uuid FROM plotsystem_builder_is_reviewer WHERE buildteam_id = ?") + .setValue(id).executeQuery()) { + + List builders = new ArrayList<>(); + while (rs.next()) builders.add(Builder.byUUID(UUID.fromString(rs.getString(1)))); + DatabaseConnection.closeResultSet(rs); + return builders; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataException { + try (ResultSet rs = DatabaseConnection.createStatement("SELECT buildteam_id FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") + .setValue(reviewerUUID.toString()).executeQuery()) { + + List buildTeams = new ArrayList<>(); + while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1))); + DatabaseConnection.closeResultSet(rs); + return buildTeams; + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public List getBuildTeams() { + List buildTeams = new ArrayList<>(); + try (ResultSet rs = DatabaseConnection.createStatement("SELECT id, name FROM plotsystem_buildteams").executeQuery()) { + while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1), rs.getString(2))); + DatabaseConnection.closeResultSet(rs); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } + return buildTeams; + } + + @Override + public void addBuildTeam(String name) throws DataException { + int id = DatabaseConnection.getTableID("plotsystem_buildteams"); + try { + DatabaseConnection.createStatement("INSERT INTO plotsystem_buildteams (id, name) VALUES (?, ?)") + .setValue(id) + .setValue(name).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void removeBuildTeam(int serverId) throws DataException { + try { + DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteams WHERE id = ?") + .setValue(serverId).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void setBuildTeamName(int id, String newName) throws DataException { + try { + DatabaseConnection.createStatement("UPDATE plotsystem_buildteams SET name = ? WHERE id = ?") + .setValue(newName) + .setValue(id).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void addCountry(int id, int countryId) throws DataException { + try { + DatabaseConnection.createStatement("INSERT plotsystem_buildteam_has_countries SET country_id = ?, buildteam_id = ?") + .setValue(countryId) + .setValue(id).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void removeCountry(int id, int countryId) throws DataException { + try { + DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteam_has_countries WHERE country_id = ? AND buildteam_id = ?") + .setValue(countryId) + .setValue(id).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void addReviewer(int id, String reviewerUUID) throws DataException { + try { + DatabaseConnection.createStatement("INSERT plotsystem_builder_is_reviewer SET builder_uuid = ?, buildteam_id = ?") + .setValue(reviewerUUID) + .setValue(id).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } + + @Override + public void removeReviewer(int id, String reviewerUUID) throws DataException { + try { + DatabaseConnection.createStatement("DELETE FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ? AND buildteam_id = ?") + .setValue(reviewerUUID) + .setValue(id).executeUpdate(); + } catch (SQLException e) { + throw new DataException(e.getMessage()); + } + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java index f2458881..bdffdd33 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java @@ -242,7 +242,7 @@ public List getReviewerCountries(List buildTeams) { buildTeams.forEach(b -> { try { countries.addAll(b.getCountries().stream().map(Country::getID).collect(Collectors.toList())); - } catch (SQLException ex) { + } catch (DataException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } }); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java index 9e39986f..b01a7c53 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java @@ -1,16 +1,24 @@ package com.alpsbte.plotsystem.core.database; +import com.alpsbte.plotsystem.core.data.BuildTeamProvider; import com.alpsbte.plotsystem.core.data.BuilderProvider; import com.alpsbte.plotsystem.core.data.DataProvider; public class DataProviderSql implements DataProvider { private final BuilderProvider builderProvider; + private final BuildTeamProvider buildTeamProvider; public DataProviderSql() { builderProvider = new BuilderProviderSql(); + buildTeamProvider = new BuildTeamProviderSql(); } @Override public BuilderProvider getBuilderProvider() { return builderProvider; } + + @Override + public BuildTeamProvider getBuildTeamProvider() { + return buildTeamProvider; + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 3ad21d42..6852aa8e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -25,29 +25,24 @@ package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.data.DataException; -import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; import java.util.UUID; -import static net.kyori.adventure.text.Component.text; - public class BuildTeam { private final int ID; - private String name; + private final String name; - private BuildTeam(int ID) throws SQLException { + public BuildTeam(int ID) throws SQLException { this.ID = ID; + this.name = PlotSystem.getDataProvider().getBuildTeamProvider().getName(ID); + } - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_buildteams WHERE id = ?") - .setValue(ID).executeQuery()) { - - if (rs.next()) this.name = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - } + public BuildTeam(int ID, String name) { + this.ID = ID; + this.name = name; } public int getID() { @@ -58,90 +53,47 @@ public String getName() { return name; } - public List getCountries() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT country_id FROM plotsystem_buildteam_has_countries WHERE buildteam_id = ?") - .setValue(ID).executeQuery()) { - - List countries = new ArrayList<>(); - while (rs.next()) countries.add(new Country(rs.getInt(1))); - DatabaseConnection.closeResultSet(rs); - return countries; - } + public List getCountries() throws DataException { + return PlotSystem.getDataProvider().getBuildTeamProvider().getCountries(ID); } - public List getReviewers() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT builder_uuid FROM plotsystem_builder_is_reviewer WHERE buildteam_id = ?") - .setValue(ID).executeQuery()) { - - List builders = new ArrayList<>(); - while (rs.next()) builders.add(Builder.byUUID(UUID.fromString(rs.getString(1)))); - DatabaseConnection.closeResultSet(rs); - return builders; - } + public List getReviewers() throws DataException { + return PlotSystem.getDataProvider().getBuildTeamProvider().getReviewers(ID); } - public static List getBuildTeamsByReviewer(UUID reviewerUUID) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT buildteam_id FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") - .setValue(reviewerUUID.toString()).executeQuery()) { - - List buildTeams = new ArrayList<>(); - while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1))); - DatabaseConnection.closeResultSet(rs); - return buildTeams; - } + public static List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataException { + return PlotSystem.getDataProvider().getBuildTeamProvider().getBuildTeamsByReviewer(reviewerUUID); } public static List getBuildTeams() { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_buildteams").executeQuery()) { - List buildTeams = new ArrayList<>(); - while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1))); - DatabaseConnection.closeResultSet(rs); - return buildTeams; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); + return PlotSystem.getDataProvider().getBuildTeamProvider().getBuildTeams(); } - public static void addBuildTeam(String name) throws SQLException { - int id = DatabaseConnection.getTableID("plotsystem_buildteams"); - DatabaseConnection.createStatement("INSERT INTO plotsystem_buildteams (id, name) VALUES (?, ?)") - .setValue(id) - .setValue(name).executeUpdate(); + public static void addBuildTeam(String name) throws DataException { + PlotSystem.getDataProvider().getBuildTeamProvider().addBuildTeam(name); } - public static void removeBuildTeam(int serverID) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteams WHERE id = ?") - .setValue(serverID).executeUpdate(); + public static void removeBuildTeam(int serverID) throws DataException { + PlotSystem.getDataProvider().getBuildTeamProvider().removeBuildTeam(serverID); } - public static void setBuildTeamName(int id, String newName) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_buildteams SET name = ? WHERE id = ?") - .setValue(newName) - .setValue(id).executeUpdate(); + public static void setBuildTeamName(int id, String newName) throws DataException { + PlotSystem.getDataProvider().getBuildTeamProvider().setBuildTeamName(id, newName); } - public static void addCountry(int id, int countryID) throws SQLException { - DatabaseConnection.createStatement("INSERT plotsystem_buildteam_has_countries SET country_id = ?, buildteam_id = ?") - .setValue(countryID) - .setValue(id).executeUpdate(); + public static void addCountry(int id, int countryID) throws DataException { + PlotSystem.getDataProvider().getBuildTeamProvider().addCountry(id, countryID); } - public static void removeCountry(int id, int countryID) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteam_has_countries WHERE country_id = ? AND buildteam_id = ?") - .setValue(countryID) - .setValue(id).executeUpdate(); + public static void removeCountry(int id, int countryID) throws DataException { + PlotSystem.getDataProvider().getBuildTeamProvider().removeCountry(id, countryID); } - public static void addReviewer(int id, String reviewerUUID) throws SQLException { - DatabaseConnection.createStatement("INSERT plotsystem_builder_is_reviewer SET builder_uuid = ?, buildteam_id = ?") - .setValue(reviewerUUID) - .setValue(id).executeUpdate(); + public static void removeReviewer(int id, String reviewerUUID) throws SQLException { + PlotSystem.getDataProvider().getBuildTeamProvider().removeReviewer(id, reviewerUUID); } - public static void removeReviewer(int id, String reviewerUUID) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ? AND buildteam_id = ?") - .setValue(reviewerUUID) - .setValue(id).executeUpdate(); + public static void addReviewer(int id, String reviewerUUID) throws DataException { + PlotSystem.getDataProvider().getBuildTeamProvider().addReviewer(id, reviewerUUID); } } From a641300b2987cfe6e3b5c68379086a30fef8c2ac Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 16 Jan 2025 20:23:39 +0100 Subject: [PATCH 003/175] remove interface abstraction --- .../com/alpsbte/plotsystem/PlotSystem.java | 12 -- .../admin/setup/CMD_Setup_BuildTeam.java | 5 +- .../core/data/BuildTeamProvider.java | 23 ---- .../plotsystem/core/data/BuilderProvider.java | 36 ------ .../plotsystem/core/data/DataException.java | 7 - .../plotsystem/core/data/DataProvider.java | 6 - .../core/database/BuildTeamProviderSql.java | 114 +++++------------ .../core/database/BuilderProviderSql.java | 121 +++++------------- .../core/database/DataProvider.java | 6 + .../core/database/DataProviderSql.java | 24 ---- .../core/holograms/PlotsLeaderboard.java | 4 +- .../core/holograms/ScoreLeaderboard.java | 5 +- .../core/menus/PlayerPlotsMenu.java | 3 +- .../plotsystem/core/menus/ReviewMenu.java | 3 +- .../plotsystem/core/system/BuildTeam.java | 45 ++++--- .../plotsystem/core/system/Builder.java | 75 ++++++----- .../plot/generator/DefaultPlotGenerator.java | 3 +- 17 files changed, 136 insertions(+), 356 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/DataException.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index e9e1522a..7da8e0c8 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -25,8 +25,6 @@ package com.alpsbte.plotsystem; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; -import com.alpsbte.plotsystem.core.data.DataProvider; -import com.alpsbte.plotsystem.core.database.DataProviderSql; import com.alpsbte.plotsystem.core.holograms.HologramRegister; import com.alpsbte.alpslib.io.YamlFileFactory; import com.alpsbte.alpslib.io.config.ConfigNotImplementedException; @@ -76,7 +74,6 @@ public class PlotSystem extends JavaPlugin { private static final String VERSION = "4.0"; private static PlotSystem plugin; - private static DataProvider dataProvider; private CommandManager commandManager; private boolean pluginEnabled = false; @@ -142,10 +139,6 @@ public void onEnable() { return; } - // Set data provider - //TODO: get from config - dataProvider = new DataProviderSql(); - // Register event listeners try { this.getServer().getPluginManager().registerEvents(new EventListener(), this); @@ -274,11 +267,6 @@ public void saveConfig() { public static PlotSystem getPlugin() { return plugin; } - - public static DataProvider getDataProvider() { - return dataProvider; - } - public CommandManager getCommandManager() { return commandManager; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 070a12cd..3212aa1f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -28,7 +28,6 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; @@ -104,9 +103,9 @@ public void onCommand(CommandSender sender, String[] args) { StringJoiner countriesAsString = new StringJoiner(", "); StringJoiner reviewersAsString = new StringJoiner(", "); b.getCountries().forEach(c -> countriesAsString.add(String.valueOf(c.getID()))); - b.getReviewers().forEach(r -> {try {reviewersAsString.add(r.getName());} catch (DataException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex);}}); + b.getReviewers().forEach(r -> {try {reviewersAsString.add(r.getName());} catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex);}}); sender.sendMessage(" §6> §b" + b.getID() + " (" + b.getName() + ") §f- Country IDs: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString)); - } catch (DataException ex) { + } catch (SQLException ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java deleted file mode 100644 index d518d657..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/data/BuildTeamProvider.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.alpsbte.plotsystem.core.data; - -import com.alpsbte.plotsystem.core.system.BuildTeam; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Country; - -import java.util.List; -import java.util.UUID; - -public interface BuildTeamProvider { - String getName(int id) throws DataException; - List getCountries(int id) throws DataException; - List getReviewers(int id) throws DataException; - List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataException; - List getBuildTeams(); - void addBuildTeam(String name) throws DataException; - void removeBuildTeam(int serverId) throws DataException; - void setBuildTeamName(int id, String newName) throws DataException; - void addCountry(int id, int countryId) throws DataException; - void removeCountry(int id, int countryId) throws DataException; - void addReviewer(int id, String reviewerUUID) throws DataException; - void removeReviewer(int id, String reviewerUUID) throws DataException; -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java deleted file mode 100644 index 3db26a33..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/data/BuilderProvider.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.alpsbte.plotsystem.core.data; - -import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; -import com.alpsbte.plotsystem.core.system.BuildTeam; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Country; -import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; -import com.alpsbte.plotsystem.utils.enums.Slot; - -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - - -public interface BuilderProvider { - String getName(UUID uuid) throws DataException; - int getScore(UUID uuid) throws DataException; - int getCompletedBuildsCount(UUID uuid) throws DataException; - Slot getFreeSlot(UUID uuid) throws DataException; - Plot getPlot(UUID uuid, Slot slot) throws DataException; - void addScore(UUID uuid, int score) throws DataException; - void addCompletedBuild(UUID uuid, int amount) throws DataException; - void setPlot(UUID uuid, int plotID, Slot slot) throws DataException; - void removePlot(UUID uuid, Slot slot) throws DataException; - Builder getBuilderByName(String name) throws DataException; - PlotType getPlotTypeSetting(UUID uuid); - void setPlotTypeSetting(UUID uuid, PlotType plotType); - boolean isReviewer(UUID uuid) throws DataException; - List getReviewerCountries(List buildTeams); - int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; - int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; - int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; - HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException; - HashMap getLeaderboardEntriesByCompletedBuilds(int limit) throws DataException; -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/DataException.java b/src/main/java/com/alpsbte/plotsystem/core/data/DataException.java deleted file mode 100644 index e7f7b59a..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/data/DataException.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.alpsbte.plotsystem.core.data; - -public class DataException extends RuntimeException { - public DataException(String message) { - super(message); - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java deleted file mode 100644 index d1dfe681..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/data/DataProvider.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.alpsbte.plotsystem.core.data; - -public interface DataProvider { - BuilderProvider getBuilderProvider(); - BuildTeamProvider getBuildTeamProvider(); -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java index a0512ba6..739406b2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java @@ -1,8 +1,6 @@ package com.alpsbte.plotsystem.core.database; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.BuildTeamProvider; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; @@ -15,22 +13,18 @@ import static net.kyori.adventure.text.Component.text; -public class BuildTeamProviderSql implements BuildTeamProvider { - @Override - public String getName(int id) throws DataException { +public class BuildTeamProviderSql { + public String getName(int id) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_buildteams WHERE id = ?") .setValue(id).executeQuery()) { if (rs.next()) return rs.getString(1); DatabaseConnection.closeResultSet(rs); - } catch (SQLException e) { - throw new DataException(e.getMessage()); } return null; } - @Override - public List getCountries(int id) throws DataException { + public List getCountries(int id) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT country_id FROM plotsystem_buildteam_has_countries WHERE buildteam_id = ?") .setValue(id).executeQuery()) { @@ -38,13 +32,10 @@ public List getCountries(int id) throws DataException { while (rs.next()) countries.add(new Country(rs.getInt(1))); DatabaseConnection.closeResultSet(rs); return countries; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public List getReviewers(int id) throws DataException { + public List getReviewers(int id) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT builder_uuid FROM plotsystem_builder_is_reviewer WHERE buildteam_id = ?") .setValue(id).executeQuery()) { @@ -52,13 +43,10 @@ public List getReviewers(int id) throws DataException { while (rs.next()) builders.add(Builder.byUUID(UUID.fromString(rs.getString(1)))); DatabaseConnection.closeResultSet(rs); return builders; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataException { + public List getBuildTeamsByReviewer(UUID reviewerUUID) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT buildteam_id FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") .setValue(reviewerUUID.toString()).executeQuery()) { @@ -66,12 +54,9 @@ public List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataExc while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1))); DatabaseConnection.closeResultSet(rs); return buildTeams; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override public List getBuildTeams() { List buildTeams = new ArrayList<>(); try (ResultSet rs = DatabaseConnection.createStatement("SELECT id, name FROM plotsystem_buildteams").executeQuery()) { @@ -83,80 +68,45 @@ public List getBuildTeams() { return buildTeams; } - @Override - public void addBuildTeam(String name) throws DataException { + public void addBuildTeam(String name) throws SQLException { int id = DatabaseConnection.getTableID("plotsystem_buildteams"); - try { - DatabaseConnection.createStatement("INSERT INTO plotsystem_buildteams (id, name) VALUES (?, ?)") - .setValue(id) - .setValue(name).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + DatabaseConnection.createStatement("INSERT INTO plotsystem_buildteams (id, name) VALUES (?, ?)") + .setValue(id) + .setValue(name).executeUpdate(); } - @Override - public void removeBuildTeam(int serverId) throws DataException { - try { - DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteams WHERE id = ?") - .setValue(serverId).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void removeBuildTeam(int serverId) throws SQLException { + DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteams WHERE id = ?") + .setValue(serverId).executeUpdate(); } - @Override - public void setBuildTeamName(int id, String newName) throws DataException { - try { - DatabaseConnection.createStatement("UPDATE plotsystem_buildteams SET name = ? WHERE id = ?") - .setValue(newName) - .setValue(id).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void setBuildTeamName(int id, String newName) throws SQLException { + DatabaseConnection.createStatement("UPDATE plotsystem_buildteams SET name = ? WHERE id = ?") + .setValue(newName) + .setValue(id).executeUpdate(); } - @Override - public void addCountry(int id, int countryId) throws DataException { - try { - DatabaseConnection.createStatement("INSERT plotsystem_buildteam_has_countries SET country_id = ?, buildteam_id = ?") - .setValue(countryId) - .setValue(id).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void addCountry(int id, int countryId) throws SQLException { + DatabaseConnection.createStatement("INSERT plotsystem_buildteam_has_countries SET country_id = ?, buildteam_id = ?") + .setValue(countryId) + .setValue(id).executeUpdate(); } - @Override - public void removeCountry(int id, int countryId) throws DataException { - try { - DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteam_has_countries WHERE country_id = ? AND buildteam_id = ?") - .setValue(countryId) - .setValue(id).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void removeCountry(int id, int countryId) throws SQLException { + DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteam_has_countries WHERE country_id = ? AND buildteam_id = ?") + .setValue(countryId) + .setValue(id).executeUpdate(); } - @Override - public void addReviewer(int id, String reviewerUUID) throws DataException { - try { - DatabaseConnection.createStatement("INSERT plotsystem_builder_is_reviewer SET builder_uuid = ?, buildteam_id = ?") - .setValue(reviewerUUID) - .setValue(id).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void addReviewer(int id, String reviewerUUID) throws SQLException { + DatabaseConnection.createStatement("INSERT plotsystem_builder_is_reviewer SET builder_uuid = ?, buildteam_id = ?") + .setValue(reviewerUUID) + .setValue(id).executeUpdate(); } - @Override - public void removeReviewer(int id, String reviewerUUID) throws DataException { - try { - DatabaseConnection.createStatement("DELETE FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ? AND buildteam_id = ?") - .setValue(reviewerUUID) - .setValue(id).executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void removeReviewer(int id, String reviewerUUID) throws SQLException { + DatabaseConnection.createStatement("DELETE FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ? AND buildteam_id = ?") + .setValue(reviewerUUID) + .setValue(id).executeUpdate(); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java index bdffdd33..6b3fa3f0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java @@ -2,12 +2,10 @@ import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.holograms.PlotsLeaderboard; import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.data.BuilderProvider; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; @@ -22,9 +20,8 @@ import static net.kyori.adventure.text.Component.text; -public class BuilderProviderSql implements BuilderProvider { - @Override - public String getName(UUID uuid) throws DataException { +public class BuilderProviderSql { + public String getName(UUID uuid) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_builders WHERE uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -38,13 +35,10 @@ public String getName(UUID uuid) throws DataException { Player p = Bukkit.getPlayer(uuid); return p != null ? p.getName() : ""; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public int getScore(UUID uuid) { + public int getScore(UUID uuid) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT score FROM plotsystem_builders WHERE uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -56,13 +50,10 @@ public int getScore(UUID uuid) { DatabaseConnection.closeResultSet(rs); return 0; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public int getCompletedBuildsCount(UUID uuid) { + public int getCompletedBuildsCount(UUID uuid) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT completed_plots FROM plotsystem_builders WHERE uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -74,13 +65,10 @@ public int getCompletedBuildsCount(UUID uuid) { DatabaseConnection.closeResultSet(rs); return 0; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public Slot getFreeSlot(UUID uuid) { + public Slot getFreeSlot(UUID uuid) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT first_slot, second_slot, third_slot FROM plotsystem_builders WHERE uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -95,13 +83,10 @@ public Slot getFreeSlot(UUID uuid) { DatabaseConnection.closeResultSet(rs); return null; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public Plot getPlot(UUID uuid, Slot slot) throws DataException { + public Plot getPlot(UUID uuid, Slot slot) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT " + slot.name().toLowerCase() + " FROM plotsystem_builders WHERE uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -112,65 +97,42 @@ public Plot getPlot(UUID uuid, Slot slot) throws DataException { DatabaseConnection.closeResultSet(rs); return boo ? null : new Plot(plotID); - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public void addScore(UUID uuid, int score) throws DataException { - try { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET score = ? WHERE uuid = ?") - .setValue(getScore(uuid) + score).setValue(uuid.toString()) - .executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void addScore(UUID uuid, int score) throws SQLException { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET score = ? WHERE uuid = ?") + .setValue(getScore(uuid) + score).setValue(uuid.toString()) + .executeUpdate(); Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() .filter(leaderboard -> leaderboard instanceof ScoreLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); } - @Override - public void addCompletedBuild(UUID uuid, int amount) throws DataException { - try { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET completed_plots = ? WHERE uuid = ?") - .setValue(getCompletedBuildsCount(uuid) + amount).setValue(uuid.toString()) - .executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void addCompletedBuild(UUID uuid, int amount) throws SQLException { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET completed_plots = ? WHERE uuid = ?") + .setValue(getCompletedBuildsCount(uuid) + amount).setValue(uuid.toString()) + .executeUpdate(); Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() .filter(leaderboard -> leaderboard instanceof PlotsLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); } - @Override - public void setPlot(UUID uuid, int plotID, Slot slot) throws DataException { - try { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = ? WHERE uuid = ?") - .setValue(plotID).setValue(uuid.toString()) - .executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + public void setPlot(UUID uuid, int plotID, Slot slot) throws SQLException { + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = ? WHERE uuid = ?") + .setValue(plotID).setValue(uuid.toString()) + .executeUpdate(); } - @Override - public void removePlot(UUID uuid, Slot slot) throws DataException { + public void removePlot(UUID uuid, Slot slot) throws SQLException { if (slot != null) { // If not null, plot is already removed from player slot - try { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = DEFAULT(first_slot) WHERE uuid = ?") - .setValue(uuid.toString()) - .executeUpdate(); - } catch (SQLException e) { - throw new DataException(e.getMessage()); - } + DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = DEFAULT(first_slot) WHERE uuid = ?") + .setValue(uuid.toString()) + .executeUpdate(); } } - @Override - public Builder getBuilderByName(String name) throws DataException { + public Builder getBuilderByName(String name) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT uuid FROM plotsystem_builders WHERE name = ?") .setValue(name).executeQuery()) { @@ -182,12 +144,9 @@ public Builder getBuilderByName(String name) throws DataException { DatabaseConnection.closeResultSet(rs); return null; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override public PlotType getPlotTypeSetting(UUID uuid) { try (ResultSet rs = DatabaseConnection.createStatement("SELECT setting_plot_type FROM plotsystem_builders WHERE uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -206,7 +165,6 @@ public PlotType getPlotTypeSetting(UUID uuid) { return null; } - @Override public void setPlotTypeSetting(UUID uuid, PlotType plotType) { try { if (plotType == null) { @@ -222,8 +180,7 @@ public void setPlotTypeSetting(UUID uuid, PlotType plotType) { } } - @Override - public boolean isReviewer(UUID uuid) throws DataException { + public boolean isReviewer(UUID uuid) throws SQLException{ try (ResultSet rs = DatabaseConnection.createStatement("SELECT COUNT(builder_uuid) FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") .setValue(uuid.toString()).executeQuery()) { @@ -231,18 +188,15 @@ public boolean isReviewer(UUID uuid) throws DataException { if (rs.next()) count = rs.getInt(1); DatabaseConnection.closeResultSet(rs); return count > 0; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override public List getReviewerCountries(List buildTeams) { Set countries = new HashSet<>(); buildTeams.forEach(b -> { try { countries.addAll(b.getCountries().stream().map(Country::getID).collect(Collectors.toList())); - } catch (DataException ex) { + } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } }); @@ -255,8 +209,7 @@ public List getReviewerCountries(List buildTeams) { }).collect(Collectors.toList()); } - @Override - public int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + public int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { String query = getLeaderboardScoreQuery(sortBy, 0); try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { @@ -273,13 +226,10 @@ public int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe DatabaseConnection.closeResultSet(rs); return score; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + public int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { String query = getLeaderboardScoreQuery(sortBy, 0); try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { @@ -296,13 +246,10 @@ public int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimefra DatabaseConnection.closeResultSet(rs); return position; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + public int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { String query = "SELECT COUNT(*) FROM (" + getLeaderboardScoreQuery(sortBy, 0) + ") results"; try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { @@ -311,13 +258,10 @@ public int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy DatabaseConnection.closeResultSet(rs); return position; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { + public HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { String query = getLeaderboardScoreQuery(sortBy, 10); try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { @@ -329,13 +273,10 @@ public HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.Le DatabaseConnection.closeResultSet(rs); return lines; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } - @Override - public HashMap getLeaderboardEntriesByCompletedBuilds(int limit) throws DataException { + public HashMap getLeaderboardEntriesByCompletedBuilds(int limit) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT name, completed_plots FROM plotsystem_builders ORDER BY completed_plots DESC LIMIT ?") .setValue(limit).executeQuery()) { @@ -346,8 +287,6 @@ public HashMap getLeaderboardEntriesByCompletedBuilds(int limit DatabaseConnection.closeResultSet(rs); return results; - } catch (SQLException e) { - throw new DataException(e.getMessage()); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java new file mode 100644 index 00000000..6c452593 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -0,0 +1,6 @@ +package com.alpsbte.plotsystem.core.database; + +public class DataProvider { + public static BuilderProviderSql BUILDER = new BuilderProviderSql(); + public static BuildTeamProviderSql BUILD_TEAM = new BuildTeamProviderSql(); +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java deleted file mode 100644 index b01a7c53..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProviderSql.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.alpsbte.plotsystem.core.database; - -import com.alpsbte.plotsystem.core.data.BuildTeamProvider; -import com.alpsbte.plotsystem.core.data.BuilderProvider; -import com.alpsbte.plotsystem.core.data.DataProvider; - -public class DataProviderSql implements DataProvider { - private final BuilderProvider builderProvider; - private final BuildTeamProvider buildTeamProvider; - - public DataProviderSql() { - builderProvider = new BuilderProviderSql(); - buildTeamProvider = new BuildTeamProviderSql(); - } - @Override - public BuilderProvider getBuilderProvider() { - return builderProvider; - } - - @Override - public BuildTeamProvider getBuildTeamProvider() { - return buildTeamProvider; - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java index cdd7f87f..f8ea20db 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java @@ -26,12 +26,12 @@ import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.items.BaseItems; import org.bukkit.inventory.ItemStack; +import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -67,7 +67,7 @@ public List> getContent(UUID playerUUID) { } return lines; - } catch (DataException ex) { + } catch (SQLException ex) { PlotSystem.getPlugin().getLogger().log(Level.SEVERE, "An error occurred while reading leaderboard content", ex); } return new ArrayList<>(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java index 37ae1897..309e2e77 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java @@ -26,7 +26,6 @@ import com.alpsbte.alpslib.hologram.DecentHologramPagedDisplay; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Payout; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; @@ -129,7 +128,7 @@ public List> getContent(UUID playerUUID) { } return lines; - } catch (DataException ex) { + } catch (SQLException ex) { PlotSystem.getPlugin().getLogger().log(Level.SEVERE, "An error occurred while reading leaderboard content", ex); } return new ArrayList<>(); @@ -141,7 +140,7 @@ private Component getRankingString(Player player) { position = Builder.getBuilderScorePosition(player.getUniqueId(), sortByLeaderboard); rows = Builder.getBuildersInSort(sortByLeaderboard); myScore = Builder.getBuilderScore(player.getUniqueId(), sortByLeaderboard); - } catch (DataException ex) { + } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(Component.text("A SQL error occurred!"), ex); return Component.empty(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index d1f642c4..d2ca2eeb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -27,7 +27,6 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -89,7 +88,7 @@ protected void setMenuItemsAsync() { .append(text(builder.getCompletedBuilds(), WHITE))) .build()) .build()); - } catch (DataException ex) { + } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex); getMenu().getSlot(4).setItem(MenuItems.errorItem(getMenuPlayer())); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 0041ea73..03b40ed7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -27,7 +27,6 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -95,7 +94,7 @@ protected void setPaginatedMenuItemsAsync(List source) { lines.add(""); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER) + ": §f" + plot.getPlotOwner().getName()); if (!plot.getPlotMembers().isEmpty()) lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBERS) + ": §f" + plot.getPlotMembers().stream().map(m -> { - try {return m.getName();} catch (DataException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} + try {return m.getName();} catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} return ""; }).collect(Collectors.joining(", ")) ); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 6852aa8e..a1954806 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -24,8 +24,7 @@ package com.alpsbte.plotsystem.core.system; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; +import com.alpsbte.plotsystem.core.database.DataProvider; import java.sql.SQLException; import java.util.List; @@ -37,7 +36,7 @@ public class BuildTeam { public BuildTeam(int ID) throws SQLException { this.ID = ID; - this.name = PlotSystem.getDataProvider().getBuildTeamProvider().getName(ID); + this.name = DataProvider.BUILD_TEAM.getName(ID); } public BuildTeam(int ID, String name) { @@ -53,47 +52,47 @@ public String getName() { return name; } - public List getCountries() throws DataException { - return PlotSystem.getDataProvider().getBuildTeamProvider().getCountries(ID); + public List getCountries() throws SQLException { + return DataProvider.BUILD_TEAM.getCountries(ID); } - public List getReviewers() throws DataException { - return PlotSystem.getDataProvider().getBuildTeamProvider().getReviewers(ID); + public List getReviewers() throws SQLException { + return DataProvider.BUILD_TEAM.getReviewers(ID); } - public static List getBuildTeamsByReviewer(UUID reviewerUUID) throws DataException { - return PlotSystem.getDataProvider().getBuildTeamProvider().getBuildTeamsByReviewer(reviewerUUID); + public static List getBuildTeamsByReviewer(UUID reviewerUUID) throws SQLException { + return DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(reviewerUUID); } public static List getBuildTeams() { - return PlotSystem.getDataProvider().getBuildTeamProvider().getBuildTeams(); + return DataProvider.BUILD_TEAM.getBuildTeams(); } - public static void addBuildTeam(String name) throws DataException { - PlotSystem.getDataProvider().getBuildTeamProvider().addBuildTeam(name); + public static void addBuildTeam(String name) throws SQLException { + DataProvider.BUILD_TEAM.addBuildTeam(name); } - public static void removeBuildTeam(int serverID) throws DataException { - PlotSystem.getDataProvider().getBuildTeamProvider().removeBuildTeam(serverID); + public static void removeBuildTeam(int serverID) throws SQLException { + DataProvider.BUILD_TEAM.removeBuildTeam(serverID); } - public static void setBuildTeamName(int id, String newName) throws DataException { - PlotSystem.getDataProvider().getBuildTeamProvider().setBuildTeamName(id, newName); + public static void setBuildTeamName(int id, String newName) throws SQLException { + DataProvider.BUILD_TEAM.setBuildTeamName(id, newName); } - public static void addCountry(int id, int countryID) throws DataException { - PlotSystem.getDataProvider().getBuildTeamProvider().addCountry(id, countryID); + public static void addCountry(int id, int countryID) throws SQLException { + DataProvider.BUILD_TEAM.addCountry(id, countryID); } - public static void removeCountry(int id, int countryID) throws DataException { - PlotSystem.getDataProvider().getBuildTeamProvider().removeCountry(id, countryID); + public static void removeCountry(int id, int countryID) throws SQLException { + DataProvider.BUILD_TEAM.removeCountry(id, countryID); } public static void removeReviewer(int id, String reviewerUUID) throws SQLException { - PlotSystem.getDataProvider().getBuildTeamProvider().removeReviewer(id, reviewerUUID); + DataProvider.BUILD_TEAM.removeReviewer(id, reviewerUUID); } - public static void addReviewer(int id, String reviewerUUID) throws DataException { - PlotSystem.getDataProvider().getBuildTeamProvider().addReviewer(id, reviewerUUID); + public static void addReviewer(int id, String reviewerUUID) throws SQLException { + DataProvider.BUILD_TEAM.addReviewer(id, reviewerUUID); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 7d4d1753..0fca443b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -26,8 +26,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; @@ -75,24 +74,24 @@ public java.util.UUID getUUID() { public boolean isOnline() {return Bukkit.getPlayer(uuid) != null;} - public String getName() throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getName(uuid); + public String getName() throws SQLException { + return DataProvider.BUILDER.getName(uuid); } - public int getScore() throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getScore(uuid); + public int getScore() throws SQLException { + return DataProvider.BUILDER.getScore(uuid); } - public int getCompletedBuilds() throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getCompletedBuildsCount(uuid); + public int getCompletedBuilds() throws SQLException { + return DataProvider.BUILDER.getCompletedBuildsCount(uuid); } - public Slot getFreeSlot() throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getFreeSlot(uuid); + public Slot getFreeSlot() throws SQLException { + return DataProvider.BUILDER.getFreeSlot(uuid); } - public Plot getPlot(Slot slot) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getPlot(uuid, slot); + public Plot getPlot(Slot slot) throws SQLException { + return DataProvider.BUILDER.getPlot(uuid, slot); } public ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) throws SQLException { @@ -127,47 +126,47 @@ public ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) th .build(); } - public void addScore(int score) throws DataException { - PlotSystem.getDataProvider().getBuilderProvider().addScore(uuid, score); + public void addScore(int score) throws SQLException { + DataProvider.BUILDER.addScore(uuid, score); } - public void addCompletedBuild(int amount) throws DataException { - PlotSystem.getDataProvider().getBuilderProvider().addCompletedBuild(uuid, amount); + public void addCompletedBuild(int amount) throws SQLException { + DataProvider.BUILDER.addCompletedBuild(uuid, amount); } - public void setPlot(int plotID, Slot slot) throws DataException { - PlotSystem.getDataProvider().getBuilderProvider().setPlot(uuid, plotID, slot); + public void setPlot(int plotID, Slot slot) throws SQLException { + DataProvider.BUILDER.setPlot(uuid, plotID, slot); } - public void removePlot(Slot slot) throws DataException { - PlotSystem.getDataProvider().getBuilderProvider().removePlot(uuid, slot); + public void removePlot(Slot slot) throws SQLException { + DataProvider.BUILDER.removePlot(uuid, slot); } - public static Builder getBuilderByName(String name) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getBuilderByName(name); + public static Builder getBuilderByName(String name) throws SQLException { + return DataProvider.BUILDER.getBuilderByName(name); } - public static int getBuilderScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardScore(uuid, sortBy); + public static int getBuilderScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { + return DataProvider.BUILDER.getLeaderboardScore(uuid, sortBy); } - public static int getBuilderScorePosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardPosition(uuid, sortBy); + public static int getBuilderScorePosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { + return DataProvider.BUILDER.getLeaderboardPosition(uuid, sortBy); } - public static int getBuildersInSort(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardEntryCount(sortBy); + public static int getBuildersInSort(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { + return DataProvider.BUILDER.getLeaderboardEntryCount(sortBy); } - public static HashMap getBuildersByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardEntriesByScore(sortBy); + public static HashMap getBuildersByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { + return DataProvider.BUILDER.getLeaderboardEntriesByScore(sortBy); } - public static HashMap getBuildersByCompletedBuilds(int limit) throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().getLeaderboardEntriesByCompletedBuilds(limit); + public static HashMap getBuildersByCompletedBuilds(int limit) throws SQLException { + return DataProvider.BUILDER.getLeaderboardEntriesByCompletedBuilds(limit); } - public Slot getSlot(Plot plot) throws DataException { + public Slot getSlot(Plot plot) throws SQLException { for (Slot slot : Slot.values()) { Plot slotPlot = getPlot(slot); if (slotPlot != null && slotPlot.getID() == plot.getID()) { @@ -180,12 +179,12 @@ public Slot getSlot(Plot plot) throws DataException { public PlotType getPlotTypeSetting() { if (plotType != null) return plotType; - this.plotType = PlotSystem.getDataProvider().getBuilderProvider().getPlotTypeSetting(uuid); + this.plotType = DataProvider.BUILDER.getPlotTypeSetting(uuid); return plotType; } public void setPlotTypeSetting(PlotType plotType) { - PlotSystem.getDataProvider().getBuilderProvider().setPlotTypeSetting(uuid, plotType); + DataProvider.BUILDER.setPlotTypeSetting(uuid, plotType); this.plotType = plotType; } @@ -193,8 +192,8 @@ public Reviewer getAsReviewer() throws SQLException { return new Reviewer(getUUID()); } - public boolean isReviewer() throws DataException { - return PlotSystem.getDataProvider().getBuilderProvider().isReviewer(uuid); + public boolean isReviewer() throws SQLException { + return DataProvider.BUILDER.isReviewer(uuid); } public static class Reviewer { @@ -204,7 +203,7 @@ public Reviewer(UUID reviewerUUID) throws SQLException { } public List getCountries() { - return PlotSystem.getDataProvider().getBuilderProvider().getReviewerCountries(buildTeams); + return DataProvider.BUILDER.getReviewerCountries(buildTeams); } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index c7f99241..363f95b3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.data.DataException; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -89,7 +88,7 @@ protected boolean init() { getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Error.ALL_SLOTS_OCCUPIED))); getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); } - } catch (DataException ex) { + } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex); } return false; From e518344468859e8e25042b3f6ac23be124d76945 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sun, 19 Jan 2025 22:54:01 +0100 Subject: [PATCH 004/175] update Builder and BuilderProvider --- pom.xml | 2 +- .../plotsystem/commands/CMD_Plots.java | 2 +- .../admin/setup/CMD_Setup_BuildTeam.java | 4 +- .../core/database/BuilderProviderSql.java | 325 ------------------ .../core/database/DataProvider.java | 4 +- .../core/database/DatabaseConnection.java | 14 +- .../database/providers/BuilderProvider.java | 276 +++++++++++++++ .../core/holograms/HologramRegister.java | 4 +- .../leaderboards/LeaderboardEntry.java | 25 ++ .../leaderboards/LeaderboardTimeframe.java | 20 ++ .../{ => leaderboards}/ScoreLeaderboard.java | 152 ++++---- .../core/menus/PlayerPlotsMenu.java | 2 +- .../plotsystem/core/menus/PlotTypeMenu.java | 10 +- .../plotsystem/core/menus/ReviewPlotMenu.java | 6 +- .../core/menus/companion/CompanionMenu.java | 37 +- .../plotsystem/core/system/Builder.java | 189 ++++------ .../plotsystem/core/system/Payout.java | 15 +- .../plotsystem/core/system/Review.java | 6 +- .../plotsystem/core/system/plot/Plot.java | 4 +- .../plot/generator/AbstractPlotGenerator.java | 2 +- .../plot/generator/DefaultPlotGenerator.java | 4 +- .../core/system/plot/utils/PlotUtils.java | 4 +- 22 files changed, 529 insertions(+), 578 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java rename src/main/java/com/alpsbte/plotsystem/core/holograms/{ => leaderboards}/ScoreLeaderboard.java (63%) diff --git a/pom.xml b/pom.xml index 9619af4e..c1a77602 100644 --- a/pom.xml +++ b/pom.xml @@ -123,7 +123,7 @@ com.alpsbte.alpslib alpslib-utils - 1.1.1 + 1.3.4 compile diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java index 7021c9c2..a8aa741a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java @@ -63,7 +63,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - Builder builder = Builder.getBuilderByName(args[0]); + Builder builder = Builder.byName(args[0]); if (builder == null) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); return true; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 3212aa1f..bf739fed 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -383,7 +383,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team exits try { if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - Builder builder = Builder.getBuilderByName(args[2]); + Builder builder = Builder.byName(args[2]); if (builder == null || BuildTeam.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == Integer.parseInt(args[1]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is already reviewer for this build team!")); return; @@ -430,7 +430,7 @@ public void onCommand(CommandSender sender, String[] args) { try { if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - Builder builder = Builder.getBuilderByName(args[2]); + Builder builder = Builder.byName(args[2]); if (builder == null || BuildTeam.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is not a reviewer for this build team!")); return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java deleted file mode 100644 index 6b3fa3f0..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/database/BuilderProviderSql.java +++ /dev/null @@ -1,325 +0,0 @@ -package com.alpsbte.plotsystem.core.database; - -import com.alpsbte.alpslib.hologram.DecentHologramDisplay; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.holograms.PlotsLeaderboard; -import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; -import com.alpsbte.plotsystem.core.system.BuildTeam; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Country; -import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; -import com.alpsbte.plotsystem.utils.enums.Slot; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; -import java.util.stream.Collectors; - -import static net.kyori.adventure.text.Component.text; - -public class BuilderProviderSql { - public String getName(UUID uuid) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_builders WHERE uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return s; - } - - DatabaseConnection.closeResultSet(rs); - - Player p = Bukkit.getPlayer(uuid); - return p != null ? p.getName() : ""; - } - } - - public int getScore(UUID uuid) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT score FROM plotsystem_builders WHERE uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } - } - - public int getCompletedBuildsCount(UUID uuid) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT completed_plots FROM plotsystem_builders WHERE uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } - } - - public Slot getFreeSlot(UUID uuid) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT first_slot, second_slot, third_slot FROM plotsystem_builders WHERE uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - if (rs.next()) { - for (int i = 1; i <= 3; i++) { - if (rs.getString(i) == null) { - DatabaseConnection.closeResultSet(rs); - return Slot.values()[i - 1]; - } - } - } - - DatabaseConnection.closeResultSet(rs); - return null; - } - } - - public Plot getPlot(UUID uuid, Slot slot) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT " + slot.name().toLowerCase() + " FROM plotsystem_builders WHERE uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - int plotID = -1; - if (rs.next()) plotID = rs.getInt(1); - - boolean boo = rs.wasNull(); - DatabaseConnection.closeResultSet(rs); - - return boo ? null : new Plot(plotID); - } - } - - public void addScore(UUID uuid, int score) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET score = ? WHERE uuid = ?") - .setValue(getScore(uuid) + score).setValue(uuid.toString()) - .executeUpdate(); - - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() - .filter(leaderboard -> leaderboard instanceof ScoreLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); - } - - public void addCompletedBuild(UUID uuid, int amount) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET completed_plots = ? WHERE uuid = ?") - .setValue(getCompletedBuildsCount(uuid) + amount).setValue(uuid.toString()) - .executeUpdate(); - - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> DecentHologramDisplay.activeDisplays.stream() - .filter(leaderboard -> leaderboard instanceof PlotsLeaderboard).findFirst().ifPresent(DecentHologramDisplay::reloadAll)); - } - - public void setPlot(UUID uuid, int plotID, Slot slot) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = ? WHERE uuid = ?") - .setValue(plotID).setValue(uuid.toString()) - .executeUpdate(); - } - - public void removePlot(UUID uuid, Slot slot) throws SQLException { - if (slot != null) { // If not null, plot is already removed from player slot - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET " + slot.name().toLowerCase() + " = DEFAULT(first_slot) WHERE uuid = ?") - .setValue(uuid.toString()) - .executeUpdate(); - } - } - - public Builder getBuilderByName(String name) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT uuid FROM plotsystem_builders WHERE name = ?") - .setValue(name).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return Builder.byUUID(UUID.fromString(s)); - } - - DatabaseConnection.closeResultSet(rs); - return null; - } - } - - public PlotType getPlotTypeSetting(UUID uuid) { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT setting_plot_type FROM plotsystem_builders WHERE uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - if (rs.next()) { - int id = rs.getInt(1); - PlotType plotType = PlotType.byId(id); - DatabaseConnection.closeResultSet(rs); - - return plotType; - } - DatabaseConnection.closeResultSet(rs); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while getting language setting from database"), ex); - } - return null; - } - - public void setPlotTypeSetting(UUID uuid, PlotType plotType) { - try { - if (plotType == null) { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET setting_plot_type = DEFAULT(setting_plot_type) WHERE uuid = ?") - .setValue(uuid.toString()).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET setting_plot_type = ? WHERE uuid = ?") - .setValue(plotType.getId()).setValue(uuid.toString()) - .executeUpdate(); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while getting language setting from database"), ex); - } - } - - public boolean isReviewer(UUID uuid) throws SQLException{ - try (ResultSet rs = DatabaseConnection.createStatement("SELECT COUNT(builder_uuid) FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") - .setValue(uuid.toString()).executeQuery()) { - - int count = 0; - if (rs.next()) count = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return count > 0; - } - } - - public List getReviewerCountries(List buildTeams) { - Set countries = new HashSet<>(); - buildTeams.forEach(b -> { - try { - countries.addAll(b.getCountries().stream().map(Country::getID).collect(Collectors.toList())); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - }); - - return countries.stream().map(c -> { - try { - return new Country(c); - } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - return null; - }).collect(Collectors.toList()); - } - - public int getLeaderboardScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = getLeaderboardScoreQuery(sortBy, 0); - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - boolean found = false; - int score = 0; - while (rs.next() && !found) { - if (rs.getString(3).equals(uuid.toString())) { - found = true; - score = rs.getInt(4); - } - } - - if (!found) score = -1; - - DatabaseConnection.closeResultSet(rs); - return score; - } - } - - public int getLeaderboardPosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = getLeaderboardScoreQuery(sortBy, 0); - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - boolean found = false; - int position = 0; - while (rs.next() && !found) { - position++; - if (rs.getString(3).equals(uuid.toString())) { - found = true; - } - } - - if (!found) position = -1; - - DatabaseConnection.closeResultSet(rs); - return position; - } - } - - public int getLeaderboardEntryCount(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = "SELECT COUNT(*) FROM (" + getLeaderboardScoreQuery(sortBy, 0) + ") results"; - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - rs.next(); - int position = rs.getInt(1); - - DatabaseConnection.closeResultSet(rs); - return position; - } - } - - public HashMap getLeaderboardEntriesByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - String query = getLeaderboardScoreQuery(sortBy, 10); - - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - HashMap lines = new HashMap<>(); - - while (rs.next()) { - lines.put(rs.getString(2), rs.getInt(4)); - } - - DatabaseConnection.closeResultSet(rs); - return lines; - } - } - - public HashMap getLeaderboardEntriesByCompletedBuilds(int limit) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name, completed_plots FROM plotsystem_builders ORDER BY completed_plots DESC LIMIT ?") - .setValue(limit).executeQuery()) { - - HashMap results = new HashMap<>(); - while (rs.next()) { - results.put(rs.getString(1), rs.getInt(2)); - } - - DatabaseConnection.closeResultSet(rs); - return results; - } - } - - private String getLeaderboardScoreQuery(ScoreLeaderboard.LeaderboardTimeframe sortBy, int limit) { - String minimumDate = null; - switch (sortBy) { - case DAILY: - minimumDate = "(NOW() - INTERVAL 1 DAY)"; - break; - case WEEKLY: - minimumDate = "(NOW() - INTERVAL 1 WEEK)"; - break; - case MONTHLY: - minimumDate = "(NOW() - INTERVAL 1 MONTH)"; - break; - case YEARLY: - minimumDate = "(NOW() - INTERVAL 1 YEAR)"; - break; - default: - // no limits - break; - } - - // get plot id, owner username, owner uuid, score & date - // sort by score & limit (if set above) by timeframe - return "SELECT plots.id, builders.name, plots.owner_uuid, SUM(plots.score) AS score, reviews.review_date FROM plotsystem_plots AS plots\n" + - "INNER JOIN plotsystem_reviews AS reviews ON plots.review_id = reviews.id\n" + - "INNER JOIN plotsystem_builders AS builders ON builders.uuid = plots.owner_uuid\n" + - (minimumDate != null - ? "WHERE reviews.review_date BETWEEN " + minimumDate + " AND NOW()\n" - : "") + - "GROUP BY plots.owner_uuid \n" + - "ORDER BY score DESC, builders.name\n" + - (limit > 0 ? "LIMIT " + limit : ""); - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 6c452593..0117fea1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -1,6 +1,8 @@ package com.alpsbte.plotsystem.core.database; +import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; + public class DataProvider { - public static BuilderProviderSql BUILDER = new BuilderProviderSql(); + public static BuilderProvider BUILDER = new BuilderProvider(); public static BuildTeamProviderSql BUILD_TEAM = new BuildTeamProviderSql(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index 2acac67a..8a69c7aa 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -74,18 +74,8 @@ public static void InitializeDatabase() throws ClassNotFoundException, SQLExcept createTables(); } - @Deprecated - public static Connection getConnection() { - int retries = 3; - while (retries > 0) { - try { - return dataSource.getConnection(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Database connection failed!"), ex); - } - retries--; - } - return null; + public static Connection getConnection() throws SQLException { + return dataSource.getConnection(); } public static StatementBuilder createStatement(String sql) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java new file mode 100644 index 00000000..38740e0c --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -0,0 +1,276 @@ +package com.alpsbte.plotsystem.core.database.providers; + +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; +import com.alpsbte.plotsystem.utils.enums.Slot; + +import javax.annotation.Nullable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; +import java.util.concurrent.CompletableFuture; + +public class BuilderProvider { + public static final HashMap builders = new HashMap<>(); + + public CompletableFuture getBuilderByUUID(UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + if (builders.containsKey(uuid)) return builders.get(uuid); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT name, score, first_slot, second_slot, third_slot, plot_type " + + "FROM builder WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new Builder(uuid, rs.getString(1), rs.getInt(2), rs.getInt(3), + rs.getInt(4), rs.getInt(5), rs.getInt(6)); + } + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; + }); + } + + public CompletableFuture getBuilderByName(String name) { + return CompletableFuture.supplyAsync(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT uuid FROM builder WHERE name = ?;")) { + stmt.setString(1, name); + + try (ResultSet rs = stmt.executeQuery()) { + return rs.getString(1); + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; + }).thenCompose(uuid -> { + if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); + return null; + }); + } + + public CompletableFuture setName(UUID uuid, String name) { + CompletableFuture.supplyAsync(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder SET name = ? WHERE uuid = ?;")) { + stmt.setString(1, name); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + return true; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; + }); + return null; + } + + public CompletableFuture addScore(UUID uuid, int score) { + CompletableFuture.supplyAsync(() -> { + try { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;")) { + stmt.setInt(1, score); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + return true; + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; + }); + return null; + } + + public CompletableFuture setSlot(UUID uuid, int plotID, Slot slot) { + CompletableFuture.supplyAsync(() -> { + try { + if (plotID > 0) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = ? " + + "WHERE uuid = ?;")) { + stmt.setInt(1, plotID); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + } + } else { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = " + + "DEFAULT(first_slot) WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + stmt.executeUpdate(); + } + } + return true; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; + }); + return null; + } + + public CompletableFuture setPlotType(UUID uuid, int plotTypeId) { + CompletableFuture.supplyAsync(() -> { + try { + if (plotTypeId > 0) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET plot_type = ? WHERE uuid = ?;")) { + stmt.setInt(1, plotTypeId); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + } + } else { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET plot_type = DEFAULT(plot_type) WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + stmt.executeUpdate(); + } + } + return true; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; + }); + return null; + } + + public CompletableFuture getCompletedBuildsCount(UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT COUNT(*) AS completed_plots FROM plot p INNER JOIN builder_has_plot " + + "bhp ON p.plot_id = bhp.plot_id WHERE p.status = 'completed' AND bhp.uuid = ?;")) { + stmt.setString(1, uuid.toString()); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) return rs.getInt(1); + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return 0; + }); + } + + public CompletableFuture getFreeSlot(UUID uuid) { + return CompletableFuture.supplyAsync(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + + try (ResultSet rs = stmt.executeQuery()) { + for (int i = 1; i <= 3; i++) { + if (rs.getString(i) == null) return Slot.values()[i - 1]; + } + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; + }); + } + + /** + * Retrieves the leaderboard entry for a specific player based on their UUID and the specified timeframe. + * The leaderboard entry includes the player's score, rank, and total number of players. + * + * @param uuid the unique identifier of the player. + * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). + * @return provides the leaderboard entry for the player, or null if not found. + */ + public CompletableFuture getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimeframe sortBy) { + CompletableFuture.supplyAsync(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement(getLeaderboardQuery(uuid, sortBy))) { + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new LeaderboardEntry(rs.getInt(2), rs.getInt(3), rs.getInt(4)); + } + } + + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; + }); + return null; + } + + /** + * Retrieves the leaderboard entries for all players within a specified timeframe, including their names and scores. + * + * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). + * @return provides a map of player names and their scores, or null if no data is found. + */ + public CompletableFuture> getLeaderboardEntries(LeaderboardTimeframe sortBy) { + CompletableFuture.supplyAsync(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement(getLeaderboardQuery(null, sortBy))) { + + try (ResultSet rs = stmt.executeQuery()) { + Map playerEntries = new HashMap<>(); + while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); + return playerEntries; + } + + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; + }); + return null; + } + + /** + * Constructs an SQL query to retrieve leaderboard data, optionally filtering by a specific UUID + * and sorting based on a given timeframe. + * + *

If a UUID is provided, the query will calculate the leaderboard position for the specified + * UUID and include the total number of leaderboard entries matching the timeframe criteria. + * If no UUID is provided, the query will return the top leaderboard entries ordered by score + * within the specified timeframe.

+ * + * @param uuid the unique identifier of the builder for which to calculate the leaderboard position. + * If {@code null}, the query retrieves the top entries instead of a specific position. + * @param sortBy the timeframe used to filter entries. Determines the minimum date for reviews + * (e.g., daily, weekly, monthly, yearly). + * @return the constructed SQL query as a {@code String}. + */ + private static String getLeaderboardQuery(@Nullable UUID uuid, LeaderboardTimeframe sortBy) { + String minimumDate = null; + switch (sortBy) { + case DAILY: minimumDate = "(NOW() - INTERVAL 1 DAY)"; break; + case WEEKLY: minimumDate = "(NOW() - INTERVAL 1 WEEK)"; break; + case MONTHLY: minimumDate = "(NOW() - INTERVAL 1 MONTH)"; break; + case YEARLY: minimumDate = "(NOW() - INTERVAL 1 YEAR)"; break; + } + + return "SELECT b.name, b.score" + (uuid != null ? ", ROW_NUMBER() OVER (ORDER BY b.score DESC) AS position" : "") + + (uuid != null ? ", (SELECT COUNT(*) FROM builder_has_plot bhp_sub " + + "INNER JOIN builder b_sub ON b_sub.uuid = bhp_sub.uuid " + + "INNER JOIN plot_review r_sub ON r_sub.plot_id = bhp_sub.plot_id " + + (minimumDate != null ? "WHERE r.review_date BETWEEN " + minimumDate + " AND NOW()" : "") + ") " + + "AS total_positions" : "") + + " FROM builder_has_plot bhp" + + "INNER JOIN builder b ON b.uuid = bhp.uuid" + + "INNER JOIN plot_review r ON r.plot_id = bhp.plot_id" + + (minimumDate != null + ? "WHERE r.review_date BETWEEN " + minimumDate + " AND NOW()" + : "") + + (uuid != null + ? "WHERE b.uuid = ?;" + : "ORDER BY b.name, b.score DESC LIMIT 10;" + ); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java index d8b92f73..4033cdd3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java @@ -2,6 +2,7 @@ import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.holograms.leaderboards.ScoreLeaderboard; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import org.bukkit.Bukkit; @@ -13,12 +14,11 @@ public final class HologramRegister { /** - * Registers the {@link ScoreLeaderboard}, {@link PlotsLeaderboard} and adds + * Registers the {@link ScoreLeaderboard} and adds * them to {@link DecentHologramDisplay#activeDisplays}. */ public static void init() { new ScoreLeaderboard(); - new PlotsLeaderboard(); } public static void reload() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java new file mode 100644 index 00000000..b35106f3 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java @@ -0,0 +1,25 @@ +package com.alpsbte.plotsystem.core.holograms.leaderboards; + +public class LeaderboardEntry { + private final int score; + private final int position; + private final int totalPositions; + + public LeaderboardEntry(int score, int position, int totalPositions) { + this.score = score; + this.position = position; + this.totalPositions = totalPositions; + } + + public int getScore() { + return score; + } + + public int getPosition() { + return position; + } + + public int getTotalPosition() { + return totalPositions; + } +} \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java new file mode 100644 index 00000000..dc722dd0 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java @@ -0,0 +1,20 @@ +package com.alpsbte.plotsystem.core.holograms.leaderboards; + +import com.alpsbte.plotsystem.utils.io.ConfigPaths; +import com.alpsbte.plotsystem.utils.io.LangPaths; + +public enum LeaderboardTimeframe { + DAILY(ConfigPaths.DISPLAY_OPTIONS_SHOW_DAILY), + WEEKLY(ConfigPaths.DISPLAY_OPTIONS_SHOW_WEEKLY), + MONTHLY(ConfigPaths.DISPLAY_OPTIONS_SHOW_MONTHLY), + YEARLY(ConfigPaths.DISPLAY_OPTIONS_SHOW_YEARLY), + LIFETIME(ConfigPaths.DISPLAY_OPTIONS_SHOW_LIFETIME); + + public final String configPath; + public final String langPath; + + LeaderboardTimeframe(String configPath) { + this.configPath = configPath; + this.langPath = LangPaths.Leaderboards.PAGES + name(); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java similarity index 63% rename from src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java rename to src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index 309e2e77..d520109b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -22,11 +22,13 @@ * SOFTWARE. */ -package com.alpsbte.plotsystem.core.holograms; +package com.alpsbte.plotsystem.core.holograms.leaderboards; import com.alpsbte.alpslib.hologram.DecentHologramPagedDisplay; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.holograms.HologramConfiguration; +import com.alpsbte.plotsystem.core.holograms.HologramRegister; import com.alpsbte.plotsystem.core.system.Payout; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; import com.alpsbte.plotsystem.utils.io.ConfigPaths; @@ -49,6 +51,7 @@ import java.sql.SQLException; import java.text.DecimalFormat; import java.util.*; +import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.stream.Collectors; @@ -66,7 +69,7 @@ protected ScoreLeaderboard() { public void run() { for (Player player : getPlayersInRadiusForRanking()) { if (AbstractTutorial.getActiveTutorial(player.getUniqueId()) != null) continue; - player.sendActionBar(getRankingString(player)); + getPlayerRankingComponent(player).thenAccept(player::sendActionBar); } } }.runTaskTimerAsynchronously(PlotSystem.getPlugin(), 0L, 20L); @@ -114,76 +117,71 @@ public List> getHeader(UUID playerUUID) { @Override public List> getContent(UUID playerUUID) { - try { - ArrayList> lines = new ArrayList<>(); + ArrayList> lines = new ArrayList<>(); - for (int index = 0; index < 10; index++) { - lines.add(new LeaderboardPositionLineWithPayout(index + 1, null, 0)); - } - - HashMap leaderboardScores = Builder.getBuildersByScore(sortByLeaderboard); - for (int i = 0; i < leaderboardScores.size(); i++) { - String key = (String) leaderboardScores.keySet().toArray()[i]; - lines.set(i, new LeaderboardPositionLineWithPayout(i + 1, key, leaderboardScores.get(key))); - } - - return lines; - } catch (SQLException ex) { - PlotSystem.getPlugin().getLogger().log(Level.SEVERE, "An error occurred while reading leaderboard content", ex); + for (int index = 0; index < 10; index++) { + lines.add(new LeaderboardPositionLineWithPayout(index + 1, null, 0)); } - return new ArrayList<>(); - } - private Component getRankingString(Player player) { - int position, rows, myScore; - try { - position = Builder.getBuilderScorePosition(player.getUniqueId(), sortByLeaderboard); - rows = Builder.getBuildersInSort(sortByLeaderboard); - myScore = Builder.getBuilderScore(player.getUniqueId(), sortByLeaderboard); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(Component.text("A SQL error occurred!"), ex); - return Component.empty(); - } - - // Start building the component - TextComponent.Builder builder = Component.text() - .append(Component.text(" " + LangUtil.getInstance().get(player, sortByLeaderboard.langPath)) - .color(NamedTextColor.GOLD) - .decorate(TextDecoration.BOLD) - ) - .append(Component.text(" ➜ ") - .color(NamedTextColor.DARK_GRAY) - .decorate(TextDecoration.BOLD) - ); - - if (position == -1) { - builder.append(Component.text(LangUtil.getInstance().get(player, LangPaths.Leaderboards.NOT_ON_LEADERBOARD)) - .color(NamedTextColor.RED) - .decoration(TextDecoration.BOLD, false) - ); - } else if (position < 50) { - builder.append(Component.text( - LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_POSITION, String.valueOf(position))) - .color(NamedTextColor.GREEN) - .decoration(TextDecoration.BOLD, false) - ); - } else { - String topPercentage = df.format(position * 1.0 / rows); - builder.append(Component.text( - LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_PERCENTAGE, topPercentage)) - .decoration(TextDecoration.BOLD, false) - ); - } - - if (myScore != -1) { - builder.append( - Component.text(" (", NamedTextColor.DARK_GRAY) - .append(Component.text(myScore + " points", NamedTextColor.AQUA)) - .append(Component.text(")", NamedTextColor.DARK_GRAY)) - ); - } + // TODO: Make #getContent as CompletableFuture to fetch data async + DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard) + .thenAccept((playerRankings) -> { + if (playerRankings == null) return; + for (int i = 0; i < playerRankings.size(); i++) { + String key = (String) playerRankings.keySet().toArray()[i]; + lines.set(i, new LeaderboardPositionLineWithPayout(i + 1, key, playerRankings.get(key))); + } + }); + return lines; + } - return builder.build(); + private CompletableFuture getPlayerRankingComponent(Player player) { + return DataProvider.BUILDER.getLeaderboardEntryByUUID(player.getUniqueId(), sortByLeaderboard) + .thenCompose((leaderboardEntry -> CompletableFuture.supplyAsync(() -> { + if (leaderboardEntry == null) return Component.empty(); + + // Start building the component + TextComponent.Builder builder = Component.text() + .append(Component.text(" " + LangUtil.getInstance().get(player, sortByLeaderboard.langPath)) + .color(NamedTextColor.GOLD) + .decorate(TextDecoration.BOLD) + ) + .append(Component.text(" ➜ ") + .color(NamedTextColor.DARK_GRAY) + .decorate(TextDecoration.BOLD) + ); + + if (leaderboardEntry.getPosition() == -1) { + builder.append(Component.text(LangUtil.getInstance().get(player, LangPaths.Leaderboards.NOT_ON_LEADERBOARD)) + .color(NamedTextColor.RED) + .decoration(TextDecoration.BOLD, false) + ); + } else if (leaderboardEntry.getPosition() < 50) { + builder.append(Component.text( + LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_POSITION, + String.valueOf(leaderboardEntry.getPosition()))) + .color(NamedTextColor.GREEN) + .decoration(TextDecoration.BOLD, false) + ); + } else { + String topPercentage = df.format(leaderboardEntry.getPosition() * 1.0 / leaderboardEntry.getTotalPosition()); + builder.append(Component.text( + LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_PERCENTAGE, topPercentage)) + .decoration(TextDecoration.BOLD, false) + ); + } + + if (leaderboardEntry.getScore() != -1) { + builder.append( + Component.text(" (", NamedTextColor.DARK_GRAY) + .append(Component.text(leaderboardEntry.getScore() + " " + + LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_POINTS), NamedTextColor.AQUA)) + .append(Component.text(")", NamedTextColor.DARK_GRAY)) + ); + } + + return builder.build(); + }))); } private List getPlayersInRadiusForRanking() { @@ -228,22 +226,6 @@ public String getZPath() { return ConfigPaths.SCORE_LEADERBOARD_Z; } - public enum LeaderboardTimeframe { - DAILY(ConfigPaths.DISPLAY_OPTIONS_SHOW_DAILY), - WEEKLY(ConfigPaths.DISPLAY_OPTIONS_SHOW_WEEKLY), - MONTHLY(ConfigPaths.DISPLAY_OPTIONS_SHOW_MONTHLY), - YEARLY(ConfigPaths.DISPLAY_OPTIONS_SHOW_YEARLY), - LIFETIME(ConfigPaths.DISPLAY_OPTIONS_SHOW_LIFETIME); - - public final String configPath; - public final String langPath; - - LeaderboardTimeframe(String configPath) { - this.configPath = configPath; - this.langPath = LangPaths.Leaderboards.PAGES + name(); - } - } - private class LeaderboardPositionLineWithPayout extends HologramRegister.LeaderboardPositionLine { private final int position; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index d2ca2eeb..733c5aa7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -85,7 +85,7 @@ protected void setMenuItemsAsync() { .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE) + ": ") .append(text(builder.getScore(), WHITE))) .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COMPLETED_PLOTS) + ": ", GRAY) - .append(text(builder.getCompletedBuilds(), WHITE))) + .append(text(builder.getCompletedBuildsCount(), WHITE))) .build()) .build()); } catch (SQLException ex) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index 78dbd52a..dfe1778c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -67,7 +67,7 @@ protected void setMenuItemsAsync() { .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_FOCUS_MODE)) .build()) - .setEnchanted(builder.getPlotTypeSetting().getId() == PlotType.FOCUS_MODE.getId()) + .setEnchanted(builder.getPlotType().getId() == PlotType.FOCUS_MODE.getId()) .build()); getMenu().getSlot(13).setItem( @@ -76,7 +76,7 @@ protected void setMenuItemsAsync() { .setLore(new LoreBuilder() .addLines(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_INSPIRATION_MODE)) .build()) - .setEnchanted(builder.getPlotTypeSetting().getId() == PlotType.LOCAL_INSPIRATION_MODE.getId()) + .setEnchanted(builder.getPlotType().getId() == PlotType.LOCAL_INSPIRATION_MODE.getId()) .build()); getMenu().getSlot(15).setItem( @@ -86,14 +86,14 @@ protected void setMenuItemsAsync() { .setLore(new LoreBuilder() .addLines(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_CITY_INSPIRATION_MODE)) .build()) - .setEnchanted(builder.getPlotTypeSetting().getId() == PlotType.CITY_INSPIRATION_MODE.getId()) + .setEnchanted(builder.getPlotType().getId() == PlotType.CITY_INSPIRATION_MODE.getId()) .build()); // Set selected glass pane int selectedPlotTypeSlot = 13; - if (builder.getPlotTypeSetting() == PlotType.FOCUS_MODE) + if (builder.getPlotType() == PlotType.FOCUS_MODE) selectedPlotTypeSlot = 11; - if (builder.getPlotTypeSetting() == PlotType.CITY_INSPIRATION_MODE) + if (builder.getPlotType() == PlotType.CITY_INSPIRATION_MODE) selectedPlotTypeSlot = 15; getMenu().getSlot(selectedPlotTypeSlot - 9).setItem(new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, 1).setName(empty()).build()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java index eeb461ac..c786575e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java @@ -223,10 +223,9 @@ protected void setItemClickEventsAsync() { plot.setStatus(Status.completed); plot.getReview().setFeedbackSent(false); plot.getReview().setFeedback("No Feedback"); - plot.getPlotOwner().addCompletedBuild(1); // Remove Plot from Owner - plot.getPlotOwner().removePlot(plot.getSlot()); + plot.getPlotOwner().setSlot(-1, plot.getSlot()); if (plot.getPlotMembers().isEmpty()) { // Plot was made alone @@ -250,10 +249,9 @@ protected void setItemClickEventsAsync() { for (Builder builder : plot.getPlotMembers()) { // Score gets split between all participants builder.addScore(plot.getSharedScore()); - builder.addCompletedBuild(1); // Remove Slot from Member - builder.removePlot(builder.getSlot(plot)); + builder.setSlot(-1, builder.getSlot(plot)); } } } else { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 63e5fa8c..df98d8bc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -44,12 +44,15 @@ import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.CustomHeads; import com.alpsbte.plotsystem.utils.items.MenuItems; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.sql.SQLException; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Optional; @@ -114,7 +117,7 @@ public static HashMap getFooterItems(int startingSlot, Play final int i_ = i; Plot plot = builder.getPlot(Slot.values()[i]); - items.put(startingSlot + 1 + i, new FooterItem(builder.getPlotMenuItem(plot, Slot.values()[i].ordinal(), player), (clickPlayer, clickInformation) -> { + items.put(startingSlot + 1 + i, new FooterItem(getPlotMenuItem(plot, Slot.values()[i].ordinal(), player), (clickPlayer, clickInformation) -> { if (plot == null) return; try { new PlotActionsMenu(clickPlayer, builder.getPlot(Slot.values()[i_])); @@ -191,4 +194,36 @@ public static class FooterItem { this.item = item; } } + + public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) throws SQLException { + String nameText = LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); + Component statusComp = Component.text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true); + Component slotDescriptionComp = Component.text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), NamedTextColor.GRAY); + + Material itemMaterial = Material.MAP; + ArrayList lore = new LoreBuilder() + .addLines(slotDescriptionComp, + Component.empty(), + statusComp.append(Component.text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) + .build(); + + if (plot != null) { + itemMaterial = Material.FILLED_MAP; + String plotIdText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.ID); + String plotCityText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.CITY); + String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); + lore = new LoreBuilder() + .addLines(Component.text(plotIdText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getID(), NamedTextColor.WHITE)), + Component.text(plotCityText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getCity().getName(), NamedTextColor.WHITE)), + Component.text(plotDifficultyText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), NamedTextColor.WHITE)), + Component.empty(), + statusComp.append(Component.text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) + .build(); + } + + return new ItemBuilder(itemMaterial, 1 + slotIndex) + .setName(Component.text(nameText, NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) + .setLore(lore) + .build(); + } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 0fca443b..28a55bb7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -24,180 +24,129 @@ package com.alpsbte.plotsystem.core.system; -import com.alpsbte.alpslib.utils.item.ItemBuilder; -import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.Slot; -import com.alpsbte.plotsystem.utils.io.LangPaths; -import com.alpsbte.plotsystem.utils.io.LangUtil; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Bukkit; -import org.bukkit.Material; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; import java.sql.SQLException; import java.util.*; +import java.util.concurrent.CompletableFuture; public class Builder { - public static final HashMap builders = new HashMap<>(); - private final UUID uuid; - public PlotType plotType; - - private Builder(UUID UUID) { + private String name; + private int score; + private int firstSlot; + private int secondSlot; + private int thirdSlot; + private int plotType; + + public Builder(UUID UUID, String name, int score, int first_slot, int second_slot, int third_slot, int plot_type) { this.uuid = UUID; - } - - public static Builder byUUID(UUID uuid) { - if (builders.containsKey(uuid)) - return builders.get(uuid); - - Builder builder = new Builder(uuid); - builders.put(uuid, builder); - - return builders.get(uuid); - } - - public Player getPlayer() { - return Bukkit.getPlayer(uuid); + this.name = name; + this.score = score; + this.firstSlot = first_slot; + this.secondSlot = second_slot; + this.thirdSlot = third_slot; + this.plotType = plot_type; } public java.util.UUID getUUID() { return uuid; } - public boolean isOnline() {return Bukkit.getPlayer(uuid) != null;} - - public String getName() throws SQLException { - return DataProvider.BUILDER.getName(uuid); + public String getName() { + return name; } - public int getScore() throws SQLException { - return DataProvider.BUILDER.getScore(uuid); + public CompletableFuture setName(String name) { + this.name = name; + return DataProvider.BUILDER.setName(uuid, name); } - public int getCompletedBuilds() throws SQLException { - return DataProvider.BUILDER.getCompletedBuildsCount(uuid); + public int getScore() { + return score; } - public Slot getFreeSlot() throws SQLException { - return DataProvider.BUILDER.getFreeSlot(uuid); + public CompletableFuture addScore(int score) { + return DataProvider.BUILDER.addScore(uuid, score) + .thenCompose(success-> { + if (success) this.score = this.score + score; + return CompletableFuture.completedFuture(success); + }); } - public Plot getPlot(Slot slot) throws SQLException { - return DataProvider.BUILDER.getPlot(uuid, slot); - } - - public ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) throws SQLException { - String nameText = LangUtil.getInstance().get(getPlayer(), LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); - Component statusComp = Component.text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true); - Component slotDescriptionComp = Component.text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), NamedTextColor.GRAY); - - Material itemMaterial = Material.MAP; - ArrayList lore = new LoreBuilder() - .addLines(slotDescriptionComp, - Component.empty(), - statusComp.append(Component.text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) - .build(); - - if (plot != null) { - itemMaterial = Material.FILLED_MAP; - String plotIdText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.ID); - String plotCityText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.CITY); - String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); - lore = new LoreBuilder() - .addLines(Component.text(plotIdText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getID(), NamedTextColor.WHITE)), - Component.text(plotCityText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getCity().getName(), NamedTextColor.WHITE)), - Component.text(plotDifficultyText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), NamedTextColor.WHITE)), - Component.empty(), - statusComp.append(Component.text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) - .build(); + public Plot getSlot(Slot slot) { + if (slot == Slot.first_slot && firstSlot != -1) { + return new Plot(firstSlot); + } else if (slot == Slot.second_slot && secondSlot != -1) { + return new Plot(secondSlot); + } else if (slot == Slot.third_slot && thirdSlot != -1) { + return new Plot(thirdSlot); } - - return new ItemBuilder(itemMaterial, 1 + slotIndex) - .setName(Component.text(nameText, NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) - .setLore(lore) - .build(); - } - - public void addScore(int score) throws SQLException { - DataProvider.BUILDER.addScore(uuid, score); - } - - public void addCompletedBuild(int amount) throws SQLException { - DataProvider.BUILDER.addCompletedBuild(uuid, amount); - } - - public void setPlot(int plotID, Slot slot) throws SQLException { - DataProvider.BUILDER.setPlot(uuid, plotID, slot); - } - - public void removePlot(Slot slot) throws SQLException { - DataProvider.BUILDER.removePlot(uuid, slot); + return null; } - public static Builder getBuilderByName(String name) throws SQLException { - return DataProvider.BUILDER.getBuilderByName(name); + public CompletableFuture setSlot(Slot slot, int plotId) { + return DataProvider.BUILDER.setSlot(uuid, plotId, slot) + .thenCompose(success -> { + if (success) { + switch (slot) { + case first_slot: firstSlot = plotId; break; + case second_slot: secondSlot = plotId; break; + case third_slot: thirdSlot = plotId; break; + } + } + return CompletableFuture.completedFuture(success); + }); } - public static int getBuilderScore(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - return DataProvider.BUILDER.getLeaderboardScore(uuid, sortBy); + public PlotType getPlotType() { + return PlotType.byId(plotType); } - public static int getBuilderScorePosition(UUID uuid, ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - return DataProvider.BUILDER.getLeaderboardPosition(uuid, sortBy); + public CompletableFuture setPlotType(int plotType) { + return DataProvider.BUILDER.setPlotType(uuid, plotType) + .thenCompose(success -> { + if (success) this.plotType = plotType; + return CompletableFuture.completedFuture(success); + }); } - public static int getBuildersInSort(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - return DataProvider.BUILDER.getLeaderboardEntryCount(sortBy); + public Player getPlayer() { + return Bukkit.getPlayer(uuid); } - public static HashMap getBuildersByScore(ScoreLeaderboard.LeaderboardTimeframe sortBy) throws SQLException { - return DataProvider.BUILDER.getLeaderboardEntriesByScore(sortBy); + public boolean isOnline() { + return getPlayer() != null; } - public static HashMap getBuildersByCompletedBuilds(int limit) throws SQLException { - return DataProvider.BUILDER.getLeaderboardEntriesByCompletedBuilds(limit); + public CompletableFuture getCompletedBuildsCount() { + return DataProvider.BUILDER.getCompletedBuildsCount(uuid); } - public Slot getSlot(Plot plot) throws SQLException { - for (Slot slot : Slot.values()) { - Plot slotPlot = getPlot(slot); - if (slotPlot != null && slotPlot.getID() == plot.getID()) { - return slot; - } - } - return null; + public CompletableFuture getFreeSlot() { + return DataProvider.BUILDER.getFreeSlot(uuid); } - public PlotType getPlotTypeSetting() { - if (plotType != null) - return plotType; - this.plotType = DataProvider.BUILDER.getPlotTypeSetting(uuid); - return plotType; + public static CompletableFuture byUUID(UUID uuid) { + return DataProvider.BUILDER.getBuilderByUUID(uuid); } - public void setPlotTypeSetting(PlotType plotType) { - DataProvider.BUILDER.setPlotTypeSetting(uuid, plotType); - this.plotType = plotType; + public static CompletableFuture byName(String name) { + return DataProvider.BUILDER.getBuilderByName(name); } public Reviewer getAsReviewer() throws SQLException { return new Reviewer(getUUID()); } - public boolean isReviewer() throws SQLException { - return DataProvider.BUILDER.isReviewer(uuid); - } - public static class Reviewer { private final List buildTeams; + public Reviewer(UUID reviewerUUID) throws SQLException { this.buildTeams = BuildTeam.getBuildTeamsByReviewer(reviewerUUID); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java b/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java index dcf183ca..b6d8e423 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java @@ -25,26 +25,27 @@ package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.holograms.ScoreLeaderboard; +import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; +import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; import java.sql.ResultSet; import java.sql.SQLException; public class Payout { private final int id; - private final ScoreLeaderboard.LeaderboardTimeframe timeframe; + private final LeaderboardTimeframe timeframe; private final int position; private final String payoutAmount; - private Payout(int id, ScoreLeaderboard.LeaderboardTimeframe timeframe, int position, String payoutAmount) { + private Payout(int id, LeaderboardTimeframe timeframe, int position, String payoutAmount) { this.id = id; this.timeframe = timeframe; this.position = position; this.payoutAmount = payoutAmount; } - public static Payout getPayout(ScoreLeaderboard.LeaderboardTimeframe timeframe, int position) throws SQLException { - if (timeframe == ScoreLeaderboard.LeaderboardTimeframe.LIFETIME) { + public static Payout getPayout(LeaderboardTimeframe timeframe, int position) throws SQLException { + if (timeframe == LeaderboardTimeframe.LIFETIME) { throw new IllegalArgumentException("Invalid option LIFETIME"); } if (position < 1 || position > 10) { @@ -56,7 +57,7 @@ public static Payout getPayout(ScoreLeaderboard.LeaderboardTimeframe timeframe, Payout instance = null; if (rs.next()) { - instance = new Payout(rs.getInt(1), ScoreLeaderboard.LeaderboardTimeframe.valueOf(rs.getString(2)), rs.getInt(3), rs.getString(4)); + instance = new Payout(rs.getInt(1), LeaderboardTimeframe.valueOf(rs.getString(2)), rs.getInt(3), rs.getString(4)); } DatabaseConnection.closeResultSet(rs); @@ -68,7 +69,7 @@ public int getId() { return id; } - public ScoreLeaderboard.LeaderboardTimeframe getTimeframe() { + public LeaderboardTimeframe getTimeframe() { return timeframe; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java index bf9d5fa5..e52bca57 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java @@ -223,21 +223,19 @@ public static void undoReview(Review review) { for (Builder member : plot.getPlotMembers()) { member.addScore(-plot.getSharedScore()); - member.addCompletedBuild(-1); if (member.getFreeSlot() != null) { - member.setPlot(plot.getID(), member.getFreeSlot()); + member.setSlot(plot.getID(), member.getFreeSlot()); } } plot.getPlotOwner().addScore(-plot.getSharedScore()); - plot.getPlotOwner().addCompletedBuild(-1); plot.setTotalScore(-1); plot.setStatus(Status.unreviewed); plot.setPasted(false); if (plot.getPlotOwner().getFreeSlot() != null) { - plot.getPlotOwner().setPlot(plot.getID(), plot.getPlotOwner().getFreeSlot()); + plot.getPlotOwner().setSlot(plot.getID(), plot.getPlotOwner().getFreeSlot()); } int cityId = plot.getCity().getID(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 83cfc5d8..669fbd28 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -480,7 +480,7 @@ public void addPlotMember(Builder member) throws SQLException { members.add(member); setPlotMembers(members); - member.setPlot(this.ID, slot); + member.setSlot(this.ID, slot); getPermissions().addBuilderPerms(member.getUUID()); } } @@ -494,7 +494,7 @@ public void removePlotMember(Builder member) throws SQLException { Slot slot = member.getSlot(this); if (slot != null) { - member.removePlot(slot); + member.setSlot(-1, slot); } if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 265ab27e..cb560af4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -95,7 +95,7 @@ public abstract class AbstractPlotGenerator { * @param builder - builder of the plot */ public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) throws SQLException { - this(plot, builder, builder.getPlotTypeSetting()); + this(plot, builder, builder.getPlotType()); } /** diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 363f95b3..681f7bb5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -128,14 +128,14 @@ protected void onComplete(boolean failed, boolean unloadWorld) throws SQLExcepti super.onComplete(failed, false); if (!failed) { - getBuilder().setPlot(plot.getID(), getBuilder().getFreeSlot()); + getBuilder().setSlot(plot.getID(), getBuilder().getFreeSlot()); plot.setStatus(Status.unfinished); ((Plot) plot).setPlotType(plotType); ((Plot) plot).setPlotOwner(getBuilder().getPlayer().getUniqueId().toString()); PlotUtils.Cache.clearCache(getBuilder().getUUID()); plot.getWorld().teleportPlayer(getBuilder().getPlayer()); - LangUtil.getInstance().broadcast(LangPaths.Message.Info.CREATED_NEW_PLOT, plot.getPlotOwner().getName()); + LangUtil.getInstance().broadcast(LangPaths.Message.Info.CREATED_NEW_PLOT, getBuilder().getName()); } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 3c2bd0aa..48c9e208 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -438,7 +438,7 @@ public static boolean abandonPlot(AbstractPlot plot) { if (plot.getPlotOwner() != null) { Cache.clearCache(plot.getPlotOwner().getUUID()); - plot.getPlotOwner().removePlot(dPlot.getSlot()); + plot.getPlotOwner().setSlot(-1, dPlot.getSlot()); } dPlot.setPlotOwner(null); @@ -572,7 +572,7 @@ public static void showOutlines() { if (!plot.getWorld().getWorldName().equals(player.getWorld().getName())) continue; - if (!plot.getPlotOwner().getPlotTypeSetting().hasEnvironment() || plot.getVersion() <= 2) + if (!plot.getPlotOwner().getPlotType().hasEnvironment() || plot.getVersion() <= 2) continue; List points = plot.getBlockOutline(); From 614a75dd7e3fb68c412516b186db647de1aefad5 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 20 Jan 2025 22:09:06 +0100 Subject: [PATCH 005/175] Fix CMD_Plots.java, CMD_Tpll.java and PlotSystem.java --- .../com/alpsbte/plotsystem/PlotSystem.java | 10 +- .../plotsystem/commands/CMD_Plots.java | 28 ++-- .../alpsbte/plotsystem/commands/CMD_Tpll.java | 127 ++++++++++-------- .../core/menus/PlayerPlotsMenu.java | 2 +- 4 files changed, 87 insertions(+), 80 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 7da8e0c8..1126662d 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -64,6 +64,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.*; +import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import static net.kyori.adventure.text.Component.empty; @@ -231,8 +232,13 @@ public void onDisable() { } else { // Unload plots for (UUID player : PlotUtils.Cache.getCachedInProgressPlots().keySet()) { - for (Plot plot : PlotUtils.Cache.getCachedInProgressPlots(Builder.byUUID(player))) { - if (plot != null) plot.getWorld().unloadWorld(true); + try { + Builder builder = Builder.byUUID(player).get(); + for (Plot plot : PlotUtils.Cache.getCachedInProgressPlots(builder)) { + if (plot != null) plot.getWorld().unloadWorld(true); + } + } catch (InterruptedException | ExecutionException e) { + throw new RuntimeException(e); } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java index a8aa741a..ea5d876c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java @@ -38,10 +38,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; - -import static net.kyori.adventure.text.Component.text; - public class CMD_Plots extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { @@ -50,30 +46,26 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - if (getPlayer(sender) == null) { + Player player = getPlayer(sender); + if (player == null) { Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return true; } - Player player = (Player) sender; - - try { - if (args.length < 1) { - new PlayerPlotsMenu(player, Builder.byUUID(player.getUniqueId())); - return true; - } + if (args.length < 1) { + Builder.byUUID(player.getUniqueId()).thenAccept(builder -> Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), + () -> new PlayerPlotsMenu(player, builder))); + return true; + } - Builder builder = Builder.byName(args[0]); + Builder.byName(args[0]).thenAccept(builder -> Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (builder == null) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); - return true; + return; } new PlayerPlotsMenu(player, builder); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + })); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index c30bf114..1d550326 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -75,78 +75,87 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - try { - if (args == null || args.length < 2 || args.length > 3) { - sendInfo(sender); - return true; - } + if (args == null || args.length < 2 || args.length > 3) { + sendInfo(sender); + return true; + } - String[] splitCoords = args[0].split(","); - if (splitCoords.length == 2) { - args = splitCoords; - } + String[] splitCoords = args[0].split(","); + if (splitCoords.length == 2) { + args = splitCoords; + } - if (args[0].endsWith(",")) { - args[0] = args[0].substring(0, args[0].length() - 1); - } - if (args[1].endsWith(",")) { - args[1] = args[1].substring(0, args[1].length() - 1); - } + if (args[0].endsWith(",")) { + args[0] = args[0].substring(0, args[0].length() - 1); + } + if (args[1].endsWith(",")) { + args[1] = args[1].substring(0, args[1].length() - 1); + } + + // Parse coordinates to doubles + double lat; + double lon; + try { + lat = Double.parseDouble(args[0]); + lon = Double.parseDouble(args[1]); + } catch (Exception ignore) { + sendInfo(sender); + return true; + } - // Parse coordinates to doubles - double lat; - double lon; + CompletableFuture.runAsync(() -> { try { - lat = Double.parseDouble(args[0]); - lon = Double.parseDouble(args[1]); - } catch (Exception ignore) { - sendInfo(sender); - return true; - } + // Get the terra coordinates from the irl coordinates + double[] terraCoords = CoordinateConversion.convertFromGeo(lon, lat); - // Get the terra coordinates from the irl coordinates - double[] terraCoords = CoordinateConversion.convertFromGeo(lon, lat); + // Get plot, that the player is in + AbstractPlot plot = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()).get(), Status.unfinished, Status.unreviewed, Status.completed); - // Get plot, that the player is in - AbstractPlot plot = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished, Status.unreviewed, Status.completed); + // Convert terra coordinates to plot relative coordinates + CompletableFuture plotCoordsFuture = plot != null ? PlotUtils.convertTerraToPlotXZ(plot, terraCoords) : null; - // Convert terra coordinates to plot relative coordinates - CompletableFuture plotCoords = plot != null ? PlotUtils.convertTerraToPlotXZ(plot, terraCoords) : null; + if (plotCoordsFuture == null) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CANNOT_TELEPORT_OUTSIDE_PLOT))); + return; + } - if (plotCoords == null) { - player.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CANNOT_TELEPORT_OUTSIDE_PLOT))); - return true; - } + double[] plotCoordinates = plotCoordsFuture.get(); - // Get Highest Y - int highestY = 0; - Location block = new Location(playerWorld, plotCoords.get()[0], 0, plotCoords.get()[1]); - for (int i = 1; i < 256; i++) { - block.add(0, 1, 0); - if (!block.getBlock().isEmpty()) { - highestY = i; - } - } - if (highestY < PlotWorld.MIN_WORLD_HEIGHT) { - highestY = PlotWorld.MIN_WORLD_HEIGHT; - } + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + int highestY = getHighestY(playerWorld, plotCoordinates); - player.teleport(new Location(playerWorld, plotCoords.get()[0], highestY + 1, plotCoords.get()[1], player.getLocation().getYaw(), player.getLocation().getPitch())); + player.teleport(new Location(playerWorld, plotCoordinates[0], highestY + 1, plotCoordinates[1], player.getLocation().getYaw(), player.getLocation().getPitch())); - DecimalFormat df = new DecimalFormat("##.#####"); - df.setRoundingMode(RoundingMode.FLOOR); - player.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.TELEPORTING_TPLL, df.format(lat), df.format(lon)))); + DecimalFormat df = new DecimalFormat("##.#####"); + df.setRoundingMode(RoundingMode.FLOOR); + player.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.TELEPORTING_TPLL, df.format(lat), df.format(lon)))); + }); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + } catch (IOException | OutOfProjectionBoundsException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A coordinate conversion error occurred!"), ex); + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + } catch (InterruptedException | ExecutionException ex) { + sendInfo(sender); + } + }); + return true; + } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - } catch (IOException | OutOfProjectionBoundsException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A coordinate conversion error occurred!"), ex); - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - } catch (InterruptedException | ExecutionException ex) { - sendInfo(sender); + private static int getHighestY(World playerWorld, double[] plotCoordinates) { + int highestY = 0; + Location block = new Location(playerWorld, plotCoordinates[0], 0, plotCoordinates[1]); + for (int i = 1; i < 256; i++) { + block.add(0, 1, 0); + if (!block.getBlock().isEmpty()) { + highestY = i; + } } - return true; + if (highestY < PlotWorld.MIN_WORLD_HEIGHT) { + highestY = PlotWorld.MIN_WORLD_HEIGHT; + } + return highestY; } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 733c5aa7..358227ab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -58,7 +58,7 @@ public class PlayerPlotsMenu extends AbstractMenu { private int plotDisplayCount = 0; - public PlayerPlotsMenu(Player menuPlayer, Builder builder) throws SQLException { + public PlayerPlotsMenu(Player menuPlayer, Builder builder) { super(6, LangUtil.getInstance().get(menuPlayer.getPlayer(), LangPaths.MenuTitle.PLAYER_PLOTS, builder.getName() + "'"), menuPlayer); this.builder = builder; } From eaafbf2cae7e5f05006240a074159f953e9d95be Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Mon, 20 Jan 2025 23:00:16 +0100 Subject: [PATCH 006/175] update BuilderProvider --- .../core/database/DataProvider.java | 24 ++ .../database/providers/BuilderProvider.java | 304 +++++++++--------- .../leaderboards/LeaderboardEntry.java | 24 ++ .../leaderboards/LeaderboardTimeframe.java | 24 ++ .../leaderboards/ScoreLeaderboard.java | 109 +++---- .../plotsystem/core/system/Builder.java | 83 ++--- .../plotsystem/core/system/plot/Plot.java | 8 +- .../alpsbte/plotsystem/utils/enums/Slot.java | 2 +- 8 files changed, 325 insertions(+), 253 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 0117fea1..2b5dc314 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database; import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 38740e0c..2b10cc73 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.PlotSystem; @@ -12,172 +36,150 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; -import java.util.concurrent.CompletableFuture; public class BuilderProvider { public static final HashMap builders = new HashMap<>(); - public CompletableFuture getBuilderByUUID(UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - if (builders.containsKey(uuid)) return builders.get(uuid); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT name, score, first_slot, second_slot, third_slot, plot_type " + - "FROM builder WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); + public Builder getBuilderByUUID(UUID uuid) { + if (builders.containsKey(uuid)) return builders.get(uuid); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT name, score, first_slot, second_slot, third_slot, plot_type " + + "FROM builder WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new Builder(uuid, rs.getString(1), rs.getInt(2), rs.getInt(3), - rs.getInt(4), rs.getInt(5), rs.getInt(6)); - } + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new Builder(uuid, rs.getString(1), rs.getInt(2), rs.getInt(3), + rs.getInt(4), rs.getInt(5), rs.getInt(6)); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); } - return null; - }); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; } - public CompletableFuture getBuilderByName(String name) { - return CompletableFuture.supplyAsync(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT uuid FROM builder WHERE name = ?;")) { - stmt.setString(1, name); + public Builder getBuilderByName(String name) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT uuid FROM builder WHERE name = ?;")) { + stmt.setString(1, name); - try (ResultSet rs = stmt.executeQuery()) { - return rs.getString(1); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + try (ResultSet rs = stmt.executeQuery()) { + String uuid = rs.getString(1); + if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); } - return null; - }).thenCompose(uuid -> { - if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); - return null; - }); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; + } + + public boolean setName(UUID uuid, String name) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder SET name = ? WHERE uuid = ?;")) { + stmt.setString(1, name); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + if (builders.containsKey(uuid)) builders.get(uuid).setName(name); + return true; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; } - public CompletableFuture setName(UUID uuid, String name) { - CompletableFuture.supplyAsync(() -> { + public boolean addScore(UUID uuid, int score) { + try { try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder SET name = ? WHERE uuid = ?;")) { - stmt.setString(1, name); + .prepareStatement("UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;")) { + stmt.setInt(1, score); stmt.setString(2, uuid.toString()); stmt.executeUpdate(); return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); } - return false; - }); - return null; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; } - public CompletableFuture addScore(UUID uuid, int score) { - CompletableFuture.supplyAsync(() -> { - try { + public boolean setSlot(UUID uuid, int plotID, Slot slot) { + try { + if (plotID > 0) { try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;")) { - stmt.setInt(1, score); + .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = ? " + + "WHERE uuid = ?;")) { + stmt.setInt(1, plotID); stmt.setString(2, uuid.toString()); stmt.executeUpdate(); - return true; } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } - return false; - }); - return null; - } - - public CompletableFuture setSlot(UUID uuid, int plotID, Slot slot) { - CompletableFuture.supplyAsync(() -> { - try { - if (plotID > 0) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = ? " + - "WHERE uuid = ?;")) { - stmt.setInt(1, plotID); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - } - } else { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = " + - "DEFAULT(first_slot) WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); - stmt.executeUpdate(); - } + } else { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = " + + "DEFAULT(first_slot) WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + stmt.executeUpdate(); } - return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); } - return false; - }); - return null; + return true; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; } - public CompletableFuture setPlotType(UUID uuid, int plotTypeId) { - CompletableFuture.supplyAsync(() -> { - try { - if (plotTypeId > 0) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET plot_type = ? WHERE uuid = ?;")) { - stmt.setInt(1, plotTypeId); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - } - } else { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET plot_type = DEFAULT(plot_type) WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); - stmt.executeUpdate(); - } + public boolean setPlotType(UUID uuid, int plotTypeId) { + try { + if (plotTypeId > 0) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET plot_type = ? WHERE uuid = ?;")) { + stmt.setInt(1, plotTypeId); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + } + } else { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET plot_type = DEFAULT(plot_type) WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + stmt.executeUpdate(); } - return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); } - return false; - }); - return null; + return true; + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return false; } - public CompletableFuture getCompletedBuildsCount(UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT COUNT(*) AS completed_plots FROM plot p INNER JOIN builder_has_plot " + - "bhp ON p.plot_id = bhp.plot_id WHERE p.status = 'completed' AND bhp.uuid = ?;")) { - stmt.setString(1, uuid.toString()); + public int getCompletedBuildsCount(UUID uuid) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT COUNT(*) AS completed_plots FROM plot p INNER JOIN builder_has_plot " + + "bhp ON p.plot_id = bhp.plot_id WHERE p.status = 'completed' AND bhp.uuid = ?;")) { + stmt.setString(1, uuid.toString()); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) return rs.getInt(1); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) return rs.getInt(1); } - return 0; - }); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return 0; } - public CompletableFuture getFreeSlot(UUID uuid) { - return CompletableFuture.supplyAsync(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); + public Slot getFreeSlot(UUID uuid) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); - try (ResultSet rs = stmt.executeQuery()) { - for (int i = 1; i <= 3; i++) { - if (rs.getString(i) == null) return Slot.values()[i - 1]; - } + try (ResultSet rs = stmt.executeQuery()) { + for (int i = 1; i <= 3; i++) { + if (rs.getString(i) == null) return Slot.values()[i - 1]; } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); } - return null; - }); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } + return null; } /** @@ -188,22 +190,19 @@ public CompletableFuture getFreeSlot(UUID uuid) { * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). * @return provides the leaderboard entry for the player, or null if not found. */ - public CompletableFuture getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimeframe sortBy) { - CompletableFuture.supplyAsync(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement(getLeaderboardQuery(uuid, sortBy))) { + public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimeframe sortBy) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement(getLeaderboardQuery(uuid, sortBy))) { - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new LeaderboardEntry(rs.getInt(2), rs.getInt(3), rs.getInt(4)); - } + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new LeaderboardEntry(rs.getInt(2), rs.getInt(3), rs.getInt(4)); } - - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); } - return null; - }); + + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } return null; } @@ -213,22 +212,19 @@ public CompletableFuture getLeaderboardEntryByUUID(UUID uuid, * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). * @return provides a map of player names and their scores, or null if no data is found. */ - public CompletableFuture> getLeaderboardEntries(LeaderboardTimeframe sortBy) { - CompletableFuture.supplyAsync(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement(getLeaderboardQuery(null, sortBy))) { + public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement(getLeaderboardQuery(null, sortBy))) { - try (ResultSet rs = stmt.executeQuery()) { - Map playerEntries = new HashMap<>(); - while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); - return playerEntries; - } - - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + try (ResultSet rs = stmt.executeQuery()) { + Map playerEntries = new HashMap<>(); + while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); + return playerEntries; } - return null; - }); + + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); + } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java index b35106f3..99a860ab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.holograms.leaderboards; public class LeaderboardEntry { diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java index dc722dd0..dde38049 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.holograms.leaderboards; import com.alpsbte.plotsystem.utils.io.ConfigPaths; diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index d520109b..dd05009f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -51,7 +51,6 @@ import java.sql.SQLException; import java.text.DecimalFormat; import java.util.*; -import java.util.concurrent.CompletableFuture; import java.util.logging.Level; import java.util.stream.Collectors; @@ -69,7 +68,7 @@ protected ScoreLeaderboard() { public void run() { for (Player player : getPlayersInRadiusForRanking()) { if (AbstractTutorial.getActiveTutorial(player.getUniqueId()) != null) continue; - getPlayerRankingComponent(player).thenAccept(player::sendActionBar); + player.sendActionBar(getPlayerRankingComponent(player)); } } }.runTaskTimerAsynchronously(PlotSystem.getPlugin(), 0L, 20L); @@ -123,65 +122,61 @@ public List> getContent(UUID playerUUID) { lines.add(new LeaderboardPositionLineWithPayout(index + 1, null, 0)); } - // TODO: Make #getContent as CompletableFuture to fetch data async - DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard) - .thenAccept((playerRankings) -> { - if (playerRankings == null) return; - for (int i = 0; i < playerRankings.size(); i++) { - String key = (String) playerRankings.keySet().toArray()[i]; - lines.set(i, new LeaderboardPositionLineWithPayout(i + 1, key, playerRankings.get(key))); - } - }); + Map playerRankings = DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard); + if (playerRankings != null) { + for (int i = 0; i < playerRankings.size(); i++) { + String key = (String) playerRankings.keySet().toArray()[i]; + lines.set(i, new LeaderboardPositionLineWithPayout(i + 1, key, playerRankings.get(key))); + } + } return lines; } - private CompletableFuture getPlayerRankingComponent(Player player) { - return DataProvider.BUILDER.getLeaderboardEntryByUUID(player.getUniqueId(), sortByLeaderboard) - .thenCompose((leaderboardEntry -> CompletableFuture.supplyAsync(() -> { - if (leaderboardEntry == null) return Component.empty(); - - // Start building the component - TextComponent.Builder builder = Component.text() - .append(Component.text(" " + LangUtil.getInstance().get(player, sortByLeaderboard.langPath)) - .color(NamedTextColor.GOLD) - .decorate(TextDecoration.BOLD) - ) - .append(Component.text(" ➜ ") - .color(NamedTextColor.DARK_GRAY) - .decorate(TextDecoration.BOLD) - ); - - if (leaderboardEntry.getPosition() == -1) { - builder.append(Component.text(LangUtil.getInstance().get(player, LangPaths.Leaderboards.NOT_ON_LEADERBOARD)) - .color(NamedTextColor.RED) - .decoration(TextDecoration.BOLD, false) - ); - } else if (leaderboardEntry.getPosition() < 50) { - builder.append(Component.text( - LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_POSITION, - String.valueOf(leaderboardEntry.getPosition()))) - .color(NamedTextColor.GREEN) - .decoration(TextDecoration.BOLD, false) - ); - } else { - String topPercentage = df.format(leaderboardEntry.getPosition() * 1.0 / leaderboardEntry.getTotalPosition()); - builder.append(Component.text( - LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_PERCENTAGE, topPercentage)) - .decoration(TextDecoration.BOLD, false) - ); - } + private Component getPlayerRankingComponent(Player player) { + LeaderboardEntry leaderboardEntry = DataProvider.BUILDER.getLeaderboardEntryByUUID(player.getUniqueId(), sortByLeaderboard); + if (leaderboardEntry == null) return Component.empty(); + + // Start building the component + TextComponent.Builder builder = Component.text() + .append(Component.text(" " + LangUtil.getInstance().get(player, sortByLeaderboard.langPath)) + .color(NamedTextColor.GOLD) + .decorate(TextDecoration.BOLD) + ) + .append(Component.text(" ➜ ") + .color(NamedTextColor.DARK_GRAY) + .decorate(TextDecoration.BOLD) + ); + + if (leaderboardEntry.getPosition() == -1) { + builder.append(Component.text(LangUtil.getInstance().get(player, LangPaths.Leaderboards.NOT_ON_LEADERBOARD)) + .color(NamedTextColor.RED) + .decoration(TextDecoration.BOLD, false) + ); + } else if (leaderboardEntry.getPosition() < 50) { + builder.append(Component.text( + LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_POSITION, + String.valueOf(leaderboardEntry.getPosition()))) + .color(NamedTextColor.GREEN) + .decoration(TextDecoration.BOLD, false) + ); + } else { + String topPercentage = df.format(leaderboardEntry.getPosition() * 1.0 / leaderboardEntry.getTotalPosition()); + builder.append(Component.text( + LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_PERCENTAGE, topPercentage)) + .decoration(TextDecoration.BOLD, false) + ); + } - if (leaderboardEntry.getScore() != -1) { - builder.append( - Component.text(" (", NamedTextColor.DARK_GRAY) - .append(Component.text(leaderboardEntry.getScore() + " " + - LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_POINTS), NamedTextColor.AQUA)) - .append(Component.text(")", NamedTextColor.DARK_GRAY)) - ); - } + if (leaderboardEntry.getScore() != -1) { + builder.append( + Component.text(" (", NamedTextColor.DARK_GRAY) + .append(Component.text(leaderboardEntry.getScore() + " " + + LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_POINTS), NamedTextColor.AQUA)) + .append(Component.text(")", NamedTextColor.DARK_GRAY)) + ); + } - return builder.build(); - }))); + return builder.build(); } private List getPlayersInRadiusForRanking() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 28a55bb7..ee14e620 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -33,7 +33,6 @@ import java.sql.SQLException; import java.util.*; -import java.util.concurrent.CompletableFuture; public class Builder { private final UUID uuid; @@ -62,58 +61,59 @@ public String getName() { return name; } - public CompletableFuture setName(String name) { - this.name = name; - return DataProvider.BUILDER.setName(uuid, name); + public boolean setName(String name) { + if (DataProvider.BUILDER.setName(this.uuid, name)) { + this.name = name; + return true; + } + return false; } public int getScore() { return score; } - public CompletableFuture addScore(int score) { - return DataProvider.BUILDER.addScore(uuid, score) - .thenCompose(success-> { - if (success) this.score = this.score + score; - return CompletableFuture.completedFuture(success); - }); + public boolean addScore(int score) { + if (DataProvider.BUILDER.addScore(this.uuid, score)) { + this.score = this.score + score; + return true; + } + return false; } public Plot getSlot(Slot slot) { - if (slot == Slot.first_slot && firstSlot != -1) { + if (slot == Slot.FIRST && firstSlot != -1) { return new Plot(firstSlot); - } else if (slot == Slot.second_slot && secondSlot != -1) { + } else if (slot == Slot.SECOND && secondSlot != -1) { return new Plot(secondSlot); - } else if (slot == Slot.third_slot && thirdSlot != -1) { + } else if (slot == Slot.THIRD && thirdSlot != -1) { return new Plot(thirdSlot); } return null; } - public CompletableFuture setSlot(Slot slot, int plotId) { - return DataProvider.BUILDER.setSlot(uuid, plotId, slot) - .thenCompose(success -> { - if (success) { - switch (slot) { - case first_slot: firstSlot = plotId; break; - case second_slot: secondSlot = plotId; break; - case third_slot: thirdSlot = plotId; break; - } - } - return CompletableFuture.completedFuture(success); - }); + public boolean setSlot(Slot slot, int plotId) { + if (DataProvider.BUILDER.setSlot(this.uuid, plotId, slot)) { + switch (slot) { + case FIRST: firstSlot = plotId; break; + case SECOND: secondSlot = plotId; break; + case THIRD: thirdSlot = plotId; break; + } + return true; + } + return false; } public PlotType getPlotType() { return PlotType.byId(plotType); } - public CompletableFuture setPlotType(int plotType) { - return DataProvider.BUILDER.setPlotType(uuid, plotType) - .thenCompose(success -> { - if (success) this.plotType = plotType; - return CompletableFuture.completedFuture(success); - }); + public boolean setPlotType(int plotType) { + if (DataProvider.BUILDER.setPlotType(this.uuid, plotType)) { + this.plotType = plotType; + return true; + } + return false; } public Player getPlayer() { @@ -124,19 +124,30 @@ public boolean isOnline() { return getPlayer() != null; } - public CompletableFuture getCompletedBuildsCount() { + public int getCompletedBuildsCount() { return DataProvider.BUILDER.getCompletedBuildsCount(uuid); } - public CompletableFuture getFreeSlot() { + public Slot getFreeSlot() { return DataProvider.BUILDER.getFreeSlot(uuid); } - public static CompletableFuture byUUID(UUID uuid) { + public Slot getSlotByPlotId(int plotId) { + if (firstSlot == plotId) { + return Slot.FIRST; + } else if (secondSlot == plotId) { + return Slot.SECOND; + } else if (thirdSlot == plotId) { + return Slot.THIRD; + } + return null; + } + + public static Builder byUUID(UUID uuid) { return DataProvider.BUILDER.getBuilderByUUID(uuid); } - public static CompletableFuture byName(String name) { + public static Builder byName(String name) { return DataProvider.BUILDER.getBuilderByName(name); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 669fbd28..9402b09c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -480,7 +480,7 @@ public void addPlotMember(Builder member) throws SQLException { members.add(member); setPlotMembers(members); - member.setSlot(this.ID, slot); + member.setSlot(slot, ID); getPermissions().addBuilderPerms(member.getUUID()); } } @@ -492,10 +492,8 @@ public void removePlotMember(Builder member) throws SQLException { members.remove(members.stream().filter(m -> m.getUUID().equals(member.getUUID())).findFirst().orElse(null)); setPlotMembers(members); - Slot slot = member.getSlot(this); - if (slot != null) { - member.setSlot(-1, slot); - } + Slot slot = member.getSlotByPlotId(ID); + if (slot != null) member.setSlot(slot, -1); if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); } } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java index 5f9eb803..5ba57dac 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java @@ -25,5 +25,5 @@ package com.alpsbte.plotsystem.utils.enums; public enum Slot { - first_slot, second_slot, third_slot + FIRST, SECOND, THIRD } From 28c8d2f0f3271115a5272f614a2c422aefdcbf28 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Tue, 21 Jan 2025 00:57:44 +0100 Subject: [PATCH 007/175] Fix all plot commands --- .../plotsystem/commands/CMD_Plots.java | 33 ++++--- .../alpsbte/plotsystem/commands/CMD_Tpll.java | 2 +- .../commands/admin/CMD_DeletePlot.java | 25 +++-- .../commands/plot/CMD_Plot_Abandon.java | 54 +++++------ .../commands/plot/CMD_Plot_Feedback.java | 73 +++++++------- .../commands/plot/CMD_Plot_Invite.java | 78 ++++++++------- .../commands/plot/CMD_Plot_Links.java | 48 ++++++---- .../commands/plot/CMD_Plot_Members.java | 67 ++++++------- .../commands/plot/CMD_Plot_Submit.java | 95 +++++++++++-------- .../commands/plot/CMD_Plot_Teleport.java | 61 +++++++----- .../commands/plot/CMD_Plot_UndoSubmit.java | 60 +++++++----- .../core/database/DataProvider.java | 2 + .../core/database/providers/PlotProvider.java | 28 ++++++ .../plotsystem/core/menus/FeedbackMenu.java | 2 +- .../core/system/plot/AbstractPlot.java | 2 +- .../plotsystem/core/system/plot/Plot.java | 81 +++------------- .../core/system/plot/utils/PlotUtils.java | 19 +--- .../utils/PlotMemberInvitation.java | 4 +- 18 files changed, 381 insertions(+), 353 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java index 75a5132b..91cb9650 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java @@ -30,12 +30,16 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.concurrent.CompletableFuture; + public class CMD_Plots extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { @@ -44,25 +48,30 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - if (getPlayer(sender) == null) { - Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return true; } if (args.length < 1) { - Builder.byUUID(player.getUniqueId()).thenAccept(builder -> Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), - () -> new PlayerPlotsMenu(player, builder))); - return true; + CompletableFuture.runAsync(() -> { + Builder builder = Builder.byUUID(player.getUniqueId()); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new PlayerPlotsMenu(player, builder)); + }); } - Builder.byName(args[0]).thenAccept(builder -> Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - if (builder == null) { - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); - return; - } + CompletableFuture.runAsync(() -> { + Builder builder = Builder.byName(args[0]); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + if (builder == null) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); + return; + } - new PlayerPlotsMenu(player, builder); - })); + new PlayerPlotsMenu(player, builder); + }); + }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index 2d735db0..ca06202c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -108,7 +108,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N double[] terraCoords = CoordinateConversion.convertFromGeo(lon, lat); // Get plot, that the player is in - AbstractPlot plot = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()).get(), Status.unfinished, Status.unreviewed, Status.completed); + AbstractPlot plot = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished, Status.unreviewed, Status.completed); // Convert terra coordinates to plot relative coordinates CompletableFuture plotCoordsFuture = plot != null ? PlotUtils.convertTerraToPlotXZ(plot, terraCoords) : null; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java index 2f460d6d..c21bab12 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; @@ -33,6 +34,8 @@ import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; +import java.util.concurrent.CompletableFuture; + public class CMD_DeletePlot extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { @@ -47,16 +50,20 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } int plotID = Integer.parseInt(args[0]); - if (!PlotUtils.plotExists(plotID)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find plot with ID #" + plotID + "!")); - return true; - } - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Deleting plot...")); - if (PlotUtils.Actions.deletePlot(new Plot(plotID))) { - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully deleted plot with the ID §6#" + plotID + "§a!")); - if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); - } else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An unexpected error has occurred!")); + CompletableFuture.runAsync(() -> { + Plot plot = DataProvider.PLOT.getPlotById(plotID); + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find plot with ID #" + plotID + "!")); + return; + } + + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Deleting plot...")); + if (PlotUtils.Actions.deletePlot(plot)) { + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully deleted plot with the ID §6#" + plotID + "§a!")); + if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); + } else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An unexpected error has occurred!")); + }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java index d2ba32bb..7166dcdc 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -35,12 +36,10 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; -import java.sql.SQLException; -import java.util.Objects; - -import static net.kyori.adventure.text.Component.text; +import java.util.concurrent.CompletableFuture; public class CMD_Plot_Abandon extends SubCommand { @@ -50,45 +49,42 @@ public CMD_Plot_Abandon(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { + CompletableFuture.runAsync(() -> { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - if (PlotUtils.plotExists(plotID)) { - plot = new Plot(plotID); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; - } + plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); } else if (getPlayer(sender) != null && PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.unfinished); - if (p instanceof Plot) { - plot = (Plot) p; - } else { + if (!(p instanceof Plot)) { sendInfo(sender); return; } + plot = (Plot) p; } else { sendInfo(sender); return; } - if (Objects.requireNonNull(plot).getStatus() == Status.unfinished) { - if (sender.hasPermission("plotsystem.review") || plot.getPlotOwner().getUUID().equals(getPlayer(sender).getUniqueId())) { - if (PlotUtils.Actions.abandonPlot(plot)) { - sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.ABANDONED_PLOT, plot.getID() + ""))); - if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.ABANDON_PLOT_SOUND, 1, 1); - } - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); - } - } else { + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + if (plot.getStatus() != Status.unfinished) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_ABANDON_UNFINISHED_PLOTS))); + return; + } + if (!sender.hasPermission("plotsystem.review") && !plot.getPlotOwner().getUUID().equals(getPlayer(sender).getUniqueId())) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); + return; } - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + if (PlotUtils.Actions.abandonPlot(plot)) { + sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.ABANDONED_PLOT, plot.getID() + ""))); + if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.ABANDON_PLOT_SOUND, 1, 1); + } + }); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java index 0af9373d..9af8c787 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.FeedbackMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; @@ -39,9 +40,9 @@ import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; -import java.sql.SQLException; -import java.util.Objects; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -53,46 +54,44 @@ public CMD_Plot_Feedback(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { - if (getPlayer(sender) != null) { - Plot plot; - if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - if (PlotUtils.plotExists(plotID)) { - plot = new Plot(plotID); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; - } - } else if (PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.completed); - if (p instanceof Plot) { - plot = (Plot) p; - } else { - sendInfo(sender); - return; - } - } else { + Player player = getPlayer(sender); + if (getPlayer(sender) == null) { + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + CompletableFuture.runAsync(() -> { + Plot plot; + if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { + plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + } else if (player != null && PlotUtils.isPlotWorld(player.getWorld())) { + AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); + if (!(p instanceof Plot)) { sendInfo(sender); return; } - - if (Objects.requireNonNull(plot).getPlotOwner().getUUID().equals(getPlayer(sender).getUniqueId()) || plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getPlayer(sender).getUniqueId())) || getPlayer(sender).hasPermission("plotsystem.plot.review")) { - if (plot.isReviewed()) { - new FeedbackMenu(getPlayer(sender), plot.getID()); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_HAS_NOT_YET_REVIEWED))); - } - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); - } + plot = (Plot) p; } else { - Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + sendInfo(sender); + return; } - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + if (!plot.getPlotOwner().getUUID().equals(player.getUniqueId()) + && plot.getPlotMembers().stream().noneMatch(m -> m.getUUID().equals(player.getUniqueId())) && !player.hasPermission("plotsystem.plot.review")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; + } + if (!plot.isReviewed()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_HAS_NOT_YET_REVIEWED))); + return; + } + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new FeedbackMenu(player, plot.getID())); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java index 6c7ad623..b21a3181 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java @@ -31,10 +31,11 @@ import com.alpsbte.plotsystem.utils.PlotMemberInvitation; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; - -import java.sql.SQLException; +import org.bukkit.entity.Player; import static net.kyori.adventure.text.Component.text; @@ -46,40 +47,49 @@ public CMD_Plot_Invite(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length > 0) { - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if (getPlayer(sender) != null && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { - PlotMemberInvitation invite = null; - for (PlotMemberInvitation item : PlotMemberInvitation.invitationsList) { - if (item.invitee.getUniqueId().toString().equals(getPlayer(sender).getUniqueId().toString())) { - invite = item; - try { - switch (args[0]) { - case "accept": - item.acceptInvite(); - break; - case "reject": - item.rejectInvite(); - break; - default: - sendInfo(sender); - break; - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - } - } - - if (invite != null) { - PlotMemberInvitation.invitationsList.remove(invite); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_INVITATIONS))); - } - } - } else { + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + if (args.length == 0) { sendInfo(sender); + return; + } + + // TODO: don't register command if this config value is false + FileConfiguration config = PlotSystem.getPlugin().getConfig(); + if (!config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + return; + } + + PlotMemberInvitation invite = null; + for (PlotMemberInvitation item : PlotMemberInvitation.invitationsList) { + if (!item.invitee.getUniqueId().toString().equals(player.getUniqueId().toString())) { + continue; + } + + invite = item; + switch (args[0]) { + case "accept": + item.acceptInvite(); + break; + case "reject": + item.rejectInvite(); + break; + default: + sendInfo(sender); + break; + } } + + if (invite == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_INVITATIONS))); + return; + } + + PlotMemberInvitation.invitationsList.remove(invite); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java index 955eec37..3fd369b2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java @@ -25,9 +25,9 @@ package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; @@ -37,8 +37,9 @@ import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; -import java.sql.SQLException; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -50,26 +51,35 @@ public CMD_Plot_Links(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { - if (getPlayer(sender) != null) { - if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - if (PlotUtils.plotExists(plotID)) { - PlotUtils.ChatFormatting.sendLinkMessages(new Plot(plotID), getPlayer(sender)); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - } - } else if (PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - PlotUtils.ChatFormatting.sendLinkMessages(PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.unfinished, Status.unreviewed), getPlayer(sender)); - } else { + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + CompletableFuture.runAsync(() -> { + Builder builder = Builder.byUUID(player.getUniqueId()); + if (args.length == 0) { + if (!PlotUtils.isPlotWorld(player.getWorld())) { sendInfo(sender); + return; } - } else { - Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + PlotUtils.ChatFormatting.sendLinkMessages(PlotUtils.getCurrentPlot(builder, Status.unfinished, Status.unreviewed), player); + return; } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + if (AlpsUtils.tryParseInt(args[0]) == null) { + sendInfo(sender); + return; + } + Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + + PlotUtils.ChatFormatting.sendLinkMessages(plot, player); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java index e60229fb..84570334 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java @@ -25,9 +25,9 @@ package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.PlotMemberMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; @@ -38,9 +38,9 @@ import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; -import java.sql.SQLException; -import java.util.Objects; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -52,45 +52,40 @@ public CMD_Plot_Members(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { - if (getPlayer(sender) != null) { - Plot plot; - // Get Plot - if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - //plot members - int plotID = Integer.parseInt(args[0]); - if (PlotUtils.plotExists(plotID)) { - plot = new Plot(plotID); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("This plot does not exist!")); - return; - } - } else if (PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - //plot members - AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.unfinished, Status.unreviewed); - if (p instanceof Plot) { - plot = (Plot) p; - } else { - sendInfo(sender); - return; - } - } else { - sendInfo(sender); + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + CompletableFuture.runAsync(() -> { + Plot plot; + if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { + plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("This plot does not exist!")); return; } - - if (Objects.requireNonNull(plot).getPlotOwner().getUUID().equals(getPlayer(sender).getUniqueId()) || getPlayer(sender).hasPermission("plotsystem.admin")) { - new PlotMemberMenu(plot, getPlayer(sender)); + } else if (PlotUtils.isPlotWorld(player.getWorld())) { + AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished, Status.unreviewed); + if (p instanceof Plot) { + plot = (Plot) p; } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("You don't have permission to manage this plot's members!")); + sendInfo(sender); + return; } } else { - Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + sendInfo(sender); + return; } - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + if (!plot.getPlotOwner().getUUID().equals(player.getUniqueId()) && !player.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("You don't have permission to manage this plot's members!")); + return; + } + + new PlotMemberMenu(plot, player); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java index 1389b4a8..227dfd19 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -35,10 +36,14 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.sql.SQLException; -import java.util.Objects; +import java.util.List; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -50,59 +55,69 @@ public CMD_Plot_Submit(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { + Player player = getPlayer(sender); + if (getPlayer(sender) == null) { + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + CompletableFuture.runAsync(() -> { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - if (PlotUtils.plotExists(plotID)) { - plot = new Plot(plotID); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; - } - } else if (getPlayer(sender) != null && PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId())); - if (p instanceof Plot) { - plot = (Plot) p; - } else { + plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + } else if (player != null && PlotUtils.isPlotWorld(player.getWorld())) { + AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); + if (!(p instanceof Plot)) { sendInfo(sender); return; } + plot = (Plot) p; } else { sendInfo(sender); return; } - if (sender.hasPermission("plotsystem.review") || Objects.requireNonNull(plot).getPlotOwner().getUUID().equals(getPlayer(sender).getUniqueId())) { - if (Objects.requireNonNull(plot).getStatus() == Status.unfinished) { - PlotUtils.Actions.submitPlot(plot); + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + if (!sender.hasPermission("plotsystem.review") && !plot.getPlotOwner().getUUID().equals(player.getUniqueId())) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); + return; + } + if (plot.getStatus() != Status.unfinished) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_SUBMIT_UNFINISHED_PLOTS))); + return; + } - if (plot.getPlotMembers().isEmpty()) { - // Plot was made alone - langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), plot.getPlotOwner().getName()); - } else { - // Plot was made in a group - StringBuilder sb = new StringBuilder(plot.getPlotOwner().getName() + ", "); - - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), sb.toString()); - } + List plotMembers = plot.getPlotMembers(); + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); + try { + PlotUtils.Actions.submitPlot(plot); + } catch (SQLException e) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); + } + if (plotMembers.isEmpty()) { + // Plot was made alone + langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), plot.getPlotOwner().getName()); } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_SUBMIT_UNFINISHED_PLOTS))); + // Plot was made in a group + StringBuilder sb = new StringBuilder(plot.getPlotOwner().getName() + ", "); + + for (int i = 0; i < plotMembers.size(); i++) { + sb.append(i == plotMembers.size() - 1 ? + plotMembers.get(i).getName() : + plotMembers.get(i).getName() + ", "); + } + langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), sb.toString()); } - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); - } - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + player.playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); + }); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index 0ce04f45..d6bedf0d 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -29,18 +29,20 @@ import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.ICommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import java.sql.SQLException; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -52,30 +54,45 @@ public CMD_Plot_Teleport(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { - if (getPlayer(sender) != null) { - if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - Plot plot; - if (PlotUtils.plotExists(plotID) && (plot = new Plot(plotID)).getStatus() != Status.unclaimed) { - plot.getWorld().teleportPlayer(getPlayer(sender)); - } else { - if (sender.hasPermission("plotsystem.admin") && PlotUtils.plotExists(plotID)) { - new DefaultPlotGenerator(new Plot(plotID), Builder.byUUID(getPlayer(sender).getUniqueId())); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - } + if (getPlayer(sender) == null) { + Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + if (args.length == 0 || AlpsUtils.tryParseInt(args[0]) == null) { + sendInfo(sender); + return; + } + + int plotID = Integer.parseInt(args[0]); + + CompletableFuture.runAsync(() -> { + Plot plot = DataProvider.PLOT.getPlotById(plotID); + + if (plot == null || plot.getStatus() == Status.unclaimed) { + if (sender.hasPermission("plotsystem.admin") && plot != null) { + Builder builder = Builder.byUUID(getPlayer(sender).getUniqueId()); + if (builder == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + return; } - } else { - sendInfo(sender); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + try { + new DefaultPlotGenerator(plot, builder); + } catch (SQLException e) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); + } + }); + return; } - } else { - Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; } - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + plot.getWorld().teleportPlayer(getPlayer(sender)); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java index 421299a2..237ff8e3 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -35,10 +36,13 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import net.kyori.adventure.text.format.NamedTextColor; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.sql.SQLException; -import java.util.Objects; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -50,41 +54,49 @@ public CMD_Plot_UndoSubmit(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - try { + Player player = getPlayer(sender); + if (getPlayer(sender) == null) { + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + return; + } + + CompletableFuture.runAsync(() -> { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - if (PlotUtils.plotExists(plotID)) { - plot = new Plot(plotID); - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; - } - } else if (getPlayer(sender) != null && PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.unreviewed); - if (p instanceof Plot) { - plot = (Plot) p; - } else { + plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + } else if (player != null && PlotUtils.isPlotWorld(player.getWorld())) { + AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); + if (!(p instanceof Plot)) { sendInfo(sender); return; } + plot = (Plot) p; } else { sendInfo(sender); return; } - if (Objects.requireNonNull(plot).getStatus() == Status.unreviewed) { - PlotUtils.Actions.undoSubmit(plot); - - sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.UNDID_SUBMISSION, plot.getID() + ""))); - if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); - } else { + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + if (plot.getStatus() != Status.unreviewed) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_UNDO_SUBMISSIONS_UNREVIEWED_PLOTS))); + return; } - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + try { + PlotUtils.Actions.undoSubmit(plot); + } catch (SQLException e) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); + } + + sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.UNDID_SUBMISSION, plot.getID() + ""))); + player.playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); + }); + }); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 2b5dc314..bb60ebb7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -25,8 +25,10 @@ package com.alpsbte.plotsystem.core.database; import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; +import com.alpsbte.plotsystem.core.database.providers.PlotProvider; public class DataProvider { public static BuilderProvider BUILDER = new BuilderProvider(); public static BuildTeamProviderSql BUILD_TEAM = new BuildTeamProviderSql(); + public static PlotProvider PLOT = new PlotProvider(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java new file mode 100644 index 00000000..76be768c --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -0,0 +1,28 @@ +package com.alpsbte.plotsystem.core.database.providers; + +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.Review; +import com.alpsbte.plotsystem.core.system.plot.Plot; + +import java.util.List; + +public class PlotProvider { + public Plot getPlotById(int plotId) { + // TODO: implement + + // set status + // set owner + + return null; + } + + public List getPlotMembers(int plotId) { + // TODO: implement + return null; + } + + public Review getReview(int plotId) { + // TODO: implement + return null; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 6c97e3cd..b37a0074 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -54,7 +54,7 @@ public class FeedbackMenu extends AbstractMenu { private Review review = null; private final Plot plot; - public FeedbackMenu(Player player, int plotID) throws SQLException { + public FeedbackMenu(Player player, int plotID) { super(3, LangUtil.getInstance().get(player, LangPaths.MenuTitle.FEEDBACK, String.valueOf(plotID)), player); this.plot = new Plot(plotID); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 9a68d350..4278231c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -107,7 +107,7 @@ public int getID() { */ public abstract void setLastActivity(boolean setNull) throws SQLException; - public abstract Status getStatus() throws SQLException; + public abstract Status getStatus(); public abstract void setStatus(@NotNull Status status) throws SQLException; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 9402b09c..9dc16847 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.core.system.plot; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.PlotSystem; @@ -53,7 +54,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; @@ -63,11 +63,13 @@ public class Plot extends AbstractPlot { private CityProject city; private CityPlotWorld cityPlotWorld; + private Status status; public Plot(int id) { super(id); } + public CityProject getCity() throws SQLException { if (this.city != null) return this.city; @@ -106,26 +108,11 @@ public PlotDifficulty getDifficulty() throws SQLException { } @Override - public Builder getPlotOwner() throws SQLException { + public Builder getPlotOwner() { + // TODO: implement + if (plotOwner != null) return plotOwner; - - if (getStatus() != Status.unclaimed) { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT owner_uuid FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - - plotOwner = Builder.byUUID(UUID.fromString(s)); - - return plotOwner; - } - - DatabaseConnection.closeResultSet(rs); - } - } return null; } @@ -141,26 +128,8 @@ public void setPlotOwner(String UUID) throws SQLException { plotOwner = null; } - public List getPlotMembers() throws SQLException { - List builders = new ArrayList<>(); - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT member_uuids FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - String members = rs.getString(1); - if (!rs.wasNull()) { - String[] uuidMembers = members.split(","); - - for (String uuid : uuidMembers) { - builders.add(Builder.byUUID(UUID.fromString(uuid))); - } - } - } - - DatabaseConnection.closeResultSet(rs); - } - return builders; + public List getPlotMembers() { + return DataProvider.PLOT.getPlotMembers(ID); } public void setPlotMembers(@NotNull List plotMembers) throws SQLException { @@ -239,19 +208,8 @@ public void setLastActivity(boolean setNull) throws SQLException { } @Override - public Status getStatus() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT status FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return Status.valueOf(s); - } - - DatabaseConnection.closeResultSet(rs); - return null; - } + public Status getStatus() { + return status; } @Override @@ -450,21 +408,8 @@ public Slot getSlot() throws SQLException { } } - public Review getReview() throws SQLException { - if (getStatus() == Status.completed || isRejected()) { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT review_id FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return new Review(i); - } - - DatabaseConnection.closeResultSet(rs); - } - } - return null; + public Review getReview() { + return DataProvider.PLOT.getReview(ID); } public void setPasted(boolean pasted) throws SQLException { @@ -498,7 +443,7 @@ public void removePlotMember(Builder member) throws SQLException { } } - public boolean isReviewed() throws SQLException { + public boolean isReviewed() { return getReview() != null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 8d064f5b..ff4df0cc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -83,7 +83,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; -import java.sql.ResultSet; import java.sql.SQLException; import java.text.DecimalFormat; import java.util.*; @@ -107,7 +106,7 @@ private PlotUtils() {} * @return the current plot of the player */ @Nullable - public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) throws SQLException { + public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { if (builder.isOnline()) { String worldName = builder.getPlayer().getWorld().getName(); @@ -339,22 +338,6 @@ public static void syncPlotSchematicFiles() { } } - public static boolean plotExists(int id) { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT COUNT(id) FROM plotsystem_plots WHERE id = ?") - .setValue(id).executeQuery()) { - - if (rs.next() && rs.getInt(1) > 0) { - DatabaseConnection.closeResultSet(rs); - return true; - } - - DatabaseConnection.closeResultSet(rs); - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; - } - public static final class Actions { private Actions() {} public static void submitPlot(Plot plot) throws SQLException { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java index 9fe5455a..f8757b20 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java @@ -98,7 +98,7 @@ public PlotMemberInvitation(Player invitee, Plot plot) throws SQLException { }, 20 * 30); } - public void acceptInvite() throws SQLException { + public void acceptInvite() { Builder builder = Builder.byUUID(invitee.getUniqueId()); if (builder.getFreeSlot() != null) { plot.addPlotMember(Builder.byUUID(invitee.getUniqueId())); @@ -117,7 +117,7 @@ public void acceptInvite() throws SQLException { } } - public void rejectInvite() throws SQLException { + public void rejectInvite() { invitee.sendMessage(Utils.ChatUtils.getInfoFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(invitee, LangPaths.Message.Info.PLAYER_INVITE_REJECTED, TEXT_HIGHLIGHT_START + plot.getPlotOwner().getName() + TEXT_HIGHLIGHT_END)))); plot.getPlotOwner().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(plot.getPlotOwner().getPlayer(), From 4809b64f12e2e5d7fd0b6d24db0ef4f577cc9f67 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Tue, 21 Jan 2025 01:18:00 +0100 Subject: [PATCH 008/175] cleanup commands --- .../plotsystem/commands/CMD_Companion.java | 11 ++--- .../plotsystem/commands/CMD_Plots.java | 12 +++--- .../plotsystem/commands/CMD_Tutorial.java | 43 ++++++++++--------- .../commands/admin/CMD_DeletePlot.java | 12 ++++-- .../plotsystem/core/system/Builder.java | 6 +-- .../plotsystem/core/system/Review.java | 3 +- .../plotsystem/core/system/plot/Plot.java | 1 + 7 files changed, 48 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java index cd708789..4923b2c1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java @@ -54,16 +54,17 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - if (getPlayer(sender) == null) return true; + Player player = getPlayer(sender); + if (player == null) return true; try { FileConfiguration config = PlotSystem.getPlugin().getConfig(); - Tutorial tutorial = AbstractTutorial.getActiveTutorial(getPlayer(sender).getUniqueId()); + Tutorial tutorial = AbstractTutorial.getActiveTutorial(player.getUniqueId()); if (tutorial != null) { - new TutorialStagesMenu(getPlayer(sender), tutorial.getId()); + new TutorialStagesMenu(player, tutorial.getId()); } else if (config.getBoolean(ConfigPaths.TUTORIAL_ENABLE) && config.getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && - !TutorialPlot.isPlotCompleted(getPlayer(sender), TutorialCategory.BEGINNER.getId()) && getPlayer(sender).hasPermission("plotsystem.tutorial")) { - new TutorialsMenu(getPlayer(sender)); + !TutorialPlot.isPlotCompleted(player, TutorialCategory.BEGINNER.getId()) && player.hasPermission("plotsystem.tutorial")) { + new TutorialsMenu(player); } else CompanionMenu.open((Player) sender); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java index 91cb9650..f1f830c2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java @@ -43,17 +43,17 @@ public class CMD_Plots extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { - if (!sender.hasPermission(getPermission())) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); - return true; - } - Player player = getPlayer(sender); if (player == null) { Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return true; } + if (!sender.hasPermission(getPermission())) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return true; + } + if (args.length < 1) { CompletableFuture.runAsync(() -> { Builder builder = Builder.byUUID(player.getUniqueId()); @@ -62,7 +62,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } CompletableFuture.runAsync(() -> { - Builder builder = Builder.byName(args[0]); + Builder builder = Builder.byName(args[0]); Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (builder == null) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java index a98b526f..ba87ce34 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java @@ -47,29 +47,30 @@ public class CMD_Tutorial extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { - if (sender.hasPermission(getPermission())) { - if (getPlayer(sender) != null) { - if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE)) { - if (args.length == 0) { - Tutorial tutorial = AbstractTutorial.getActiveTutorial(getPlayer(sender).getUniqueId()); - if (tutorial != null) { - new TutorialStagesMenu(tutorial.getPlayer(), tutorial.getId()); - } else { - new TutorialsMenu(getPlayer(sender)); - } - } else if (args.length == 1 && AlpsUtils.tryParseInt(args[0]) != null) { - int tutorialId = Integer.parseInt(args[0]); - if (TutorialCategory.byId(tutorialId) == null) return true; - AbstractTutorial.loadTutorial(getPlayer(sender), tutorialId); - } - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.TUTORIAL_DISABLED))); - } + if (!sender.hasPermission(getPermission())) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return true; + } + if (getPlayer(sender) == null) { + Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + return true; + } + if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE)) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.TUTORIAL_DISABLED))); + return true; + } + + if (args.length == 0) { + Tutorial tutorial = AbstractTutorial.getActiveTutorial(getPlayer(sender).getUniqueId()); + if (tutorial != null) { + new TutorialStagesMenu(tutorial.getPlayer(), tutorial.getId()); } else { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + new TutorialsMenu(getPlayer(sender)); } - } else { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + } else if (args.length == 1 && AlpsUtils.tryParseInt(args[0]) != null) { + int tutorialId = Integer.parseInt(args[0]); + if (TutorialCategory.byId(tutorialId) == null) return true; + AbstractTutorial.loadTutorial(getPlayer(sender), tutorialId); } return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java index c21bab12..530b72f5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java @@ -25,11 +25,13 @@ package com.alpsbte.plotsystem.commands.admin; import com.alpsbte.alpslib.utils.AlpsUtils; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; @@ -59,10 +61,12 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } sender.sendMessage(Utils.ChatUtils.getInfoFormat("Deleting plot...")); - if (PlotUtils.Actions.deletePlot(plot)) { - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully deleted plot with the ID §6#" + plotID + "§a!")); - if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); - } else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An unexpected error has occurred!")); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + if (PlotUtils.Actions.deletePlot(plot)) { + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully deleted plot with the ID §6#" + plotID + "§a!")); + if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); + } else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An unexpected error has occurred!")); + }); }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index ee14e620..f1ad561c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -83,11 +83,11 @@ public boolean addScore(int score) { public Plot getSlot(Slot slot) { if (slot == Slot.FIRST && firstSlot != -1) { - return new Plot(firstSlot); + return DataProvider.PLOT.getPlotById(firstSlot); } else if (slot == Slot.SECOND && secondSlot != -1) { - return new Plot(secondSlot); + return DataProvider.PLOT.getPlotById(secondSlot); } else if (slot == Slot.THIRD && thirdSlot != -1) { - return new Plot(thirdSlot); + return DataProvider.PLOT.getPlotById(thirdSlot); } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java index 3dc5c171..bb6b8aae 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Category; @@ -203,7 +204,7 @@ public boolean isFeedbackSent() throws SQLException { public static void undoReview(Review review) { Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { try { - Plot plot = new Plot(review.getPlotID()); + Plot plot = DataProvider.PLOT.getPlotById(review.getPlotID()); for (Builder member : plot.getPlotMembers()) { member.addScore(-plot.getSharedScore()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 9dc16847..a0d8e2b1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -65,6 +65,7 @@ public class Plot extends AbstractPlot { private CityPlotWorld cityPlotWorld; private Status status; + // TODO: delete constructor public Plot(int id) { super(id); } From da81b45a6cb6d5855e09396838b624fe9ec6785e Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Wed, 22 Jan 2025 00:26:53 +0100 Subject: [PATCH 009/175] fix CMD_Review.java and CMD_UndoReview.java --- .../com/alpsbte/plotsystem/PlotSystem.java | 11 +- .../commands/review/CMD_Review.java | 121 +++++++----------- .../commands/review/CMD_UndoReview.java | 66 ++++++---- .../database/providers/BuilderProvider.java | 26 +++- .../leaderboards/ScoreLeaderboard.java | 14 +- 5 files changed, 114 insertions(+), 124 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index f5609434..913c9baa 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -64,7 +64,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.*; -import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import static net.kyori.adventure.text.Component.empty; @@ -232,13 +231,9 @@ public void onDisable() { } else { // Unload plots for (UUID player : PlotUtils.Cache.getCachedInProgressPlots().keySet()) { - try { - Builder builder = Builder.byUUID(player).get(); - for (Plot plot : PlotUtils.Cache.getCachedInProgressPlots(builder)) { - if (plot != null) plot.getWorld().unloadWorld(true); - } - } catch (InterruptedException | ExecutionException e) { - throw new RuntimeException(e); + Builder builder = Builder.byUUID(player); + for (Plot plot : PlotUtils.Cache.getCachedInProgressPlots(builder)) { + if (plot != null) plot.getWorld().unloadWorld(true); } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 98d4a10c..4affccc2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -27,8 +27,8 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.ReviewMenu; -import com.alpsbte.plotsystem.core.menus.ReviewPlotMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -45,93 +45,66 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; +import java.util.concurrent.CompletableFuture; -import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.RED; public class CMD_Review extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { - if (getPlayer(sender) == null) { + Player player = getPlayer(sender); + if (player == null) { Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } - if (!sender.hasPermission(getPermission())) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); - return true; - } + // TODO: clarify if separate permission node will be needed - if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) == null) { - sendInfo(sender); - return true; - } + CompletableFuture.runAsync(() -> { + if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; + } + + if (args.length < 1 || AlpsUtils.tryParseInt(args[0]) == null) { + sendInfo(sender); + return; + } + + Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + if (plot == null || plot.getStatus() != Status.unreviewed) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, + LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - Plot plot = null; - if (args.length > 0) { - int plotId = Integer.parseInt(args[0]); - if (!PlotUtils.plotExists(plotId)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, - LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; - } - plot = new Plot(plotId); + Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); + if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; } - try { - Builder.Reviewer builder = Builder.byUUID(getPlayer(sender).getUniqueId()).getAsReviewer(); - Player player = (Player) sender; - - // Check if the given plot is valid - if (plot != null && plot.getStatus() != Status.unreviewed) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, - LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; - } - - // Check if the reviewer is on the plot - AbstractPlot currentPlot = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unreviewed); - boolean teleportPlayer = false; - if (currentPlot instanceof Plot cp) { - if (plot != null && plot.getID() != currentPlot.getID()) teleportPlayer = true; - else plot = cp; - } else if (plot == null) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); - return; - } else teleportPlayer = true; - - // If the reviewer is not on the plot, teleport the player - if (teleportPlayer) { - Plot finalPlot = plot; - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> finalPlot.getWorld().teleportPlayer(player)); - return; - } - - // Check if player is allowed to review this plot (cannot be the owner or a member of this plot) - if ((plot.getPlotOwner().getUUID().toString().equals(player.getUniqueId().toString()) || - (!plot.getPlotMembers().isEmpty() && plot.getPlotMembers().stream() - .anyMatch(b -> b.getUUID().toString().equals(player.getUniqueId().toString())))) && - !PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, - LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); - return; - } - - // Check if the reviewer is allowed to review this plot in this city project - int countryID = plot.getCity().getCountry().getID(); - if (builder.getCountries().stream().anyMatch(c -> c.getID() == countryID)) { - Plot finalPlot = plot; - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewPlotMenu(player, finalPlot)); - return; - } - - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + // TODO: clarify if plot members will include owner as well + // Players cannot review their own plots + if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) + && plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId())) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); } + + // Check if the reviewer is on the plot + AbstractPlot currentPlot = PlotUtils.getCurrentPlot(builder, Status.unreviewed); + boolean teleportPlayer = false; + if (currentPlot instanceof Plot) { + if (plot.getID() != currentPlot.getID()) teleportPlayer = true; + } else teleportPlayer = true; + + // If the reviewer is not on the plot, teleport the player + if (teleportPlayer) { + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> plot.getWorld().teleportPlayer(player)); + return; + } + + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); }); return true; } @@ -153,6 +126,6 @@ public String[] getParameter() { @Override public String getPermission() { - return "plotsystem.review"; + return ""; } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index 1224e274..3f33cf95 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -27,57 +27,71 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; +import java.util.concurrent.CompletableFuture; -import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.RED; public class CMD_UndoReview extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { - if (!sender.hasPermission(getPermission())) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } - if (args.length == 0 || AlpsUtils.tryParseInt(args[0]) == null) { - sendInfo(sender); - return true; - } + // TODO: clarify if separate permission node will be needed - int plotID = Integer.parseInt(args[0]); - if (!PlotUtils.plotExists(plotID)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return true; - } + CompletableFuture.runAsync(() -> { + if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; + } - try { - Plot plot = new Plot(plotID); - if (!plot.isReviewed()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_EITHER_UNCLAIMED_OR_UNREVIEWED))); - return true; + if (args.length < 1 || AlpsUtils.tryParseInt(args[0]) == null) { + sendInfo(sender); + return; } - if (getPlayer(sender) != null && !sender.hasPermission("plotsystem.admin") && !plot.getReview().getReviewer().getUUID().equals(getPlayer(sender).getUniqueId())) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_UNDO_REVIEW))); - return true; + Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + if (plot == null || plot.getStatus() != Status.unreviewed) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, + LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + + Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); + if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; + } + + // TODO: clarify if plot members will include owner as well + // Players cannot review their own plots + if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) + && plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId())) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); } Review.undoReview(plot.getReview()); sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UNDID_REVIEW, plot.getID() + "", plot.getPlotOwner().getName()))); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 2b10cc73..1652d778 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; +import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Slot; import javax.annotation.Nullable; @@ -182,6 +183,17 @@ public Slot getFreeSlot(UUID uuid) { return null; } + public boolean canReviewPlot(Builder builder, Plot plot) { + // TODO: implement (check for build team) + // no need to check for plot owner / plot members as this is handled separately + return false; + } + + public boolean isAnyReviewer(UUID uuid) { + // TODO: implement (check if builder is a reviewer of any build team) + return false; + } + /** * Retrieves the leaderboard entry for a specific player based on their UUID and the specified timeframe. * The leaderboard entry includes the player's score, rank, and total number of players. @@ -244,13 +256,13 @@ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { * @return the constructed SQL query as a {@code String}. */ private static String getLeaderboardQuery(@Nullable UUID uuid, LeaderboardTimeframe sortBy) { - String minimumDate = null; - switch (sortBy) { - case DAILY: minimumDate = "(NOW() - INTERVAL 1 DAY)"; break; - case WEEKLY: minimumDate = "(NOW() - INTERVAL 1 WEEK)"; break; - case MONTHLY: minimumDate = "(NOW() - INTERVAL 1 MONTH)"; break; - case YEARLY: minimumDate = "(NOW() - INTERVAL 1 YEAR)"; break; - } + String minimumDate = switch (sortBy) { + case DAILY -> "(NOW() - INTERVAL 1 DAY)"; + case WEEKLY -> "(NOW() - INTERVAL 1 WEEK)"; + case MONTHLY -> "(NOW() - INTERVAL 1 MONTH)"; + case YEARLY -> "(NOW() - INTERVAL 1 YEAR)"; + default -> null; + }; return "SELECT b.name, b.score" + (uuid != null ? ", ROW_NUMBER() OVER (ORDER BY b.score DESC) AS position" : "") + (uuid != null ? ", (SELECT COUNT(*) FROM builder_has_plot bhp_sub " + diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index dd05009f..275479cf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -46,7 +46,6 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; import java.sql.SQLException; import java.text.DecimalFormat; @@ -63,15 +62,12 @@ protected ScoreLeaderboard() { setEnabled(PlotSystem.getPlugin().getConfig().getBoolean(getEnablePath())); setLocation(HologramRegister.getLocation(this)); - new BukkitRunnable() { - @Override - public void run() { - for (Player player : getPlayersInRadiusForRanking()) { - if (AbstractTutorial.getActiveTutorial(player.getUniqueId()) != null) continue; - player.sendActionBar(getPlayerRankingComponent(player)); - } + Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> { + for (Player player : getPlayersInRadiusForRanking()) { + if (AbstractTutorial.getActiveTutorial(player.getUniqueId()) != null) continue; + player.sendActionBar(getPlayerRankingComponent(player)); } - }.runTaskTimerAsynchronously(PlotSystem.getPlugin(), 0L, 20L); + }, 0L, 20L); } @Override From 315c7ba313567565d940e1262f1f5e3f6cd08ecd Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Wed, 22 Jan 2025 22:18:01 +0100 Subject: [PATCH 010/175] update all review commands to work with database rework --- .../commands/review/CMD_EditFeedback.java | 51 +++++++----- .../commands/review/CMD_EditPlot.java | 82 ++++++++++--------- .../commands/review/CMD_Review.java | 2 - .../commands/review/CMD_UndoReview.java | 4 +- .../core/system/plot/AbstractPlot.java | 6 +- .../plotsystem/core/system/plot/Plot.java | 21 +---- 6 files changed, 83 insertions(+), 83 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index 14a4d4c9..f4184acb 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -27,59 +27,72 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.sql.SQLException; +import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.RED; public class CMD_EditFeedback extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { - if (!sender.hasPermission(getPermission())) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } - if (args.length <= 1 || AlpsUtils.tryParseInt(args[0]) == null) {sendInfo(sender); return true;} - int plotID = Integer.parseInt(args[0]); + CompletableFuture.runAsync(() -> { + if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; + } - if (!PlotUtils.plotExists(plotID)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return true; - } + if (args.length < 1 || AlpsUtils.tryParseInt(args[0]) == null) { + sendInfo(sender); + return; + } + + Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - Plot plot = new Plot(plotID); - try { if (!plot.isReviewed() && !plot.isRejected()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_EITHER_UNCLAIMED_OR_UNREVIEWED))); - return true; + return; } - if (getPlayer(sender) != null && !sender.hasPermission("plotsystem.admin") && !plot.getReview().getReviewer().getUUID().equals(((Player) sender).getUniqueId())) { + + Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); + if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_SEND_FEEDBACK))); - return true; + return; } StringBuilder feedback = new StringBuilder(); for (int i = 2; i <= args.length; i++) { feedback.append(args.length == 2 ? "" : " ").append(args[i - 1]); } - plot.getReview().setFeedback(feedback.toString()); + try { + plot.getReview().setFeedback(feedback.toString()); + } catch (SQLException e) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); + } sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, plot.getID() + ""))); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 2c01c1eb..0f6c8346 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.enums.Status; @@ -37,81 +38,84 @@ import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; +import java.util.concurrent.CompletableFuture; -import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.RED; public class CMD_EditPlot extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { - if (getPlayer(sender) == null) { - Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); + Player player = getPlayer(sender); + if (player == null) { + Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } + // TODO: don't register command if this config value is false if (!ConfigUtil.getInstance().configs[1].getBoolean(ConfigPaths.EDITPLOT_ENABLED)) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.COMMAND_DISABLED))); return true; } - if (!sender.hasPermission(getPermission())) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); - return true; - } + CompletableFuture.runAsync(() -> { + if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; + } - try { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - int plotID = Integer.parseInt(args[0]); - if (!PlotUtils.plotExists(plotID)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return true; - } - plot = new Plot(plotID); - } else if (getPlayer(sender) != null && PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.unfinished, Status.unreviewed); - if (p instanceof Plot) { - plot = (Plot) p; - } else { + plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + } else if (PlotUtils.isPlotWorld(player.getWorld())) { + AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); + if (!(p instanceof Plot)) { sendInfo(sender); - return true; + return; } + plot = (Plot) p; } else { sendInfo(sender); - return true; + return; } + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } if (plot.getStatus() == Status.completed) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); - return true; + return; } - Builder builder = Builder.byUUID(getPlayer(sender).getUniqueId()); - int countryID = plot.getCity().getCountry().getID(); - if (!builder.isReviewer() || builder.getAsReviewer().getCountries().stream().noneMatch(c -> c.getID() == countryID) || plot.getPlotOwner().getUUID() == builder.getUUID() || plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == builder.getUUID())) { - return true; + Builder builder = Builder.byUUID(player.getUniqueId()); + if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); + return; } - if (!plot.getPermissions().hasBuildingPerms(builder.getUUID())) { - plot.getPermissions().addBuilderPerms(builder.getUUID()).save(); - sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.ENABLED_PLOT_PERMISSIONS, plot.getID() + ""))); - return true; - } + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + + if (!plot.getPermissions().hasBuildingPerms(builder.getUUID())) { + plot.getPermissions().addBuilderPerms(builder.getUUID()).save(); + sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.ENABLED_PLOT_PERMISSIONS, plot.getID() + ""))); + return; + } + + plot.getPermissions().removeBuilderPerms(builder.getUUID()).save(); + sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.DISABLED_PLOT_PERMISSIONS, plot.getID() + ""))); + }); + }); + - plot.getPermissions().removeBuilderPerms(builder.getUUID()).save(); - sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.DISABLED_PLOT_PERMISSIONS, plot.getID() + ""))); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 4affccc2..e6c41267 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -58,8 +58,6 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - // TODO: clarify if separate permission node will be needed - CompletableFuture.runAsync(() -> { if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index 3f33cf95..dc894151 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -56,8 +56,6 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - // TODO: clarify if separate permission node will be needed - CompletableFuture.runAsync(() -> { if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); @@ -70,7 +68,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - if (plot == null || plot.getStatus() != Status.unreviewed) { + if (plot == null || plot.getStatus() != Status.completed) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 4278231c..5a72c3b4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -86,7 +86,7 @@ public int getID() { /** * @return plot world, can be one or city plot world */ - public abstract T getWorld() throws SQLException; + public abstract T getWorld(); /** * @return the outline of the plot which contains all corner points of the polygon @@ -172,7 +172,7 @@ public BlockVector3 getCenter() { Vector3 clipboardCenter = clipboard.getRegion().getCenter(); return BlockVector3.at(clipboardCenter.x(), this.getWorld().getPlotHeightCentered(), clipboardCenter.z()); } - } catch (IOException | SQLException ex) { + } catch (IOException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("Failed to load schematic file to clipboard!"), ex); } return null; @@ -181,7 +181,7 @@ public BlockVector3 getCenter() { /** * @return plot permission manager to add or remove build rights */ - public PlotPermissions getPermissions() throws SQLException { + public PlotPermissions getPermissions() { if (plotPermissions == null) plotPermissions = new PlotPermissions(getWorld()); return plotPermissions; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index a0d8e2b1..356727b5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -219,22 +219,9 @@ public void setStatus(@NotNull Status status) throws SQLException { .setValue(status.name()).setValue(this.ID).executeUpdate(); } - public int getTotalScore() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT score FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int score = rs.getInt(1); - if (!rs.wasNull()) { - DatabaseConnection.closeResultSet(rs); - return score; - } - } - - DatabaseConnection.closeResultSet(rs); - - return -1; - } + public int getTotalScore() { + // TODO: implement + return 0; } public void setTotalScore(int score) throws SQLException { @@ -448,7 +435,7 @@ public boolean isReviewed() { return getReview() != null; } - public boolean isRejected() throws SQLException { + public boolean isRejected() { return (getStatus() == Status.unfinished || getStatus() == Status.unreviewed) && getTotalScore() != -1; // -1 == null } From 3748d11ddbcf8bd33058223904a7109d915d6e2c Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 23 Jan 2025 00:29:47 +0100 Subject: [PATCH 011/175] add CityProject, Country and Difficulty Providers --- .../admin/setup/CMD_Setup_BuildTeam.java | 3 +- .../plotsystem/core/EventListener.java | 3 +- .../core/database/DataProvider.java | 6 +- .../providers/CityProjectProvider.java | 12 ++ .../database/providers/CountryProvider.java | 25 ++++ .../providers/DifficultyProvider.java | 23 ++++ .../core/database/providers/PlotProvider.java | 20 ++++ .../core/holograms/PlotsLeaderboard.java | 100 ---------------- .../leaderboards/ScoreLeaderboard.java | 2 +- .../core/menus/PlayerPlotsMenu.java | 79 +++++-------- .../core/menus/PlotActionsMenu.java | 2 +- .../plotsystem/core/menus/ReviewMenu.java | 73 +++++------- .../core/menus/companion/CityProjectMenu.java | 17 +-- .../core/menus/companion/CompanionMenu.java | 74 +++++------- .../core/menus/companion/CountryMenu.java | 31 ++--- .../plotsystem/core/system/CityProject.java | 4 +- .../plotsystem/core/system/Country.java | 111 ++++-------------- .../plotsystem/core/system/Review.java | 4 +- .../plotsystem/core/system/plot/Plot.java | 58 +-------- .../plot/generator/DefaultPlotGenerator.java | 38 +++--- .../plotsystem/utils/enums/Continent.java | 3 +- 21 files changed, 254 insertions(+), 434 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index bf739fed..0e775909 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; @@ -334,7 +335,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team and country exists try { if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - if (Country.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[2]))) { + if (DataProvider.COUNTRY.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[2]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is not added to the build team!")); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 6087f700..6d1dad6a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; @@ -157,7 +158,7 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { // Informing reviewer about new reviews try { if (event.getPlayer().hasPermission("plotsystem.review") && builder.isReviewer()) { - List unreviewedPlots = Plot.getPlots(builder.getAsReviewer().getCountries(), Status.unreviewed); + List unreviewedPlots = DataProvider.PLOT.getPlots(builder.getAsReviewer().getCountries(), Status.unreviewed); if (!unreviewedPlots.isEmpty()) { PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, event.getPlayer()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index bb60ebb7..28dfd0d1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -24,11 +24,13 @@ package com.alpsbte.plotsystem.core.database; -import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; -import com.alpsbte.plotsystem.core.database.providers.PlotProvider; +import com.alpsbte.plotsystem.core.database.providers.*; public class DataProvider { public static BuilderProvider BUILDER = new BuilderProvider(); public static BuildTeamProviderSql BUILD_TEAM = new BuildTeamProviderSql(); public static PlotProvider PLOT = new PlotProvider(); + public static DifficultyProvider DIFFICULTY = new DifficultyProvider(); + public static CityProjectProvider CITY_PROJECT = new CityProjectProvider(); + public static CountryProvider COUNTRY = new CountryProvider(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java new file mode 100644 index 00000000..6142b333 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -0,0 +1,12 @@ +package com.alpsbte.plotsystem.core.database.providers; + +import com.alpsbte.plotsystem.core.system.CityProject; + +import java.util.List; + +public class CityProjectProvider { + public List getCityProjectByCountryCode(String countryCode) { + // TODO: implement + return List.of(); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java new file mode 100644 index 00000000..4a25259c --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -0,0 +1,25 @@ +package com.alpsbte.plotsystem.core.database.providers; + +import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.utils.enums.Continent; + +import java.util.List; + +public class CountryProvider { + public List getCountries() { + // TODO: implement + return List.of(); + } + + public List getCountriesByContinent(Continent continent) { + // TODO: implement + return List.of(); + } + + public Country getCountryByCode(String code) { + // TODO: implement + //Continent continent = Continent.fromDatabase() + + return null; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java new file mode 100644 index 00000000..5a4b4df6 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -0,0 +1,23 @@ +package com.alpsbte.plotsystem.core.database.providers; + +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; + +public class DifficultyProvider { + public double getMultiplier(PlotDifficulty difficulty) { + // TODO: implement + return 0; + } + + public int getScoreRequirement(PlotDifficulty difficulty) { + // TODO: implement + return 0; + } + + public boolean builderMeetsRequirements(Builder builder, PlotDifficulty plotDifficulty) { + int playerScore = builder.getScore(); + int scoreRequirement = getScoreRequirement(plotDifficulty); + return playerScore >= scoreRequirement; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 76be768c..a06f2322 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -1,9 +1,13 @@ package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.CityProject; +import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.enums.Status; +import java.util.ArrayList; import java.util.List; public class PlotProvider { @@ -16,6 +20,22 @@ public Plot getPlotById(int plotId) { return null; } + public List getPlots(List cities, Status... statuses) { + // TODO: implement + return List.of(); + } + + public List getPlots(List countries, Status status) { + List cities = new ArrayList<>(); + countries.forEach(c -> cities.addAll(c.getCityProjects())); + return getPlots(cities, status); + } + + public List getPlots(Builder builder) { + // TODO: get plots where builder is either owner or member + return List.of(); + } + public List getPlotMembers(int plotId) { // TODO: implement return null; diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java deleted file mode 100644 index f8ea20db..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotsLeaderboard.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.holograms; - -import com.alpsbte.alpslib.hologram.DecentHologramDisplay; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.alpsbte.plotsystem.utils.items.BaseItems; -import org.bukkit.inventory.ItemStack; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; -import java.util.logging.Level; - -public class PlotsLeaderboard extends DecentHologramDisplay implements HologramConfiguration { - protected PlotsLeaderboard() { - super(ConfigPaths.PLOTS_LEADERBOARD, null, false); - setLocation(HologramRegister.getLocation(this)); - setEnabled(PlotSystem.getPlugin().getConfig().getBoolean(getEnablePath())); - } - - @Override - public ItemStack getItem() { - return new ItemStack(BaseItems.LEADERBOARD_PLOT.getItem()); - } - - @Override - public String getTitle(UUID playerUUID) { - return "§b§lCOMPLETED PLOTS §6§l[Lifetime]"; - } - - @Override - public List> getContent(UUID playerUUID) { - try { - ArrayList> lines = new ArrayList<>(); - - HashMap entries = Builder.getBuildersByCompletedBuilds(10); - for (int i = 0; i < 10; i++) { - String key = i < entries.size() && entries.get((String) entries.keySet().toArray()[i]) != 0 ? (String) entries.keySet().toArray()[i] : null; - lines.add(new HologramRegister.LeaderboardPositionLine(i + 1, key, entries.get(key) != null ? entries.get(key) : 0)); - } - - return lines; - } catch (SQLException ex) { - PlotSystem.getPlugin().getLogger().log(Level.SEVERE, "An error occurred while reading leaderboard content", ex); - } - return new ArrayList<>(); - } - - @Override - public boolean hasViewPermission(UUID uuid) { - return true; - } - - @Override - public String getEnablePath() { - return ConfigPaths.PLOTS_LEADERBOARD_ENABLE; - } - - @Override - public String getXPath() { - return ConfigPaths.PLOTS_LEADERBOARD_X; - } - - @Override - public String getYPath() { - return ConfigPaths.PLOTS_LEADERBOARD_Y; - } - - @Override - public String getZPath() { - return ConfigPaths.PLOTS_LEADERBOARD_Z; - } -} \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index 275479cf..a3eae44d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -57,7 +57,7 @@ public class ScoreLeaderboard extends DecentHologramPagedDisplay implements Holo private final DecimalFormat df = new DecimalFormat("#.##"); private LeaderboardTimeframe sortByLeaderboard; - protected ScoreLeaderboard() { + public ScoreLeaderboard() { super("score-leaderboard", null, false, PlotSystem.getPlugin()); setEnabled(PlotSystem.getPlugin().getConfig().getBoolean(getEnablePath())); setLocation(HologramRegister.getLocation(this)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index d42f73e2..de164245 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -75,48 +76,39 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Set player stats item - try { - getMenu().getSlot(4) - .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(builder.getUUID())) - .setName(text(builder.getName(), GOLD).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE) + ": ", GRAY) - .append(text(builder.getScore(), WHITE))) - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COMPLETED_PLOTS) + ": ", GRAY) - .append(text(builder.getCompletedBuildsCount(), WHITE))) - .build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex); - getMenu().getSlot(4).setItem(MenuItems.errorItem(getMenuPlayer())); - } + getMenu().getSlot(4) + .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(builder.getUUID())) + .setName(text(builder.getName(), GOLD).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE) + ": ", GRAY) + .append(text(builder.getScore(), WHITE))) + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COMPLETED_PLOTS) + ": ", GRAY) + .append(text(builder.getCompletedBuildsCount(), WHITE))) + .build()) + .build()); // Set player plot items - try { - plots = Plot.getPlots(builder); - - plotDisplayCount = Math.min(plots.size(), 36); - for (int i = 0; i < plotDisplayCount; i++) { - Plot plot = plots.get(i); - try { - ItemStack item = switch (plot.getStatus()) { - case unfinished -> BaseItems.PLOT_UNFINISHED.getItem(); - case unreviewed -> BaseItems.PLOT_UNREVIEWED.getItem(); - default -> BaseItems.PLOT_COMPLETED.getItem(); - }; - - getMenu().getSlot(9 + i) - .setItem(new ItemBuilder(item) - .setName(text(plot.getCity().getName() + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) - .setLore(getLore(plot, getMenuPlayer()).build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(9 + i).setItem(MenuItems.errorItem(getMenuPlayer())); - } + plots = DataProvider.PLOT.getPlots(builder); + + plotDisplayCount = Math.min(plots.size(), 36); + for (int i = 0; i < plotDisplayCount; i++) { + Plot plot = plots.get(i); + try { + ItemStack item = switch (plot.getStatus()) { + case unfinished -> BaseItems.PLOT_UNFINISHED.getItem(); + case unreviewed -> BaseItems.PLOT_UNREVIEWED.getItem(); + default -> BaseItems.PLOT_COMPLETED.getItem(); + }; + + getMenu().getSlot(9 + i) + .setItem(new ItemBuilder(item) + .setName(text(plot.getCity().getName() + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) + .setLore(getLore(plot, getMenuPlayer()).build()) + .build()); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + getMenu().getSlot(9 + i).setItem(MenuItems.errorItem(getMenuPlayer())); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } } @@ -125,14 +117,7 @@ protected void setItemClickEventsAsync() { // Add click event for player plot items for (int i = 0; i < plotDisplayCount; i++) { int itemSlot = i; - getMenu().getSlot(9 + i).setClickHandler((clickPlayer, clickInformation) -> { - try { - new PlotActionsMenu(clickPlayer, plots.get(itemSlot)); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - clickPlayer.closeInventory(); - } - }); + getMenu().getSlot(9 + i).setClickHandler((clickPlayer, clickInformation) -> new PlotActionsMenu(clickPlayer, plots.get(itemSlot))); } // Set click event for back item diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 7b0c8f65..66d00b8e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -55,7 +55,7 @@ public class PlotActionsMenu extends AbstractMenu { private final Plot plot; private final boolean hasFeedback; - public PlotActionsMenu(Player menuPlayer, Plot plot) throws SQLException { + public PlotActionsMenu(Player menuPlayer, Plot plot) { super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getID() + " | " + plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), menuPlayer); this.plot = plot; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 03b40ed7..6792a935 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -63,8 +64,8 @@ protected List getSource() { List plots = new ArrayList<>(); try { countries = Builder.byUUID(getMenuPlayer().getUniqueId()).getAsReviewer().getCountries(); - plots.addAll(Plot.getPlots(countries, Status.unreviewed)); - plots.addAll(Plot.getPlots(countries, Status.unfinished)); + plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unreviewed)); + plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unfinished)); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } @@ -87,29 +88,22 @@ protected void setPaginatedMenuItemsAsync(List source) { // Set unreviewed and unfinished plot items List plots = getFilteredPlots(source); for (int i = 0; i < plots.size(); i++) { - try { - Plot plot = plots.get(i); - List lines = new ArrayList<>(); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.ID) + ": §f" + plot.getID()); - lines.add(""); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER) + ": §f" + plot.getPlotOwner().getName()); - if (!plot.getPlotMembers().isEmpty()) lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBERS) + ": §f" + plot.getPlotMembers().stream().map(m -> { - try {return m.getName();} catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - return ""; - }).collect(Collectors.joining(", ")) - ); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCity().getName()); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": §f" + plot.getCity().getCountry().getName()); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": §f" + plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase()); - - getMenu().getSlot(i + 9).setItem(new ItemBuilder(plot.getStatus() == Status.unfinished ? Material.MAP : Material.FILLED_MAP, 1) - .setName("§b§l" + LangUtil.getInstance().get(getMenuPlayer(), plot.getStatus() == Status.unfinished ? LangPaths.Review.MANAGE_PLOT : LangPaths.Review.REVIEW_PLOT)) - .setLore(lines) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(i).setItem(MenuItems.errorItem(getMenuPlayer())); + Plot plot = plots.get(i); + List lines = new ArrayList<>(); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.ID) + ": §f" + plot.getID()); + lines.add(""); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER) + ": §f" + plot.getPlotOwner().getName()); + if (!plot.getPlotMembers().isEmpty()) { + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBERS) + ": §f" + plot.getPlotMembers().stream().map(Builder::getName).collect(Collectors.joining(", "))); } + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCity().getName()); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": §f" + plot.getCity().getCountry().getName(getMenuPlayer())); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": §f" + plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase()); + + getMenu().getSlot(i + 9).setItem(new ItemBuilder(plot.getStatus() == Status.unfinished ? Material.MAP : Material.FILLED_MAP, 1) + .setName("§b§l" + LangUtil.getInstance().get(getMenuPlayer(), plot.getStatus() == Status.unfinished ? LangPaths.Review.MANAGE_PLOT : LangPaths.Review.REVIEW_PLOT)) + .setLore(lines) + .build()); } } @@ -120,17 +114,12 @@ protected void setPaginatedItemClickEventsAsync(List source) { for (int i = 0; i < plots.size(); i++) { Plot plot = plots.get(i); getMenu().getSlot(i + 9).setClickHandler((player, info) -> { - try { - if (plot.getStatus() == Status.unfinished) { - new PlotActionsMenu(getMenuPlayer(), plot); - return; - } - - player.performCommand("review " + plot.getID()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenuPlayer().closeInventory(); + if (plot.getStatus() == Status.unfinished) { + new PlotActionsMenu(getMenuPlayer(), plot); + return; } + + player.performCommand("review " + plot.getID()); }); } } @@ -152,7 +141,7 @@ protected void setItemClickEventsAsync() { if (countries.isEmpty()) return; if (filteredCountry == null) { - filteredCountry = countries.get(0); + filteredCountry = countries.getFirst(); } else { int index = countries.indexOf(filteredCountry); filteredCountry = index + 1 >= countries.size() ? null : countries.get(index + 1); @@ -196,12 +185,8 @@ protected Mask getMask() { private List getFilteredPlots(List plots) { List filteredPlots = plots.stream().map(p -> (Plot) p).collect(Collectors.toList()); - if (filteredCountry != null) filteredPlots = filteredPlots.stream().filter(p -> { - try { - return p.getCity().getCountry().getID() == filteredCountry.getID(); - } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - return false; - }).collect(Collectors.toList()); + if (filteredCountry != null) + filteredPlots = filteredPlots.stream().filter(p -> p.getCity().getCountry().getCode().equals(filteredCountry.getCode())).collect(Collectors.toList()); return filteredPlots; } @@ -211,9 +196,9 @@ private ItemStack getFilterItem(Player langPlayer) { LegacyLoreBuilder.emptyLine(); countries.forEach(c -> { - if (filteredCountry != null && filteredCountry.getID() == c.getID()) { - LegacyLoreBuilder.addLine("§b§l> §f§l" + filteredCountry.getName()); - } else LegacyLoreBuilder.addLine("§7" + c.getName()); + if (filteredCountry != null && filteredCountry.getCode().equals(c.getCode())) { + LegacyLoreBuilder.addLine("§b§l> §f§l" + filteredCountry.getName(langPlayer)); + } else LegacyLoreBuilder.addLine("§7" + c.getName(langPlayer)); }); return new ItemBuilder(MenuItems.filterItem(getMenuPlayer())) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index c3d478ee..86c7e29c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractPaginatedMenu; import com.alpsbte.plotsystem.core.menus.tutorial.TutorialsMenu; import com.alpsbte.plotsystem.core.system.Builder; @@ -50,7 +51,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; import static net.kyori.adventure.text.Component.text; @@ -60,7 +60,7 @@ public class CityProjectMenu extends AbstractPaginatedMenu { private PlotDifficulty selectedPlotDifficulty; CityProjectMenu(Player player, Country country, PlotDifficulty selectedPlotDifficulty) { - super(6, 4, country.getName() + " → " + LangUtil.getInstance().get(player, LangPaths.MenuTitle.COMPANION_SELECT_CITY), player); + super(6, 4, country.getName(player) + " → " + LangUtil.getInstance().get(player, LangPaths.MenuTitle.COMPANION_SELECT_CITY), player); this.country = country; this.selectedPlotDifficulty = selectedPlotDifficulty; } @@ -162,22 +162,17 @@ protected List getSource() { @Override protected void setPaginatedMenuItemsAsync(List source) { - List cities = source.stream().map(l -> (CityProject) l).collect(Collectors.toList()); + List cities = source.stream().map(l -> (CityProject) l).toList(); int slot = 9; for (CityProject city : cities) { - try { - getMenu().getSlot(slot).setItem(city.getItem(getMenuPlayer(), selectedPlotDifficulty)); - } catch (SQLException e) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); - getMenu().getSlot(slot).setItem(MenuItems.errorItem(getMenuPlayer())); - } + getMenu().getSlot(slot).setItem(city.getItem(getMenuPlayer(), selectedPlotDifficulty)); slot++; } } @Override protected void setPaginatedItemClickEventsAsync(List source) { - List cities = source.stream().map(l -> (CityProject) l).collect(Collectors.toList()); + List cities = source.stream().map(l -> (CityProject) l).toList(); int slot = 9; for (CityProject city : cities) { final int _slot = slot; @@ -199,7 +194,7 @@ protected void setPaginatedItemClickEventsAsync(List source) { return; } - if (selectedPlotDifficulty != null && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_SCORE_REQUIREMENT) && !Plot.hasPlotDifficultyScoreRequirement(builder, selectedPlotDifficulty)) { + if (selectedPlotDifficulty != null && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_SCORE_REQUIREMENT) && !DataProvider.DIFFICULTY.builderMeetsRequirements(builder, selectedPlotDifficulty)) { clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(clickPlayer, LangPaths.Message.Error.PLAYER_NEEDS_HIGHER_SCORE))); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 9d7db8a0..7198d596 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -28,12 +28,12 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.BuilderUtilitiesMenu; import com.alpsbte.plotsystem.core.menus.PlayerPlotsMenu; import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; import com.alpsbte.plotsystem.core.menus.SettingsMenu; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; @@ -44,14 +44,13 @@ import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.CustomHeads; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -65,7 +64,8 @@ public class CompanionMenu { public static boolean hasContinentView() { - return Arrays.stream(Continent.values()).map(continent -> Country.getCountries(continent).size()).filter(count -> count > 0).count() > 1; + // TODO: make this run async + return Arrays.stream(Continent.values()).map(continent -> DataProvider.COUNTRY.getCountriesByContinent(continent).size()).filter(count -> count > 0).count() > 1; } /** @@ -77,9 +77,10 @@ public static void open(Player player) { if (hasContinentView()) { new ContinentMenu(player); } else { - Optional continent = Arrays.stream(Continent.values()).filter(c -> !Country.getCountries(c).isEmpty()).findFirst(); + // TODO: make this run async + Optional continent = Arrays.stream(Continent.values()).filter(c -> !DataProvider.COUNTRY.getCountriesByContinent(c).isEmpty()).findFirst(); - if (!continent.isPresent()) { + if (continent.isEmpty()) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.ERROR_OCCURRED))); return; } @@ -116,18 +117,12 @@ public static HashMap getFooterItems(int startingSlot, Play final int i_ = i; - Plot plot = builder.getPlot(Slot.values()[i]); + Plot plot = builder.getSlot(Slot.values()[i]); items.put(startingSlot + 1 + i, new FooterItem(getPlotMenuItem(plot, Slot.values()[i].ordinal(), player), (clickPlayer, clickInformation) -> { if (plot == null) return; - try { - new PlotActionsMenu(clickPlayer, builder.getPlot(Slot.values()[i_])); - } catch (SQLException ex) { - clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(clickPlayer, LangPaths.Message.Error.ERROR_OCCURRED))); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while opening the plot actions menu!"), ex); - } + new PlotActionsMenu(clickPlayer, builder.getSlot(Slot.values()[i_])); })); - } catch (NullPointerException | SQLException ex) { + } catch (NullPointerException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while placing player slot items!"), ex); items.put(startingSlot + 1 + i, new FooterItem(MenuItems.errorItem(player))); } @@ -152,21 +147,16 @@ public static ItemStack getDifficultyItem(Player player, PlotDifficulty selected } } else item = AlpsHeadUtils.getCustomHead(CustomHeads.WHITE_CONCRETE.getId()); - try { - return new ItemBuilder(item) - .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.PLOT_DIFFICULTY), AQUA).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .emptyLine() - .addLines(selectedPlotDifficulty != null ? Utils.ItemUtils.getFormattedDifficulty(selectedPlotDifficulty) : text(LangUtil.getInstance().get(player, LangPaths.Difficulty.AUTOMATIC), WHITE).decoration(BOLD, true), - selectedPlotDifficulty != null ? text(LangUtil.getInstance().get(player, LangPaths.Difficulty.SCORE_MULTIPLIER) + ": ", GRAY).append(text("x" + Plot.getMultiplierByDifficulty(selectedPlotDifficulty), WHITE)) : empty()) - .emptyLine() - .addLine(text(LangUtil.getInstance().get(player, LangPaths.MenuDescription.PLOT_DIFFICULTY), GRAY)) - .build()) - .build(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - return MenuItems.errorItem(player); - } + return new ItemBuilder(item) + .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.PLOT_DIFFICULTY), AQUA).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .emptyLine() + .addLines(selectedPlotDifficulty != null ? Utils.ItemUtils.getFormattedDifficulty(selectedPlotDifficulty) : text(LangUtil.getInstance().get(player, LangPaths.Difficulty.AUTOMATIC), WHITE).decoration(BOLD, true), + selectedPlotDifficulty != null ? text(LangUtil.getInstance().get(player, LangPaths.Difficulty.SCORE_MULTIPLIER) + ": ", GRAY).append(text("x" + DataProvider.DIFFICULTY.getMultiplier(selectedPlotDifficulty), WHITE)) : empty()) + .emptyLine() + .addLine(text(LangUtil.getInstance().get(player, LangPaths.MenuDescription.PLOT_DIFFICULTY), GRAY)) + .build()) + .build(); } /** @@ -196,16 +186,16 @@ public static class FooterItem { } } - public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) throws SQLException { + public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) { String nameText = LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); - Component statusComp = Component.text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true); - Component slotDescriptionComp = Component.text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), NamedTextColor.GRAY); + TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true); + TextComponent slotDescriptionComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), NamedTextColor.GRAY); Material itemMaterial = Material.MAP; - ArrayList lore = new LoreBuilder() + ArrayList lore = new LoreBuilder() .addLines(slotDescriptionComp, - Component.empty(), - statusComp.append(Component.text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) + empty(), + statusComp.append(text(": Unassigned", GRAY)).decoration(BOLD, true)) .build(); if (plot != null) { @@ -214,16 +204,16 @@ public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPla String plotCityText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.CITY); String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); lore = new LoreBuilder() - .addLines(Component.text(plotIdText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getID(), NamedTextColor.WHITE)), - Component.text(plotCityText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getCity().getName(), NamedTextColor.WHITE)), - Component.text(plotDifficultyText + ": ", NamedTextColor.GRAY).append(Component.text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), NamedTextColor.WHITE)), - Component.empty(), - statusComp.append(Component.text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) + .addLines(text(plotIdText + ": ", NamedTextColor.GRAY).append(text(plot.getID(), NamedTextColor.WHITE)), + text(plotCityText + ": ", NamedTextColor.GRAY).append(text(plot.getCity().getName(), NamedTextColor.WHITE)), + text(plotDifficultyText + ": ", NamedTextColor.GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), NamedTextColor.WHITE)), + empty(), + statusComp.append(text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) .build(); } return new ItemBuilder(itemMaterial, 1 + slotIndex) - .setName(Component.text(nameText, NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) + .setName(text(nameText, NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) .setLore(lore) .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index 113ac69d..ac367211 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -27,11 +27,11 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.core.menus.tutorial.TutorialsMenu; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; -import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.Utils; @@ -46,7 +46,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; import java.util.List; import java.util.Map; @@ -89,12 +88,8 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Set city project items - try { - countryProjects = Country.getCountries(selectedContinent); - setCountryItems(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + countryProjects = DataProvider.COUNTRY.getCountriesByContinent(selectedContinent); + setCountryItems(); } @Override @@ -108,11 +103,7 @@ protected void setItemClickEventsAsync() { getMenu().getSlot(6).setItem(CompanionMenu.getDifficultyItem(getMenuPlayer(), selectedPlotDifficulty)); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.DONE_SOUND, 1, 1); - try { - setCountryItems(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + setCountryItems(); })); // Set click event for tutorial item @@ -154,7 +145,7 @@ protected Mask getMask() { .build(); } - private void setCountryItems() throws SQLException { + private void setCountryItems() { int startingSlot = 9; if (CompanionMenu.hasContinentView()) { getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); @@ -163,16 +154,16 @@ private void setCountryItems() throws SQLException { } for (Country country : countryProjects) { - ItemStack item = country.getHead(); + ItemStack item = country.getCountryItem(getMenuPlayer()); List cities = country.getCityProjects(); - int plotsOpen = Plot.getPlots(cities, Status.unclaimed).size(); - int plotsInProgress = Plot.getPlots(cities, Status.unfinished, Status.unreviewed).size(); - int plotsCompleted = Plot.getPlots(cities, Status.completed).size(); - int plotsUnclaimed = Plot.getPlots(cities, Status.unclaimed).size(); + int plotsOpen = DataProvider.PLOT.getPlots(cities, Status.unclaimed).size(); + int plotsInProgress = DataProvider.PLOT.getPlots(cities, Status.unfinished, Status.unreviewed).size(); + int plotsCompleted = DataProvider.PLOT.getPlots(cities, Status.completed).size(); + int plotsUnclaimed = DataProvider.PLOT.getPlots(cities, Status.unclaimed).size(); getMenu().getSlot(startingSlot + countryProjects.indexOf(country)).setItem(new ItemBuilder(item) - .setName(text(country.getName(), AQUA).decoration(BOLD, true)) + .setName(text(country.getName(getMenuPlayer()), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLine(text(cities.size(), GOLD).append(text(" " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.CityProject.CITIES), GRAY))) .emptyLine() diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index aba728aa..de1e4390 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -78,7 +78,7 @@ public int getID() { return ID; } - public Country getCountry() throws SQLException { + public Country getCountry() { return new Country(countryID); } @@ -100,7 +100,7 @@ public boolean isVisible() { return visible; } - public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) throws SQLException { + public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { ItemStack cpItem = getCountry().getHead(); try { PlotDifficulty cpPlotDifficulty = selectedPlotDifficulty != null ? diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index 4a4b1076..bbb87d25 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -24,118 +24,55 @@ package com.alpsbte.plotsystem.core.system; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; -import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.utils.enums.Continent; +import org.bukkit.Material; +import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.sql.ResultSet; import java.sql.SQLException; -import java.util.ArrayList; import java.util.List; -import static net.kyori.adventure.text.Component.text; - public class Country { - private final int ID; - private int serverID; - - private String name; - private String headID; - - private String continent; + private final String code; - public Country(int ID) throws SQLException { - this.ID = ID; + private String material; + private String customModelData; - try (ResultSet rs = DatabaseConnection.createStatement("SELECT server_id, name, head_id, continent FROM plotsystem_countries WHERE id = ?") - .setValue(this.ID).executeQuery()) { + private Continent continent; - if (rs.next()) { - this.serverID = rs.getInt(1); - this.name = rs.getString(2); - this.headID = rs.getString(3); - this.continent = rs.getString(4); - } + public Country(String code, Continent continent, String material, String customModelData) { + this.code = code; + this.continent = continent; + this.material = material; + this.customModelData = customModelData; - DatabaseConnection.closeResultSet(rs); - } } - public int getID() { - return ID; - } + public String getCode() {return code;} - public Server getServer() throws SQLException { - return new Server(serverID); - } + public String getMaterial() {return material;} - public String getName() { - return name; - } + public String getCustomModelData() {return customModelData;} - public ItemStack getHead() { - return AlpsHeadUtils.getCustomHead(headID); - } + public Continent getContinent() {return continent;} - /** - * Get city projects that are inside this country - *

- * Might be a good idea to put this in CityProject but could work in both classes - * - * @return CityProjects inside this country - */ public List getCityProjects() { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_city_projects WHERE country_id = ?").setValue(getID()).executeQuery()) { - List cityProjects = new ArrayList<>(); - while (rs.next()) { - cityProjects.add(new CityProject(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - return cityProjects; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); - } - - public Continent getContinent() { - return Continent.fromDatabase(continent); + return DataProvider.CITY_PROJECT.getCityProjectByCountryCode(code); } - public static List getCountries() { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_countries ORDER BY server_id").executeQuery()) { - List countries = new ArrayList<>(); - while (rs.next()) { - countries.add(new Country(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - return countries; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); + public String getName(Player player) { + // TODO: get name from new language file + return code; } - public static List getCountries(Continent continent) { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_countries WHERE continent = ? ORDER BY server_id").setValue(continent.databaseEnum).executeQuery()) { - List countries = new ArrayList<>(); - while (rs.next()) { - countries.add(new Country(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - return countries; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); + public ItemStack getCountryItem(Player player) { + return new ItemStack(Material.BARRIER); } + @Deprecated public static void addCountry(int serverID, String name, Continent continent) throws SQLException { DatabaseConnection.createStatement("INSERT INTO plotsystem_countries (id, name, server_id, continent) VALUES (?, ?, ?, ?)") .setValue(DatabaseConnection.getTableID("plotsystem_countries")) @@ -143,11 +80,13 @@ public static void addCountry(int serverID, String name, Continent continent) th .setValue(serverID).setValue(continent.databaseEnum).executeUpdate(); } + @Deprecated() public static void removeCountry(int countryID) throws SQLException { DatabaseConnection.createStatement("DELETE FROM plotsystem_countries WHERE id = ?") .setValue(countryID).executeUpdate(); } + @Deprecated public static void setHeadID(int countryID, int headID) throws SQLException { DatabaseConnection.createStatement("UPDATE plotsystem_countries SET head_id = ? WHERE id = ?") .setValue(headID) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java index bb6b8aae..1492e536 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java @@ -210,7 +210,7 @@ public static void undoReview(Review review) { member.addScore(-plot.getSharedScore()); if (member.getFreeSlot() != null) { - member.setSlot(plot.getID(), member.getFreeSlot()); + member.setSlot(member.getFreeSlot(), plot.getID()); } } @@ -220,7 +220,7 @@ public static void undoReview(Review review) { plot.setPasted(false); if (plot.getPlotOwner().getFreeSlot() != null) { - plot.getPlotOwner().setSlot(plot.getID(), plot.getPlotOwner().getFreeSlot()); + plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID()); } int cityId = plot.getCity().getID(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 356727b5..eb534f93 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -29,7 +29,6 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; @@ -71,41 +70,14 @@ public Plot(int id) { } - public CityProject getCity() throws SQLException { - if (this.city != null) - return this.city; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT city_project_id FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - CityProject cityProject = new CityProject(i); - - this.city = cityProject; - - return cityProject; - } - - DatabaseConnection.closeResultSet(rs); - return null; - } + public CityProject getCity() { + // TODO: implement + return null; } - public PlotDifficulty getDifficulty() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT difficulty_id FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return PlotDifficulty.values()[i - 1]; - } - - DatabaseConnection.closeResultSet(rs); - return null; - } + public PlotDifficulty getDifficulty() { + // TODO: implement + return null; } @Override @@ -449,24 +421,6 @@ public static List getPlots(Status... statuses) throws SQLException { return listPlots(rs); } - public static List getPlots(Builder builder) throws SQLException { - List plots = listPlots(DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots WHERE owner_uuid = '" + builder.getUUID() + "' ORDER BY CAST(status AS CHAR)").executeQuery()); - plots.addAll(listPlots(DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots WHERE INSTR(member_uuids, '" + builder.getUUID() + "') > 0 ORDER BY CAST(status AS CHAR)").executeQuery())); - return plots; - } - - public static List getPlots(Builder builder, Status... statuses) throws SQLException { - List plots = listPlots(DatabaseConnection.createStatement(getStatusQuery(" AND owner_uuid = '" + builder.getUUID().toString() + "'", statuses)).executeQuery()); - plots.addAll(getPlotsAsMember(builder, statuses)); - return plots; - } - - public static List getPlots(List countries, Status status) throws SQLException { - List cities = new ArrayList<>(); - countries.forEach(c -> cities.addAll(c.getCityProjects())); - return getPlots(cities, status); - } - // Temporary fix to receive plots of builder as member private static List getPlotsAsMember(Builder builder, Status... status) throws SQLException { List plots = new ArrayList<>(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 681f7bb5..2ac77ccd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -68,28 +68,24 @@ public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder @Override protected boolean init() { - try { - if (getBuilder().getFreeSlot() != null) { - if (DefaultPlotGenerator.playerPlotGenerationHistory.containsKey(getBuilder().getUUID())) { - if (DefaultPlotGenerator.playerPlotGenerationHistory.get(getBuilder().getUUID()).isBefore(LocalDateTime.now().minusSeconds(10))) { - DefaultPlotGenerator.playerPlotGenerationHistory.remove(getBuilder().getUUID()); - } else { - getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Error.PLEASE_WAIT))); - getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); - return false; - } + if (getBuilder().getFreeSlot() != null) { + if (DefaultPlotGenerator.playerPlotGenerationHistory.containsKey(getBuilder().getUUID())) { + if (DefaultPlotGenerator.playerPlotGenerationHistory.get(getBuilder().getUUID()).isBefore(LocalDateTime.now().minusSeconds(10))) { + DefaultPlotGenerator.playerPlotGenerationHistory.remove(getBuilder().getUUID()); + } else { + getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Error.PLEASE_WAIT))); + getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); + return false; } - - DefaultPlotGenerator.playerPlotGenerationHistory.put(getBuilder().getUUID(), LocalDateTime.now()); - getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Info.CREATING_PLOT))); - getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); - return true; - } else { - getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Error.ALL_SLOTS_OCCUPIED))); - getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex); + + DefaultPlotGenerator.playerPlotGenerationHistory.put(getBuilder().getUUID(), LocalDateTime.now()); + getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Info.CREATING_PLOT))); + getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); + return true; + } else { + getBuilder().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getBuilder().getPlayer(), LangPaths.Message.Error.ALL_SLOTS_OCCUPIED))); + getBuilder().getPlayer().playSound(getBuilder().getPlayer().getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); } return false; } @@ -128,7 +124,7 @@ protected void onComplete(boolean failed, boolean unloadWorld) throws SQLExcepti super.onComplete(failed, false); if (!failed) { - getBuilder().setSlot(plot.getID(), getBuilder().getFreeSlot()); + getBuilder().setSlot(getBuilder().getFreeSlot(), plot.getID()); plot.setStatus(Status.unfinished); ((Plot) plot).setPlotType(plotType); ((Plot) plot).setPlotOwner(getBuilder().getPlayer().getUniqueId().toString()); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java index ee278f2f..90f3be10 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -68,7 +69,7 @@ public static Continent fromDatabase(String databaseEnum) { * @return Menu item */ public ItemStack getItem(Player player) { - List countries = Country.getCountries(this); + List countries = DataProvider.COUNTRY.getCountriesByContinent(this); return new ItemBuilder(Material.COMPASS) .setName(text(LangUtil.getInstance().get(player, langPath), NamedTextColor.YELLOW).decoration(TextDecoration.BOLD, true)) From 6ca11f7d47ab6ef0feaba3d4d1ab527d474fec87 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 23 Jan 2025 00:47:48 +0100 Subject: [PATCH 012/175] open review menu if no args are provided in review command --- .../commands/review/CMD_Review.java | 10 +- .../core/menus/PlotActionsMenu.java | 95 +++--- .../plotsystem/core/menus/PlotMemberMenu.java | 71 ++--- .../plotsystem/core/menus/ReviewPlotMenu.java | 292 +++++++++--------- 4 files changed, 215 insertions(+), 253 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index e6c41267..e9d38f15 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.ReviewMenu; +import com.alpsbte.plotsystem.core.menus.ReviewPlotMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -64,7 +65,12 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - if (args.length < 1 || AlpsUtils.tryParseInt(args[0]) == null) { + if (args.length == 0) { + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); + return; + } + + if (AlpsUtils.tryParseInt(args[0]) == null) { sendInfo(sender); return; } @@ -102,7 +108,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewPlotMenu(player, plot)); }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 66d00b8e..3f670c16 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -36,7 +36,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.CustomHeads; -import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; @@ -46,7 +45,6 @@ import java.sql.SQLException; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; import static net.kyori.adventure.text.format.TextDecoration.BOLD; @@ -65,28 +63,23 @@ public PlotActionsMenu(Player menuPlayer, Plot plot) { @Override protected void setMenuItemsAsync() { // Set plot submit or undo submit item - try { - if (plot.getStatus().equals(Status.unreviewed)) { - getMenu().getSlot(10) - .setItem(new ItemBuilder(Material.FIRE_CHARGE, 1) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.UNDO_SUBMIT), RED).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.UNDO_SUBMIT), true).build()) - .build()); - } else { - getMenu().getSlot(10) - .setItem(new ItemBuilder(Material.NAME_TAG, 1) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT), GREEN).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_PLOT)).color(GRAY), true) - .emptyLine() - .addLine(Utils.ItemUtils.getNoteFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.WONT_BE_ABLE_CONTINUE_BUILDING))) - .build()) - .build()); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(10).setItem(MenuItems.errorItem(getMenuPlayer())); + if (plot.getStatus().equals(Status.unreviewed)) { + getMenu().getSlot(10) + .setItem(new ItemBuilder(Material.FIRE_CHARGE, 1) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.UNDO_SUBMIT), RED).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.UNDO_SUBMIT), true).build()) + .build()); + } else { + getMenu().getSlot(10) + .setItem(new ItemBuilder(Material.NAME_TAG, 1) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT), GREEN).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_PLOT)).color(GRAY), true) + .emptyLine() + .addLine(Utils.ItemUtils.getNoteFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.WONT_BE_ABLE_CONTINUE_BUILDING))) + .build()) + .build()); } // Set teleport to plot item @@ -117,33 +110,29 @@ protected void setMenuItemsAsync() { } // Set plot members item - try { - if (!plot.isReviewed()) { - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { - getMenu().getSlot(22) - .setItem(new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.ADD_BUTTON.getId())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.MANAGE_MEMBERS), AQUA).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.MANAGE_MEMBERS), true) - .emptyLine() - .addLine(Utils.ItemUtils.getNoteFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.SCORE_WILL_BE_SPLIT))) - .build()) - .build()); - } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { - getMenu().getSlot(22) - .setItem(new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.REMOVE_BUTTON.getId())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.LEAVE_PLOT), AQUA).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.LEAVE_PLOT), true) - .emptyLine() - .addLine(Utils.ItemUtils.getNoteFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.WONT_BE_ABLE_CONTINUE_BUILDING))) - .build()) - .build()); - } + if (!plot.isReviewed()) { + FileConfiguration config = PlotSystem.getPlugin().getConfig(); + if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + getMenu().getSlot(22) + .setItem(new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.ADD_BUTTON.getId())) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.MANAGE_MEMBERS), AQUA).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.MANAGE_MEMBERS), true) + .emptyLine() + .addLine(Utils.ItemUtils.getNoteFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.SCORE_WILL_BE_SPLIT))) + .build()) + .build()); + } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { + getMenu().getSlot(22) + .setItem(new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.REMOVE_BUTTON.getId())) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.LEAVE_PLOT), AQUA).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.LEAVE_PLOT), true) + .emptyLine() + .addLine(Utils.ItemUtils.getNoteFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.WONT_BE_ABLE_CONTINUE_BUILDING))) + .build()) + .build()); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } } @@ -152,11 +141,7 @@ protected void setItemClickEventsAsync() { // Set click event for submit or undo submit plot item getMenu().getSlot(10).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); - try { - clickPlayer.performCommand("plot " + (plot.getStatus().equals(Status.unreviewed) ? "undosubmit " : "submit ") + plot.getID()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + clickPlayer.performCommand("plot " + (plot.getStatus().equals(Status.unreviewed) ? "undosubmit " : "submit ") + plot.getID()); }); // Set click event for teleport to plot item diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index 34992e0f..cad4220c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -70,15 +70,11 @@ protected void setPreviewItems() { // Set loading item for plot member items Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - try { - List plotMembers = plot.getPlotMembers(); - for (int i = 1; i <= 3; i++) { - getMenu().getSlot(11 + i).setItem(plotMembers.size() >= i - ? MenuItems.loadingItem(Material.PLAYER_HEAD, getMenuPlayer()) - : emptyMemberSlotItem); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + List plotMembers = plot.getPlotMembers(); + for (int i = 1; i <= 3; i++) { + getMenu().getSlot(11 + i).setItem(plotMembers.size() >= i + ? MenuItems.loadingItem(Material.PLAYER_HEAD, getMenuPlayer()) + : emptyMemberSlotItem); } }); @@ -103,36 +99,28 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Set plot owner item - try { - getMenu().getSlot(10) - .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(plot.getPlotOwner().getUUID())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER), GOLD, BOLD)) - .setLore(new LoreBuilder() - .addLine(plot.getPlotOwner().getName()).build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + getMenu().getSlot(10) + .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(plot.getPlotOwner().getUUID())) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER), GOLD, BOLD)) + .setLore(new LoreBuilder() + .addLine(plot.getPlotOwner().getName()).build()) + .build()); // Set plot member items - try { - builders = plot.getPlotMembers(); - for (int i = 12; i < 15; i++) { - if (builders.size() < (i - 11)) return; - - Builder builder = builders.get(i - 12); - getMenu().getSlot(i) - .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(builder.getUUID())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBER), AQUA, BOLD)) - .setLore(new LoreBuilder() - .addLines(text(builder.getName()), - empty(), - text(Utils.ItemUtils.getActionFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.Action.CLICK_TO_REMOVE_PLOT_MEMBER)))) - .build()) - .build()); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + builders = plot.getPlotMembers(); + for (int i = 12; i < 15; i++) { + if (builders.size() < (i - 11)) return; + + Builder builder = builders.get(i - 12); + getMenu().getSlot(i) + .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(builder.getUUID())) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBER), AQUA, BOLD)) + .setLore(new LoreBuilder() + .addLines(text(builder.getName()), + empty(), + text(Utils.ItemUtils.getActionFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.Action.CLICK_TO_REMOVE_PLOT_MEMBER)))) + .build()) + .build()); } } @@ -163,13 +151,8 @@ protected void setItemClickEventsAsync() { }); // Set click event for back item - getMenu().getSlot(22).setClickHandler((clickPlayer, clickInformation) -> { - try { - new PlotActionsMenu(clickPlayer, plot); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - }); + getMenu().getSlot(22).setClickHandler((clickPlayer, clickInformation) + -> new PlotActionsMenu(clickPlayer, plot)); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java index 836888e2..360ba495 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.menus; -import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; @@ -141,174 +140,168 @@ protected void setMenuItemsAsync() { @Override protected void setItemClickEventsAsync() { // Set click event for back item - getMenu().getSlot(1).setClickHandler((clickPlayer, clickInformation) -> new ReviewMenu(getMenuPlayer())); + getMenu().getSlot(1).setClickHandler((clickPlayer, clickInformation) + -> new ReviewMenu(getMenuPlayer())); // Set click event for close item - getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) -> clickPlayer.closeInventory()); + getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) + -> clickPlayer.closeInventory()); // Set click event for plot info item - getMenu().getSlot(4).setClickHandler((clickPlayer, clickInformation) -> { + getMenu().getSlot(4).setClickHandler((clickPlayer, clickInformation) + -> new PlotActionsMenu(clickPlayer, plot)); + + /* Set click event for submit item */ + getMenu().getSlot(48).setClickHandler((clickPlayer, clickInformation) + -> Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { try { - new PlotActionsMenu(clickPlayer, plot); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - }); - - // Set click event for submit item - getMenu().getSlot(48).setClickHandler((clickPlayer, clickInformation) -> { - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - try { - StringBuilder score = new StringBuilder(); - - int totalRating = 0; - boolean isRejected = false; - - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 6; j++) { - if (Objects.requireNonNull(getMenu().getSlot(11 + (i * 9) + j).getItem(clickPlayer).getItemMeta()).hasEnchant(Enchantment.POWER)) { - if (i == 3) { - score.append(j); - } else { - score.append(j).append(","); - } - totalRating += j; - if (j == 0) isRejected = true; + StringBuilder score = new StringBuilder(); + + int totalRating = 0; + boolean isRejected = false; + + for (int i = 0; i < 4; i++) { + for (int j = 0; j < 6; j++) { + if (Objects.requireNonNull(getMenu().getSlot(11 + (i * 9) + j).getItem(clickPlayer).getItemMeta()).hasEnchant(Enchantment.POWER)) { + if (i == 3) { + score.append(j); + } else { + score.append(j).append(","); } + totalRating += j; + if (j == 0) isRejected = true; } } - if (totalRating <= 8) isRejected = true; - - if (totalRating == 0 && !sentWarning) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_ABANDONED))); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); - sentWarning = true; - return; - } else if (isRejected && !sentWarning) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_REJECTED))); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); - sentWarning = true; - return; - } else if (totalRating == 0) { - plot.setStatus(Status.unfinished); - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> clickPlayer.performCommand("plot abandon " + plot.getID())); - return; - } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> clickPlayer.closeInventory()); - - if (plot.isReviewed()) { - plot.getReview().setRating(score.toString()); - plot.getReview().setReviewer(clickPlayer.getUniqueId()); - } else new Review(plot.getID(), clickPlayer.getUniqueId(), score.toString()); - - double totalRatingWithMultiplier = totalRating * Plot.getMultiplierByDifficulty(plot.getDifficulty()); - totalRating = (int) Math.floor(totalRatingWithMultiplier); - plot.setTotalScore(totalRating); - - Component reviewerConfirmationMessage; - - if (!isRejected) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); - try { - if (!PlotUtils.savePlotAsSchematic(plot)) { - clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); - return; - } - } catch (IOException | SQLException | WorldEditException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); + } + if (totalRating <= 8) isRejected = true; + + if (totalRating == 0 && !sentWarning) { + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_ABANDONED))); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); + sentWarning = true; + return; + } else if (isRejected && !sentWarning) { + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_REJECTED))); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); + sentWarning = true; + return; + } else if (totalRating == 0) { + plot.setStatus(Status.unfinished); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> clickPlayer.performCommand("plot abandon " + plot.getID())); + return; + } + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> clickPlayer.closeInventory()); + + if (plot.isReviewed()) { + plot.getReview().setRating(score.toString()); + plot.getReview().setReviewer(clickPlayer.getUniqueId()); + } else new Review(plot.getID(), clickPlayer.getUniqueId(), score.toString()); + + double totalRatingWithMultiplier = totalRating * Plot.getMultiplierByDifficulty(plot.getDifficulty()); + totalRating = (int) Math.floor(totalRatingWithMultiplier); + plot.setTotalScore(totalRating); + + Component reviewerConfirmationMessage; + + if (!isRejected) { + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); + try { + if (!PlotUtils.savePlotAsSchematic(plot)) { + clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); + return; } + } catch (IOException | SQLException | WorldEditException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); + } - plot.setStatus(Status.completed); - plot.getReview().setFeedbackSent(false); - plot.getReview().setFeedback("No Feedback"); - - // Remove Plot from Owner - plot.getPlotOwner().setSlot(-1, plot.getSlot()); - - if (plot.getPlotMembers().isEmpty()) { - // Plot was made alone - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); - - // Builder gets 100% of score - plot.getPlotOwner().addScore(totalRating); - } else { - // Plot was made in a group - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), sb.toString())); - - // Score gets split between all participants - plot.getPlotOwner().addScore(plot.getSharedScore()); + plot.setStatus(Status.completed); + plot.getReview().setFeedbackSent(false); + plot.getReview().setFeedback("No Feedback"); - for (Builder builder : plot.getPlotMembers()) { - // Score gets split between all participants - builder.addScore(plot.getSharedScore()); + // Remove Plot from Owner + plot.getPlotOwner().setSlot(plot.getSlot(), -1); - // Remove Slot from Member - builder.setSlot(-1, builder.getSlot(plot)); - } - } - } else { - if (!plot.getPlotMembers().isEmpty()) { + if (plot.getPlotMembers().isEmpty()) { // Plot was made alone - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); + + // Builder gets 100% of score + plot.getPlotOwner().addScore(totalRating); } else { // Plot was made in a group StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), sb.toString())); + for (int i = 0; i < plot.getPlotMembers().size(); i++) { + sb.append(i == plot.getPlotMembers().size() - 1 ? + plot.getPlotMembers().get(i).getName() : + plot.getPlotMembers().get(i).getName() + ", "); } + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), sb.toString())); - PlotUtils.Actions.undoSubmit(plot); - } + // Score gets split between all participants + plot.getPlotOwner().addScore(plot.getSharedScore()); - boolean finalIsRejected = isRejected; - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - for (Player player : plot.getWorld().getBukkitWorld().getPlayers()) { - player.teleport(Utils.getSpawnLocation()); - } + for (Builder builder : plot.getPlotMembers()) { + // Score gets split between all participants + builder.addScore(plot.getSharedScore()); - // Delete plot world after reviewing - try { - if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) - plot.getWorld().deleteWorld(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + // Remove Slot from Member + builder.setSlot(plot.getSlot(), -1); + } + } + } else { + if (!plot.getPlotMembers().isEmpty()) { + // Plot was made alone + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); + } else { + // Plot was made in a group + StringBuilder sb = new StringBuilder(); - clickPlayer.sendMessage(reviewerConfirmationMessage); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1f, 1f); + for (int i = 0; i < plot.getPlotMembers().size(); i++) { + sb.append(i == plot.getPlotMembers().size() - 1 ? + plot.getPlotMembers().get(i).getName() : + plot.getPlotMembers().get(i).getName() + ", "); + } + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), sb.toString())); + } - try { - ChatInput.awaitChatInput.put(clickPlayer.getUniqueId(), - new PlayerFeedbackChatInput(clickPlayer.getUniqueId(), plot.getReview())); - PlayerFeedbackChatInput.sendChatInputMessage(clickPlayer); - } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - }); + PlotUtils.Actions.undoSubmit(plot); + } - for (Builder member : plot.getPlotMembers()) { - if (member.isOnline()) PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), member.getPlayer()); + boolean finalIsRejected = isRejected; + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + for (Player player : plot.getWorld().getBukkitWorld().getPlayers()) { + player.teleport(Utils.getSpawnLocation()); } - if (plot.getPlotOwner().isOnline()) { - PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), plot.getPlotOwner().getPlayer()); - plot.getReview().setFeedbackSent(true); + // Delete plot world after reviewing + try { + if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) + plot.getWorld().deleteWorld(); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + + clickPlayer.sendMessage(reviewerConfirmationMessage); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1f, 1f); + + ChatInput.awaitChatInput.put(clickPlayer.getUniqueId(), + new PlayerFeedbackChatInput(clickPlayer.getUniqueId(), plot.getReview())); + PlayerFeedbackChatInput.sendChatInputMessage(clickPlayer); + }); + + for (Builder member : plot.getPlotMembers()) { + if (member.isOnline()) PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), member.getPlayer()); } - }); - }); + + if (plot.getPlotOwner().isOnline()) { + PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), plot.getPlotOwner().getPlayer()); + plot.getReview().setFeedbackSent(true); + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } + })); // Set click event for point selection items for (int i = 0; i < 54; i++) { @@ -364,17 +357,12 @@ private ItemStack getPlotInfoItem() { String plotOwner, city, country, difficulty; Player plotOwnerPlayer; - try { - plotOwner = plot.getPlotOwner().getName(); - city = plot.getCity().getName(); - country = plot.getCity().getCountry().getName(); - difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); + plotOwner = plot.getPlotOwner().getName(); + city = plot.getCity().getName(); + country = plot.getCity().getCountry().getName(getMenuPlayer()); + difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); - plotOwnerPlayer = plot.getPlotOwner().getPlayer(); - } catch (SQLException e) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); - return MenuItems.errorItem(getMenuPlayer()); - } + plotOwnerPlayer = plot.getPlotOwner().getPlayer(); return new ItemBuilder(BaseItems.REVIEW_INFO_PLOT.getItem()) From 9ae7b0117e41a6ef94f5950aef7cc8f990236ee0 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 23 Jan 2025 00:56:50 +0100 Subject: [PATCH 013/175] fix errors --- .../admin/setup/CMD_Setup_Country.java | 5 +-- .../plotsystem/core/EventListener.java | 4 +-- .../core/database/providers/PlotProvider.java | 5 +++ .../core/system/plot/utils/PlotUtils.java | 34 +++++++------------ 4 files changed, 23 insertions(+), 25 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 20353fe4..2c4ad98e 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; @@ -86,7 +87,7 @@ public CMD_Setup_Country_List(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - List countries = Country.getCountries(); + List countries = DataProvider.COUNTRY.getCountries(); if (countries.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no countries registered in the database!")); return; @@ -96,7 +97,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage("§8--------------------------"); for (Country c : countries) { try { - sender.sendMessage(" §6> §b" + c.getID() + " (" + c.getName() + ") §f- Server: " + c.getServer().getID() + " (" + c.getServer().getName() + ")"); + sender.sendMessage(" §6> §b" + c.getCode() + " §f- Server: " + c.getServer().getID() + " (" + c.getServer().getName() + ")"); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 6d1dad6a..187ffd55 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -126,7 +126,7 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { // Informing player about new feedback try { - List plots = Plot.getPlots(builder, Status.completed, Status.unfinished); + List plots = DataProvider.PLOT.getPlots(builder, Status.completed, Status.unfinished); List reviewedPlots = new ArrayList<>(); for (Plot plot : plots) { @@ -146,7 +146,7 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { // Informing player about unfinished plots try { - List plots = Plot.getPlots(builder, Status.unfinished); + List plots = DataProvider.PLOT.getPlots(builder, Status.unfinished); if (!plots.isEmpty()) { PlotUtils.ChatFormatting.sendUnfinishedPlotReminderMessage(plots, event.getPlayer()); event.getPlayer().sendMessage(""); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index a06f2322..65bd5ee7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -36,6 +36,11 @@ public List getPlots(Builder builder) { return List.of(); } + public List getPlots(Builder builder, Status... statuses) { + // TODO: get plots where builder is either owner or member and filter by status + return List.of(); + } + public List getPlotMembers(int plotId) { // TODO: implement return null; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index ff4df0cc..e177d235 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core.system.plot.utils; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; @@ -141,7 +142,7 @@ public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { return null; } - public static boolean isPlayerOnPlot(AbstractPlot plot, Player player) throws SQLException { + public static boolean isPlayerOnPlot(AbstractPlot plot, Player player) { if (plot.getWorld().isWorldLoaded() && plot.getWorld().getBukkitWorld().getPlayers().contains(player)) { Location playerLoc = player.getLocation(); return plot.getWorld().getProtectedRegion().contains(Vector3.toBlockPoint(playerLoc.getX(), playerLoc.getY(), playerLoc.getZ())); @@ -149,7 +150,7 @@ public static boolean isPlayerOnPlot(AbstractPlot plot, Player player) throws SQ return false; } - public static CuboidRegion getPlotAsRegion(AbstractPlot plot) throws IOException, SQLException { + public static CuboidRegion getPlotAsRegion(AbstractPlot plot) throws IOException { Clipboard clipboard = FaweAPI.load(plot.getOutlinesSchematic()); if (clipboard != null) { if (plot.getVersion() >= 3) { @@ -424,7 +425,7 @@ public static boolean abandonPlot(AbstractPlot plot) { if (plot.getPlotOwner() != null) { Cache.clearCache(plot.getPlotOwner().getUUID()); - plot.getPlotOwner().setSlot(-1, dPlot.getSlot()); + plot.getPlotOwner().setSlot(dPlot.getSlot(), -1); } dPlot.setPlotOwner(null); @@ -494,12 +495,7 @@ public static void clearCache(UUID builderUUID) { public static List getCachedInProgressPlots(Builder builder) { if (!cachedInProgressPlots.containsKey(builder.getUUID())) { - try { - cachedInProgressPlots.put(builder.getUUID(), Plot.getPlots(builder, Status.unfinished)); - } catch (SQLException ex) { - Utils.logSqlException(ex); - return new ArrayList<>(); - } + cachedInProgressPlots.put(builder.getUUID(), DataProvider.PLOT.getPlots(builder, Status.unfinished)); } return cachedInProgressPlots.get(builder.getUUID()); @@ -648,18 +644,14 @@ public static void sendLinkMessages(AbstractPlot plot, Player player) { } public static void sendGroupTipMessage(Plot plot, Player player) { - try { - if (plot.getPlotMembers().isEmpty()) { - Component tc = text("» ", DARK_GRAY) - .append(text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_PLAY_WITH_FRIENDS), GRAY)) - .clickEvent(net.kyori.adventure.text.event.ClickEvent.runCommand("/plot members " + plot.getID())) - .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.MEMBERS))); - - player.sendMessage(tc); - player.sendMessage(text(MSG_LINE, DARK_GRAY)); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text(ex.getMessage()), ex); + if (plot.getPlotMembers().isEmpty()) { + Component tc = text("» ", DARK_GRAY) + .append(text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_PLAY_WITH_FRIENDS), GRAY)) + .clickEvent(ClickEvent.runCommand("/plot members " + plot.getID())) + .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.MEMBERS))); + + player.sendMessage(tc); + player.sendMessage(text(MSG_LINE, DARK_GRAY)); } } From bfa6b9038b9802e43b4dc200466e83935f43f09c Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 23 Jan 2025 02:38:32 +0100 Subject: [PATCH 014/175] add Utils.getConfiguredItem --- .../core/menus/companion/CountryMenu.java | 2 +- .../plotsystem/core/system/CityProject.java | 2 +- .../alpsbte/plotsystem/core/system/Country.java | 7 +++---- .../java/com/alpsbte/plotsystem/utils/Utils.java | 16 ++++++++++++++++ .../plotsystem/utils/items/BaseItems.java | 9 ++++----- 5 files changed, 25 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index ac367211..252768f6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -154,7 +154,7 @@ private void setCountryItems() { } for (Country country : countryProjects) { - ItemStack item = country.getCountryItem(getMenuPlayer()); + ItemStack item = country.getCountryItem(); List cities = country.getCityProjects(); int plotsOpen = DataProvider.PLOT.getPlots(cities, Status.unclaimed).size(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index de1e4390..ee8869f6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -101,7 +101,7 @@ public boolean isVisible() { } public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { - ItemStack cpItem = getCountry().getHead(); + ItemStack cpItem = getCountry().getCountryItem(); try { PlotDifficulty cpPlotDifficulty = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(getID(), Builder.byUUID(player.getUniqueId())).get(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index bbb87d25..0a83e932 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -26,8 +26,8 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -48,7 +48,6 @@ public Country(String code, Continent continent, String material, String customM this.continent = continent; this.material = material; this.customModelData = customModelData; - } public String getCode() {return code;} @@ -68,8 +67,8 @@ public String getName(Player player) { return code; } - public ItemStack getCountryItem(Player player) { - return new ItemStack(Material.BARRIER); + public ItemStack getCountryItem() { + return Utils.getConfiguredItem(material, customModelData); } @Deprecated diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 4f144395..dad25f79 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; +import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.menus.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; @@ -88,6 +89,21 @@ public static void updatePlayerInventorySlots(Player player) { }); } + // TODO: extract to alpsLibs? + public static ItemStack getConfiguredItem(String material, Object customModelData) { + ItemStack base; + if (material.startsWith("head(") && material.endsWith(")")) { + String headId = material.substring(material.indexOf("(") + 1, material.lastIndexOf(")")); + base = AlpsHeadUtils.getCustomHead(headId); + } else { + Material mat = Material.getMaterial(material); + base = new ItemStack(mat == null ? Material.BARRIER : mat); + } + ItemBuilder builder = new ItemBuilder(base); + if (customModelData != null) builder.setItemModel(customModelData); + + return builder.build(); + } public static class SoundUtils { private SoundUtils() {} diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index ca875059..da4a4bd3 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -1,6 +1,6 @@ package com.alpsbte.plotsystem.utils.items; -import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -39,10 +39,9 @@ public enum BaseItems { BaseItems(String configPath) { String materialString = ConfigUtil.getInstance().configs[2].getString(configPath + ".material"); - Material material = Material.getMaterial(materialString == null ? "" : materialString, false); - material = material == null ? Material.BARRIER : material; - - itemStack = new ItemBuilder(material).setItemModel(ConfigUtil.getInstance().configs[2].get(configPath + ".modelId")).build(); + materialString = materialString == null ? Material.BARRIER.name() : materialString; + Object customModelData = ConfigUtil.getInstance().configs[2].get(configPath + ".modelId"); + itemStack = Utils.getConfiguredItem(materialString, customModelData); } public ItemStack getItem() { From 95356f8e26e4ab528a56e1cc1a1b87be5502121f Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 23 Jan 2025 03:33:33 +0100 Subject: [PATCH 015/175] extract notices into separate method and fix compiler error --- .../plotsystem/core/EventListener.java | 136 +++++++++--------- 1 file changed, 71 insertions(+), 65 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 187ffd55..01e5f52b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -107,11 +107,6 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } - // Inform player about update - if (event.getPlayer().hasPermission("plotsystem.admin") && PlotSystem.UpdateChecker.updateAvailable() && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.CHECK_FOR_UPDATES)) { - event.getPlayer().sendMessage(Utils.ChatUtils.getInfoFormat("There is a new update for the Plot-System available. Check your console for more information!")); - event.getPlayer().playSound(event.getPlayer().getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); - } // Check if player has changed his name Builder builder = Builder.byUUID(event.getPlayer().getUniqueId()); @@ -124,65 +119,7 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } - // Informing player about new feedback - try { - List plots = DataProvider.PLOT.getPlots(builder, Status.completed, Status.unfinished); - List reviewedPlots = new ArrayList<>(); - - for (Plot plot : plots) { - if (plot.isReviewed() && !plot.getReview().isFeedbackSent()) { - reviewedPlots.add(plot); - plot.getReview().setFeedbackSent(true); - } - } - - if (!reviewedPlots.isEmpty()) { - PlotUtils.ChatFormatting.sendFeedbackMessage(reviewedPlots, event.getPlayer()); - event.getPlayer().sendTitle("", "§6§l" + reviewedPlots.size() + " §a§lPlot" + (reviewedPlots.size() == 1 ? " " : "s ") + (reviewedPlots.size() == 1 ? "has" : "have") + " been reviewed!", 20, 150, 20); - } - } catch (Exception ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his plot feedback!"), ex); - } - - // Informing player about unfinished plots - try { - List plots = DataProvider.PLOT.getPlots(builder, Status.unfinished); - if (!plots.isEmpty()) { - PlotUtils.ChatFormatting.sendUnfinishedPlotReminderMessage(plots, event.getPlayer()); - event.getPlayer().sendMessage(""); - } - } catch (Exception ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his unfinished plots!"), ex); - } - - // Informing reviewer about new reviews - try { - if (event.getPlayer().hasPermission("plotsystem.review") && builder.isReviewer()) { - List unreviewedPlots = DataProvider.PLOT.getPlots(builder.getAsReviewer().getCountries(), Status.unreviewed); - - if (!unreviewedPlots.isEmpty()) { - PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, event.getPlayer()); - } - } - } catch (Exception ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about unreviewed plots!"), ex); - } - - // Start or notify the player if he has not completed the beginner tutorial yet (only if required) - try { - if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && - !TutorialPlot.isPlotCompleted(event.getPlayer(), TutorialCategory.BEGINNER.getId())) { - if (!event.getPlayer().hasPlayedBefore()) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), - () -> event.getPlayer().performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); - } else { - AbstractPlotTutorial.sendTutorialRequiredMessage(event.getPlayer(), TutorialCategory.BEGINNER.getId()); - event.getPlayer().playSound(event.getPlayer().getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); - } - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + sendNotices(event.getPlayer(), builder); }); } @@ -223,7 +160,7 @@ public void onPlayerInteractEvent(PlayerInteractEvent event) { } @EventHandler - public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) throws SQLException { + public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { if (event.getRightClicked().getType().equals(EntityType.PLAYER) && event.getHand() == EquipmentSlot.HAND) { event.getPlayer().performCommand("plots " + Builder.byUUID(event.getRightClicked().getUniqueId()).getName()); } @@ -338,4 +275,73 @@ public void onPlayerChatEvent(AsyncChatEvent event) throws SQLException { public void onLanguageChange(LanguageChangeEvent event) { Utils.updatePlayerInventorySlots(event.getPlayer()); } + + private void sendNotices(Player player, Builder builder) { + // Inform player about update + if (player.hasPermission("plotsystem.admin") && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.CHECK_FOR_UPDATES) && PlotSystem.UpdateChecker.updateAvailable()) { + player.sendMessage(Utils.ChatUtils.getInfoFormat("There is a new update for the Plot-System available. Check your console for more information!")); + player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); + } + + // Informing player about new feedback + try { + List plots = DataProvider.PLOT.getPlots(builder, Status.completed, Status.unfinished); + List reviewedPlots = new ArrayList<>(); + + for (Plot plot : plots) { + if (plot.isReviewed() && !plot.getReview().isFeedbackSent()) { + reviewedPlots.add(plot); + plot.getReview().setFeedbackSent(true); + } + } + + if (!reviewedPlots.isEmpty()) { + PlotUtils.ChatFormatting.sendFeedbackMessage(reviewedPlots, player); + player.sendTitle("", "§6§l" + reviewedPlots.size() + " §a§lPlot" + (reviewedPlots.size() == 1 ? " " : "s ") + (reviewedPlots.size() == 1 ? "has" : "have") + " been reviewed!", 20, 150, 20); + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his plot feedback!"), ex); + } + + // Informing player about unfinished plots + try { + List plots = DataProvider.PLOT.getPlots(builder, Status.unfinished); + if (!plots.isEmpty()) { + PlotUtils.ChatFormatting.sendUnfinishedPlotReminderMessage(plots, player); + player.sendMessage(""); + } + } catch (Exception ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his unfinished plots!"), ex); + } + + // Informing reviewer about new reviews + try { + if (player.hasPermission("plotsystem.admin") || DataProvider.BUILDER.isAnyReviewer(builder.getUUID())) { + List unreviewedPlots = DataProvider.PLOT.getPlots(builder.getAsReviewer().getCountries(), Status.unreviewed); + + if (!unreviewedPlots.isEmpty()) { + PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, player); + } + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about unreviewed plots!"), ex); + } + + + // Start or notify the player if he has not completed the beginner tutorial yet (only if required) + try { + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && + !TutorialPlot.isPlotCompleted(player, TutorialCategory.BEGINNER.getId())) { + if (!player.hasPlayedBefore()) { + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), + () -> player.performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); + } else { + AbstractPlotTutorial.sendTutorialRequiredMessage(player, TutorialCategory.BEGINNER.getId()); + player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); + } + } + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } + } } From fb601522601e5ecc24a96f6859b18a231d363a5a Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 24 Jan 2025 02:17:12 +0100 Subject: [PATCH 016/175] turn CityProject.java into a proper model and extract various methods into providers --- .../admin/setup/CMD_Setup_BuildTeam.java | 43 +++++----- .../commands/admin/setup/CMD_Setup_City.java | 20 ++--- .../admin/setup/CMD_Setup_Country.java | 4 +- .../core/database/DataProvider.java | 2 +- .../BuildTeamProvider.java} | 60 +++++++------- .../providers/CityProjectProvider.java | 18 +++- .../core/database/providers/PlotProvider.java | 5 ++ .../core/menus/companion/CityProjectMenu.java | 2 +- .../plotsystem/core/system/BuildTeam.java | 12 +-- .../plotsystem/core/system/Builder.java | 4 +- .../plotsystem/core/system/CityProject.java | 83 ++++++------------- .../plotsystem/core/system/Country.java | 2 +- .../core/system/plot/utils/PlotUtils.java | 2 +- 13 files changed, 115 insertions(+), 142 deletions(-) rename src/main/java/com/alpsbte/plotsystem/core/database/{BuildTeamProviderSql.java => providers/BuildTeamProvider.java} (68%) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 0e775909..cd5a9f52 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -91,7 +91,7 @@ public CMD_Setup_BuildTeam_List(BaseCommand baseCommand, SubCommand subCommand) @Override public void onCommand(CommandSender sender, String[] args) { - List buildTeams = BuildTeam.getBuildTeams(); + List buildTeams = DataProvider.BUILD_TEAM.getBuildTeams(); if (buildTeams.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no build teams registered in the database!")); return; @@ -100,16 +100,11 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + buildTeams.size() + " build teams registered in the database:")); sender.sendMessage("§8--------------------------"); for (BuildTeam b : buildTeams) { - try { - StringJoiner countriesAsString = new StringJoiner(", "); - StringJoiner reviewersAsString = new StringJoiner(", "); - b.getCountries().forEach(c -> countriesAsString.add(String.valueOf(c.getID()))); - b.getReviewers().forEach(r -> {try {reviewersAsString.add(r.getName());} catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A data error occurred!"), ex);}}); - sender.sendMessage(" §6> §b" + b.getID() + " (" + b.getName() + ") §f- Country IDs: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString)); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + StringJoiner countriesAsString = new StringJoiner(", "); + StringJoiner reviewersAsString = new StringJoiner(", "); + b.getCountries().forEach(c -> countriesAsString.add(c.getCode())); + b.getReviewers().forEach(r -> {reviewersAsString.add(r.getName());}); + sender.sendMessage(" §6> §b" + b.getID() + " (" + b.getName() + ") §f- Country IDs: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString)); } sender.sendMessage("§8--------------------------"); } @@ -190,7 +185,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team exists try { - if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { + if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any build team with ID " + args[1] + "!")); sendInfo(sender); return; @@ -235,7 +230,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team exits try { - if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; String name = CMD_Setup.appendArgs(args, 2); if (name.length() > 45) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team name cannot be longer than 45 characters!")); @@ -285,14 +280,14 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team and country exists try { - if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - if (Country.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[2]))) { + if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.COUNTRY.getCountries().stream().noneMatch(c -> c.getCode().equalsIgnoreCase(args[2]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is already added to the build team!")); return; } - Country country = new Country(Integer.parseInt(args[2])); + Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); BuildTeam.addCountry(Integer.parseInt(args[1]), country.getID()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.getName() + "' to build team with ID " + args[1] + "!")); + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.getCode() + "' to build team with ID " + args[1] + "!")); } catch (SQLException ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); @@ -334,14 +329,14 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team and country exists try { - if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; if (DataProvider.COUNTRY.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[2]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is not added to the build team!")); return; } - Country country = new Country(Integer.parseInt(args[2])); + Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); BuildTeam.removeCountry(Integer.parseInt(args[1]), country.getID()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.getName() + "' from build team with ID " + args[1] + "!")); + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.getCode() + "' from build team with ID " + args[1] + "!")); } catch (SQLException ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); @@ -383,9 +378,9 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team exits try { - if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; Builder builder = Builder.byName(args[2]); - if (builder == null || BuildTeam.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == Integer.parseInt(args[1]))) { + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == Integer.parseInt(args[1]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is already reviewer for this build team!")); return; } @@ -429,10 +424,10 @@ public void onCommand(CommandSender sender, String[] args) { // Check if build team exits try { - if (BuildTeam.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; Builder builder = Builder.byName(args[2]); - if (builder == null || BuildTeam.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is not a reviewer for this build team!")); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 41d925de..9b83e11c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; @@ -87,7 +88,7 @@ public CMD_Setup_City_List(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - List cities = CityProject.getCityProjects(false); + List cities = DataProvider.CITY_PROJECT.getCityProjects(false); if (cities.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no City Projects registered in the database!")); return; @@ -96,12 +97,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + cities.size() + " City Projects registered in the database:")); sender.sendMessage("§8--------------------------"); for (CityProject c : cities) { - try { - sender.sendMessage(" §6> §b" + c.getID() + " (" + c.getName() + ") §f- Description: " + c.getDescription() + " - Country: " + c.getCountry().getName() + " - Visible: " + c.isVisible()); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + sender.sendMessage(" §6> §b" + c.getID() + " (" + c.getName() + ") §f- Description: " + c.getDescription() + " - Country: " + c.getCountry().getCode() + " - Visible: " + c.isVisible()); } sender.sendMessage("§8--------------------------"); } @@ -136,7 +132,7 @@ public CMD_Setup_City_Add(BaseCommand baseCommand, SubCommand subCommand) { public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - Country country = Country.getCountries().stream().filter(c -> c.getID() == Integer.parseInt(args[1])).findFirst().orElse(null); + Country country = DataProvider.COUNTRY.getCountryByCode(args[1]); if (country == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with ID " + args[1] + "!")); sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all countries!")); @@ -189,7 +185,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if City Project exists try { - if (CityProject.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) { + if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any City Project with ID " + args[1] + "!")); sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all City Projects!")); return; @@ -234,7 +230,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if City Project exits try { - if (CityProject.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; String name = CMD_Setup.appendArgs(args, 2); if (name.length() > 45) { @@ -283,7 +279,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if City Project exits try { - if (CityProject.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; String description = CMD_Setup.appendArgs(args, 2); if (description.length() > 255) { @@ -330,7 +326,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if City Project exits try { - if (CityProject.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; + if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) return; CityProject.setCityProjectVisibility(Integer.parseInt(args[1]), args[2].equalsIgnoreCase("true")); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 2c4ad98e..b7d98cf5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -188,7 +188,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if country exists try { - if (Country.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) { + if (DataProvider.COUNTRY.getCountryByCode(args[1]) == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with ID " + args[1] + "!")); sendInfo(sender); return; @@ -236,7 +236,7 @@ public void onCommand(CommandSender sender, String[] args) { // Check if country exists try { - if (Country.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) { + if (DataProvider.COUNTRY.getCountryByCode(args[1]) == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with name " + args[1] + "!")); sendInfo(sender); return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 28dfd0d1..21c7970b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -28,7 +28,7 @@ public class DataProvider { public static BuilderProvider BUILDER = new BuilderProvider(); - public static BuildTeamProviderSql BUILD_TEAM = new BuildTeamProviderSql(); + public static BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(); public static PlotProvider PLOT = new PlotProvider(); public static DifficultyProvider DIFFICULTY = new DifficultyProvider(); public static CityProjectProvider CITY_PROJECT = new CityProjectProvider(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java similarity index 68% rename from src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java rename to src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 739406b2..66664984 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/BuildTeamProviderSql.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -1,19 +1,39 @@ -package com.alpsbte.plotsystem.core.database; +package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.utils.Utils; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; import static net.kyori.adventure.text.Component.text; -public class BuildTeamProviderSql { +public class BuildTeamProvider { + public static final List BUILD_TEAMS = new ArrayList<>(); + + public BuildTeam getBuildTeam(int id) { + Optional buildTeam = BUILD_TEAMS.stream().filter(b -> b.getID() == id).findFirst(); + if (buildTeam.isPresent()) return buildTeam.get(); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT bt.name, bthc.country_code, bthcp.city_project_id, bthr.uuid FROM build_team bt " + + "INNER JOIN build_team_has_country bthc ON bthc.build_team_id = bt.build_team_id " + + "INNER JOIN build_team_has_city_project bthcp ON bthcp.build_team_id = bt.build_team_id " + + "INNER JOIN build_team_has_reviewer bthr ON bthr.build_team_id = bt.build_team_id " + + "WHERE bt.build_team_id = ?")) { + + } catch (SQLException ex) { Utils.logSqlException(ex); } + return null; + } + public String getName(int id) throws SQLException { try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_buildteams WHERE id = ?") .setValue(id).executeQuery()) { @@ -24,37 +44,19 @@ public String getName(int id) throws SQLException { return null; } - public List getCountries(int id) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT country_id FROM plotsystem_buildteam_has_countries WHERE buildteam_id = ?") - .setValue(id).executeQuery()) { - - List countries = new ArrayList<>(); - while (rs.next()) countries.add(new Country(rs.getInt(1))); - DatabaseConnection.closeResultSet(rs); - return countries; - } + public List getCountries(int id) { + // TODO: implement + return List.of(); } - public List getReviewers(int id) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT builder_uuid FROM plotsystem_builder_is_reviewer WHERE buildteam_id = ?") - .setValue(id).executeQuery()) { - - List builders = new ArrayList<>(); - while (rs.next()) builders.add(Builder.byUUID(UUID.fromString(rs.getString(1)))); - DatabaseConnection.closeResultSet(rs); - return builders; - } + public List getReviewers(int id) { + // TODO: implement + return List.of(); } - public List getBuildTeamsByReviewer(UUID reviewerUUID) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT buildteam_id FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ?") - .setValue(reviewerUUID.toString()).executeQuery()) { - - List buildTeams = new ArrayList<>(); - while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1))); - DatabaseConnection.closeResultSet(rs); - return buildTeams; - } + public List getBuildTeamsByReviewer(UUID reviewerUUID) { + // TODO: implement + return List.of(); } public List getBuildTeams() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 6142b333..889793ff 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -1,11 +1,27 @@ package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.system.CityProject; +import com.alpsbte.plotsystem.core.system.Country; import java.util.List; public class CityProjectProvider { - public List getCityProjectByCountryCode(String countryCode) { + public CityProject getCityProjectById(int id) { + // TODO: implement + return null; + } + + public List getCityProjectsByCountryCode(String countryCode) { + // TODO: implement + return List.of(); + } + + public List getCityProjects(Country country, boolean onlyVisible) { + // TODO: implement + return List.of(); + } + + public List getCityProjects(boolean onlyVisible) { // TODO: implement return List.of(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 65bd5ee7..3ce2d153 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -20,6 +20,11 @@ public Plot getPlotById(int plotId) { return null; } + public List getPlots(CityProject city, Status... statuses) { + // TODO: implement + return List.of(); + } + public List getPlots(List cities, Status... statuses) { // TODO: implement return List.of(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 86c7e29c..10547c9a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -156,7 +156,7 @@ protected Mask getMask() { @Override protected List getSource() { - if (projects == null) projects = CityProject.getCityProjects(country, true); + if (projects == null) projects = DataProvider.CITY_PROJECT.getCityProjects(country, true); return projects; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index a1954806..6c7e2d1b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -52,22 +52,14 @@ public String getName() { return name; } - public List getCountries() throws SQLException { + public List getCountries() { return DataProvider.BUILD_TEAM.getCountries(ID); } - public List getReviewers() throws SQLException { + public List getReviewers() { return DataProvider.BUILD_TEAM.getReviewers(ID); } - public static List getBuildTeamsByReviewer(UUID reviewerUUID) throws SQLException { - return DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(reviewerUUID); - } - - public static List getBuildTeams() { - return DataProvider.BUILD_TEAM.getBuildTeams(); - } - public static void addBuildTeam(String name) throws SQLException { DataProvider.BUILD_TEAM.addBuildTeam(name); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index f1ad561c..87f9ce3b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -158,8 +158,8 @@ public Reviewer getAsReviewer() throws SQLException { public static class Reviewer { private final List buildTeams; - public Reviewer(UUID reviewerUUID) throws SQLException { - this.buildTeams = BuildTeam.getBuildTeamsByReviewer(reviewerUUID); + public Reviewer(UUID reviewerUUID) { + this.buildTeams = DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(reviewerUUID); } public List getCountries() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index ee8869f6..6d1c0e55 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -27,7 +27,9 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.database.providers.CityProjectProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; @@ -51,27 +53,15 @@ public class CityProject { private final int ID; - private int countryID; + private String countryCode; + private String serverName; + private boolean isVisible; - private String name; - private String description; - private boolean visible; - - public CityProject(int ID) throws SQLException { - this.ID = ID; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT country_id, name, description, visible FROM plotsystem_city_projects WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - this.countryID = rs.getInt(1); - this.name = rs.getString(2); - this.description = rs.getString(3); - this.visible = rs.getInt(4) == 1; - } - - DatabaseConnection.closeResultSet(rs); - } + public CityProject(int id, String countryCode, String serverName, boolean isVisible) { + this.ID = id; + this.countryCode = countryCode; + this.serverName = serverName; + this.isVisible = isVisible; } public int getID() { @@ -79,25 +69,27 @@ public int getID() { } public Country getCountry() { - return new Country(countryID); + return DataProvider.COUNTRY.getCountryByCode(countryCode); } - public String getName() { - return name; + public String getName(Player player) { + // TODO: implement (get from language file) + return "CityProject WIP"; } - public String getDescription() { - return description; + public String getDescription(Player player) { + // TODO: implement (get from language file) + return "Description WIP"; } - public ArrayList getDescriptionComponents() { + public ArrayList getDescriptionComponents(Player player) { ArrayList descriptionLines = new ArrayList<>(); - for (String line : getDescription().split("%newline%")) descriptionLines.add(text(line)); + for (String line : getDescription(player).split("%newline%")) descriptionLines.add(text(line)); return descriptionLines; } public boolean isVisible() { - return visible; + return isVisible; } public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { @@ -106,16 +98,16 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { PlotDifficulty cpPlotDifficulty = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(getID(), Builder.byUUID(player.getUniqueId())).get(); - int plotsOpen = Plot.getPlots(getID(), Status.unclaimed).size(); - int plotsInProgress = Plot.getPlots(getID(), Status.unfinished, Status.unreviewed).size(); - int plotsCompleted = Plot.getPlots(getID(), Status.completed).size(); + int plotsOpen = DataProvider.PLOT.getPlots(this, Status.unclaimed).size(); + int plotsInProgress = DataProvider.PLOT.getPlots(this, Status.unfinished, Status.unreviewed).size(); + int plotsCompleted = DataProvider.PLOT.getPlots(this, Status.completed).size(); int plotsUnclaimed = cpPlotDifficulty != null ? Plot.getPlots(getID(), cpPlotDifficulty, Status.unclaimed).size() : 0; int plotsOpenForPlayer = cpPlotDifficulty != null && plotsUnclaimed != 0 ? getOpenPlotsForPlayer(getID(), cpPlotDifficulty) : 0; return new ItemBuilder(cpItem) - .setName(text(getName(), AQUA).decoration(BOLD, true)) + .setName(text(getName(player), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() - .addLines(true, getDescription()) + .addLines(true, getDescription(player)) .emptyLine() .addLine(text(plotsOpen, GOLD) .append(text(" " + LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_OPEN) + " ", GRAY)) @@ -138,35 +130,10 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { } } - public static List getCityProjects(Country country, boolean onlyVisible) { - // if country is not null, only get country's city projects, otherwise load all - DatabaseConnection.StatementBuilder statement = DatabaseConnection.createStatement("SELECT id FROM plotsystem_city_projects " + (country == null ? "" : "WHERE country_id = ?") + " ORDER BY country_id"); - if (country != null) statement.setValue(country.getID()); - - try (ResultSet rs = statement.executeQuery()) { - List cityProjects = new ArrayList<>(); - while (rs.next()) { - CityProject city = new CityProject(rs.getInt(1)); - if (city.isVisible() || !onlyVisible) cityProjects.add(city); - } - - DatabaseConnection.closeResultSet(rs); - return cityProjects; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); - } - private int getOpenPlotsForPlayer(int plotID, PlotDifficulty plotDifficulty) throws SQLException { return Plot.getPlots(plotID, plotDifficulty, Status.unclaimed).size(); } - - public static List getCityProjects(boolean onlyVisible) { - return getCityProjects(null, onlyVisible); - } - public static void addCityProject(Country country, String name) throws SQLException { DatabaseConnection.createStatement("INSERT INTO plotsystem_city_projects (id, name, country_id, description, visible) VALUES (?, ?, ?, ?, ?)") .setValue(DatabaseConnection.getTableID("plotsystem_city_projects")) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index 0a83e932..c816c561 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -59,7 +59,7 @@ public Country(String code, Continent continent, String material, String customM public Continent getContinent() {return continent;} public List getCityProjects() { - return DataProvider.CITY_PROJECT.getCityProjectByCountryCode(code); + return DataProvider.CITY_PROJECT.getCityProjectsByCountryCode(code); } public String getName(Player player) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index e177d235..c1b7ac8c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -326,7 +326,7 @@ public static void syncPlotSchematicFiles() { if (config.getBoolean(ConfigPaths.SYNC_FTP_FILES_ENABLE)) { long interval = config.getLong(ConfigPaths.SYNC_FTP_FILES_INTERVAL); - Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> CityProject.getCityProjects(false).forEach(c -> { + Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> DataProvider.CITY_PROJECT.getCityProjects(false).forEach(c -> { try { if (c.getCountry().getServer().getFTPConfiguration() != null) { List plots = Plot.getPlots(c.getID(), Status.unclaimed); From 3e51a8b9885628037ca22f15a970fd31422d35a2 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 25 Jan 2025 00:20:58 +0100 Subject: [PATCH 017/175] Finish city project model and fix CMD_Setup_City.java --- .../commands/admin/setup/CMD_Setup_City.java | 171 ++++++------------ .../providers/CityProjectProvider.java | 24 ++- .../core/database/providers/PlotProvider.java | 6 + .../core/menus/PlayerPlotsMenu.java | 2 +- .../plotsystem/core/menus/ReviewMenu.java | 2 +- .../plotsystem/core/menus/ReviewPlotMenu.java | 2 +- .../core/menus/companion/CompanionMenu.java | 2 +- .../plotsystem/core/system/CityProject.java | 79 ++++---- .../plotsystem/core/system/plot/Plot.java | 2 +- 9 files changed, 126 insertions(+), 164 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 9b83e11c..e903747c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -24,8 +24,6 @@ package com.alpsbte.plotsystem.commands.admin.setup; -import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -34,10 +32,11 @@ import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.command.CommandSender; -import java.sql.SQLException; import java.util.List; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; public class CMD_Setup_City extends SubCommand { @@ -50,8 +49,7 @@ private void register() { registerSubCommand(new CMD_Setup_City_List(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_City_Add(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_City_Remove(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_City_SetName(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_City_SetDescription(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_City_SetServer(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_City_SetVisible(getBaseCommand(), this)); } @@ -95,11 +93,15 @@ public void onCommand(CommandSender sender, String[] args) { } sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + cities.size() + " City Projects registered in the database:")); - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); for (CityProject c : cities) { - sender.sendMessage(" §6> §b" + c.getID() + " (" + c.getName() + ") §f- Description: " + c.getDescription() + " - Country: " + c.getCountry().getCode() + " - Visible: " + c.isVisible()); + sender.sendMessage(text(" » ", DARK_GRAY) + .append(text(c.getID())) + .append(text(" - Country: " + c.getCountry().getCode() + + " - Server: " + c.getServerName() + + " - Visible: " + c.isVisible(), WHITE))); } - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); } @Override @@ -130,27 +132,26 @@ public CMD_Setup_City_Add(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 3) {sendInfo(sender); return;} - Country country = DataProvider.COUNTRY.getCountryByCode(args[1]); + String cityProjectId = args[1]; + String countryCode = args[2]; + Country country = DataProvider.COUNTRY.getCountryByCode(countryCode); if (country == null) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with ID " + args[1] + "!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with code " + countryCode + "!")); sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all countries!")); return; } - String name = CMD_Setup.appendArgs(args, 2); - if (name.length() > 45) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("City Project name cannot be longer than 45 characters!")); + String serverName = args[3]; + if (serverName.length() > 255) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 255 characters!")); return; } + // TODO: verify if server exists - try { - CityProject.addCityProject(country, name); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with name '" + name + "' in country with the ID " + args[1] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + boolean added = DataProvider.CITY_PROJECT.addCityProject(cityProjectId, country.getCode(), serverName); + if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); } @Override @@ -165,7 +166,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"Country-ID", "Name"}; + return new String[]{"City-Project-ID", "Country-Code", "Server-Name"}; } @Override @@ -181,21 +182,20 @@ public CMD_Setup_City_Remove(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 1) {sendInfo(sender); return;} + String cityProjectId = args[1]; // Check if City Project exists - try { - if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any City Project with ID " + args[1] + "!")); - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all City Projects!")); - return; - } - CityProject.removeCityProject(Integer.parseInt(args[1])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed City Project with ID " + args[1] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + CityProject cityProject = DataProvider.CITY_PROJECT.getCityProjectById(cityProjectId); + if (cityProject == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any City Project with ID " + cityProjectId + "!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all City Projects!")); + return; } + + boolean removed = DataProvider.CITY_PROJECT.removeCityProject(cityProjectId); + if (removed) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed City Project with ID " + cityProjectId + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while removing city project!")); } @Override @@ -219,84 +219,34 @@ public String getPermission() { } } - public static class CMD_Setup_City_SetName extends SubCommand { - public CMD_Setup_City_SetName(BaseCommand baseCommand, SubCommand subCommand) { + public static class CMD_Setup_City_SetServer extends SubCommand { + public CMD_Setup_City_SetServer(BaseCommand baseCommand, SubCommand subCommand) { super(baseCommand, subCommand); } @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 2) {sendInfo(sender); return;} // Check if City Project exits - try { - if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; - - String name = CMD_Setup.appendArgs(args, 2); - if (name.length() > 45) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("City Project name cannot be longer than 45 characters!")); - return; - } - - CityProject.setCityProjectName(Integer.parseInt(args[1]), name); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed name of City Project with ID " + args[1] + " to '" + name + "'!")); + CityProject cityProject = DataProvider.CITY_PROJECT.getCityProjectById(args[1]); + if (cityProject == null) return; - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + String serverName = args[2]; + if (serverName.length() > 255) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 255 characters!")); + return; } - } - - @Override - public String[] getNames() { - return new String[]{"setname"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"City-ID", "Name"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.city.setname"; - } - } - - public static class CMD_Setup_City_SetDescription extends SubCommand { - public CMD_Setup_City_SetDescription(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } + // TODO: verify if server exists - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - - // Check if City Project exits - try { - if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; - - String description = CMD_Setup.appendArgs(args, 2); - if (description.length() > 255) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("City Project description cant be longer than 255 characters!")); - return; - } - CityProject.setCityProjectDescription(Integer.parseInt(args[1]), description); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set description of City Project with ID " + args[1] + " to '" + description + "'!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + boolean successful = cityProject.setServer(serverName); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed server of City Project with ID " + args[1] + " to '" + serverName + "'!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project server!")); } @Override public String[] getNames() { - return new String[]{"setdescription"}; + return new String[]{"setserver"}; } @Override @@ -306,12 +256,12 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"City-ID", "Description"}; + return new String[]{"City-ID", "Server-Name"}; } @Override public String getPermission() { - return "plotsystem.admin.pss.city.setdescription"; + return "plotsystem.admin.pss.city.setserver"; } } @@ -322,19 +272,18 @@ public CMD_Setup_City_SetVisible(BaseCommand baseCommand, SubCommand subCommand) @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 2) {sendInfo(sender); return;} // Check if City Project exits - try { - if (DataProvider.CITY_PROJECT.getCityProjects(false).stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; - if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) return; - - CityProject.setCityProjectVisibility(Integer.parseInt(args[1]), args[2].equalsIgnoreCase("true")); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set visibility of City Project with ID " + args[1] + " to " + args[2].toUpperCase() + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + CityProject cityProject = DataProvider.CITY_PROJECT.getCityProjectById(args[1]); + if (cityProject == null) return; + if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) return; + + boolean isVisible = args[2].equalsIgnoreCase("true"); + boolean successful = cityProject.setVisible(isVisible); + + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set visibility of City Project with ID " + args[1] + " to " + args[2].toUpperCase() + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project visibility!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 889793ff..65a3d12b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -6,7 +6,7 @@ import java.util.List; public class CityProjectProvider { - public CityProject getCityProjectById(int id) { + public CityProject getCityProjectById(String id) { // TODO: implement return null; } @@ -25,4 +25,26 @@ public List getCityProjects(boolean onlyVisible) { // TODO: implement return List.of(); } + + public boolean addCityProject(String id, String countryCode, String serverName) { + // TODO: implement (isVisible can be default) + // return false if error occurred + return false; + } + + public boolean removeCityProject(String id) { + // TODO: implement + // return false if error occurred + return false; + } + + public boolean setCityProjectVisibility(String id, boolean isVisible) { + // TODO: implement + return false; + } + + public boolean setCityProjectServer(String id, String serverName) { + // TODO: implement + return false; + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 3ce2d153..d4880088 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -5,6 +5,7 @@ import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Status; import java.util.ArrayList; @@ -25,6 +26,11 @@ public List getPlots(CityProject city, Status... statuses) { return List.of(); } + public List getPlots(CityProject city, PlotDifficulty plotDifficulty, Status status) { + // TODO: implement + return List.of(); + } + public List getPlots(List cities, Status... statuses) { // TODO: implement return List.of(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index de164245..309ae219 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -102,7 +102,7 @@ protected void setMenuItemsAsync() { getMenu().getSlot(9 + i) .setItem(new ItemBuilder(item) - .setName(text(plot.getCity().getName() + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) + .setName(text(plot.getCity().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) .setLore(getLore(plot, getMenuPlayer()).build()) .build()); } catch (SQLException ex) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 6792a935..5f8750fa 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -96,7 +96,7 @@ protected void setPaginatedMenuItemsAsync(List source) { if (!plot.getPlotMembers().isEmpty()) { lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBERS) + ": §f" + plot.getPlotMembers().stream().map(Builder::getName).collect(Collectors.joining(", "))); } - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCity().getName()); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCity().getName(getMenuPlayer())); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": §f" + plot.getCity().getCountry().getName(getMenuPlayer())); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": §f" + plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java index 360ba495..7b7ce4f3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java @@ -358,7 +358,7 @@ private ItemStack getPlotInfoItem() { Player plotOwnerPlayer; plotOwner = plot.getPlotOwner().getName(); - city = plot.getCity().getName(); + city = plot.getCity().getName(getMenuPlayer()); country = plot.getCity().getCountry().getName(getMenuPlayer()); difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 7198d596..9cfc8e9a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -205,7 +205,7 @@ public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPla String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); lore = new LoreBuilder() .addLines(text(plotIdText + ": ", NamedTextColor.GRAY).append(text(plot.getID(), NamedTextColor.WHITE)), - text(plotCityText + ": ", NamedTextColor.GRAY).append(text(plot.getCity().getName(), NamedTextColor.WHITE)), + text(plotCityText + ": ", NamedTextColor.GRAY).append(text(plot.getCity().getName(langPlayer), NamedTextColor.WHITE)), text(plotDifficultyText + ": ", NamedTextColor.GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), NamedTextColor.WHITE)), empty(), statusComp.append(text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index 6d1c0e55..e1053f3c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -28,8 +28,6 @@ import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.database.providers.CityProjectProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; @@ -41,7 +39,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.ExecutionException; @@ -52,19 +49,19 @@ public class CityProject { - private final int ID; - private String countryCode; + private final String ID; + private final String countryCode; private String serverName; private boolean isVisible; - public CityProject(int id, String countryCode, String serverName, boolean isVisible) { + public CityProject(String id, String countryCode, String serverName, boolean isVisible) { this.ID = id; this.countryCode = countryCode; this.serverName = serverName; this.isVisible = isVisible; } - public int getID() { + public String getID() { return ID; } @@ -72,6 +69,18 @@ public Country getCountry() { return DataProvider.COUNTRY.getCountryByCode(countryCode); } + public String getServerName() { + return serverName; + } + + public boolean setServer(String serverName) { + if (DataProvider.CITY_PROJECT.setCityProjectServer(ID, serverName)) { + this.serverName = serverName; + return true; + } + return false; + } + public String getName(Player player) { // TODO: implement (get from language file) return "CityProject WIP"; @@ -92,17 +101,29 @@ public boolean isVisible() { return isVisible; } + public boolean setVisible(boolean isVisible) { + if (DataProvider.CITY_PROJECT.setCityProjectVisibility(ID, isVisible)) { + this.isVisible = isVisible; + return true; + } + return false; + } + public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { ItemStack cpItem = getCountry().getCountryItem(); try { - PlotDifficulty cpPlotDifficulty = selectedPlotDifficulty != null ? + PlotDifficulty plotDifficulty = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(getID(), Builder.byUUID(player.getUniqueId())).get(); int plotsOpen = DataProvider.PLOT.getPlots(this, Status.unclaimed).size(); int plotsInProgress = DataProvider.PLOT.getPlots(this, Status.unfinished, Status.unreviewed).size(); int plotsCompleted = DataProvider.PLOT.getPlots(this, Status.completed).size(); - int plotsUnclaimed = cpPlotDifficulty != null ? Plot.getPlots(getID(), cpPlotDifficulty, Status.unclaimed).size() : 0; - int plotsOpenForPlayer = cpPlotDifficulty != null && plotsUnclaimed != 0 ? getOpenPlotsForPlayer(getID(), cpPlotDifficulty) : 0; + int plotsUnclaimed = plotDifficulty != null + ? DataProvider.PLOT.getPlots(this, plotDifficulty, Status.unclaimed).size() + : 0; + int plotsOpenForPlayer = plotDifficulty != null && plotsUnclaimed != 0 + ? DataProvider.PLOT.getPlots(this, plotDifficulty, Status.unclaimed).size() + : 0; return new ItemBuilder(cpItem) .setName(text(getName(player), AQUA).decoration(BOLD, true)) @@ -120,7 +141,7 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { .append(text(" " + LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_COMPLETED), GRAY))) .emptyLine() .addLine(plotsUnclaimed != 0 - ? Utils.ItemUtils.getFormattedDifficulty(cpPlotDifficulty) + ? Utils.ItemUtils.getFormattedDifficulty(plotDifficulty) : text(LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_NO_PLOTS_AVAILABLE), WHITE).decoration(BOLD, true)) .build()) .build(); @@ -129,40 +150,4 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { return MenuItems.errorItem(player); } } - - private int getOpenPlotsForPlayer(int plotID, PlotDifficulty plotDifficulty) throws SQLException { - return Plot.getPlots(plotID, plotDifficulty, Status.unclaimed).size(); - } - - public static void addCityProject(Country country, String name) throws SQLException { - DatabaseConnection.createStatement("INSERT INTO plotsystem_city_projects (id, name, country_id, description, visible) VALUES (?, ?, ?, ?, ?)") - .setValue(DatabaseConnection.getTableID("plotsystem_city_projects")) - .setValue(name) - .setValue(country.getID()) - .setValue("") - .setValue(true).executeUpdate(); - } - - public static void removeCityProject(int id) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_city_projects WHERE id = ?") - .setValue(id).executeUpdate(); - } - - public static void setCityProjectName(int id, String newName) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_city_projects SET name = ? WHERE id = ?") - .setValue(newName) - .setValue(id).executeUpdate(); - } - - public static void setCityProjectDescription(int id, String description) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_city_projects SET description = ? WHERE id = ?") - .setValue(description) - .setValue(id).executeUpdate(); - } - - public static void setCityProjectVisibility(int id, boolean isEnabled) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_city_projects SET visible = ? WHERE id = ?") - .setValue(isEnabled ? 1 : 0) - .setValue(id).executeUpdate(); - } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index eb534f93..d2a6db57 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -512,7 +512,7 @@ public static boolean hasPlotDifficultyScoreRequirement(Builder builder, PlotDif return playerScore >= scoreRequirement; } - public static CompletableFuture getPlotDifficultyForBuilder(int cityID, Builder builder) throws SQLException { + public static CompletableFuture getPlotDifficultyForBuilder(String cityID, Builder builder) throws SQLException { // Check if plot difficulties are available boolean easyHasPlots = false, mediumHasPlots = false, hardHasPlots = false; if (!getPlots(cityID, PlotDifficulty.EASY, Status.unclaimed).isEmpty()) easyHasPlots = true; From d2cbb14f11a64d6ce83d2967307b49fe78b47a9b Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Wed, 29 Jan 2025 21:38:54 +0100 Subject: [PATCH 018/175] Finish BuildTeam model and fix CMD_Setup_BuildTeam.java --- .../admin/setup/CMD_Setup_BuildTeam.java | 192 +++++++++--------- .../commands/admin/setup/CMD_Setup_City.java | 5 +- .../database/providers/BuildTeamProvider.java | 71 +++---- .../core/database/providers/PlotProvider.java | 5 + .../core/menus/companion/CityProjectMenu.java | 9 +- .../plotsystem/core/system/BuildTeam.java | 68 ++++--- .../plotsystem/core/system/CityProject.java | 3 +- .../plotsystem/core/system/plot/Plot.java | 74 +------ .../plot/generator/DefaultPlotGenerator.java | 6 +- .../core/system/plot/utils/PlotUtils.java | 9 +- 10 files changed, 194 insertions(+), 248 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index cd5a9f52..1d082944 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -35,11 +34,11 @@ import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.command.CommandSender; -import java.sql.SQLException; import java.util.List; import java.util.StringJoiner; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.*; public class CMD_Setup_BuildTeam extends SubCommand { public CMD_Setup_BuildTeam(BaseCommand baseCommand) { @@ -98,15 +97,18 @@ public void onCommand(CommandSender sender, String[] args) { } sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + buildTeams.size() + " build teams registered in the database:")); - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); for (BuildTeam b : buildTeams) { StringJoiner countriesAsString = new StringJoiner(", "); StringJoiner reviewersAsString = new StringJoiner(", "); b.getCountries().forEach(c -> countriesAsString.add(c.getCode())); - b.getReviewers().forEach(r -> {reviewersAsString.add(r.getName());}); - sender.sendMessage(" §6> §b" + b.getID() + " (" + b.getName() + ") §f- Country IDs: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString)); + b.getReviewers().forEach(r -> reviewersAsString.add(r.getName())); + sender.sendMessage(text(" » ", DARK_GRAY) + .append(text(b.getID() + " (" + b.getName() + ") ", AQUA)) + .append(text("- Country Codes: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString), WHITE))); } - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); } @Override @@ -138,19 +140,16 @@ public CMD_Setup_BuildTeam_Add(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { if (args.length <= 1) {sendInfo(sender); return;} - if (args[1].length() > 45) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team name cannot be longer than 45 characters!")); + + String name = args[1]; + if (name.length() > 255) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team name cannot be longer than 255 characters!")); return; } - try { - String name = CMD_Setup.appendArgs(args, 1); - BuildTeam.addBuildTeam(name); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added build team with name '" + name + "'!")); - } catch (Exception ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + boolean successful = DataProvider.BUILD_TEAM.addBuildTeam(name); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added build team with name '" + name + "'!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -183,19 +182,18 @@ public CMD_Setup_BuildTeam_Remove(BaseCommand baseCommand, SubCommand subCommand public void onCommand(CommandSender sender, String[] args) { if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + // Check if build team exists - try { - if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any build team with ID " + args[1] + "!")); - sendInfo(sender); - return; - } - BuildTeam.removeBuildTeam(Integer.parseInt(args[1])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); - } catch (Exception ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (buildTeam == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any build team with ID " + args[1] + "!")); + sendInfo(sender); + return; } + + boolean successful = DataProvider.BUILD_TEAM.removeBuildTeam(buildTeam.getID()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -228,21 +226,23 @@ public CMD_Setup_BuildTeam_SetName(BaseCommand baseCommand, SubCommand subComman public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + // Check if build team exits - try { - if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - String name = CMD_Setup.appendArgs(args, 2); - if (name.length() > 45) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team name cannot be longer than 45 characters!")); - return; - } - - BuildTeam.setBuildTeamName(Integer.parseInt(args[1]), name); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed name of build team with ID " + args[1] + " to '" + name + "'!")); - } catch (Exception ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (buildTeam == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); + return; + } + + String name = args[2]; + if (name.length() > 255) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team name cannot be longer than 255 characters!")); + return; } + + boolean successful = buildTeam.setName(name); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed name of build team with ID " + args[1] + " to '" + name + "'!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -278,20 +278,23 @@ public void onCommand(CommandSender sender, String[] args) { return; } + + BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); + + // Check if build team and country exists - try { - if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - if (DataProvider.COUNTRY.getCountries().stream().noneMatch(c -> c.getCode().equalsIgnoreCase(args[2]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is already added to the build team!")); - return; - } - Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); - BuildTeam.addCountry(Integer.parseInt(args[1]), country.getID()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.getCode() + "' to build team with ID " + args[1] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (buildTeam == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); + return; + } + if (country == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is already added to the build team!")); + return; } + boolean successful = buildTeam.addCountry(country); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.getCode() + "' to build team with ID " + args[1] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -306,7 +309,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"BuildTeam-ID", "Country-ID"}; + return new String[]{"BuildTeam-ID", "Country-Code"}; } @Override @@ -322,25 +325,27 @@ public CMD_Setup_BuildTeam_RemoveCountry(BaseCommand baseCommand, SubCommand sub @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null || AlpsUtils.tryParseInt(args[2]) == null) { + if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) { sendInfo(sender); return; } + BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); + // Check if build team and country exists - try { - if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - if (DataProvider.COUNTRY.getCountries().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[2]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is not added to the build team!")); - return; - } - Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); - BuildTeam.removeCountry(Integer.parseInt(args[1]), country.getID()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.getCode() + "' from build team with ID " + args[1] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (buildTeam == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); + return; } + if (country == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is not added to the build team!")); + return; + } + + boolean successful = buildTeam.removeCountry(country.getCode()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.getCode() + "' from build team with ID " + args[1] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -355,7 +360,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"BuildTeam-ID", "Country-ID"}; + return new String[]{"BuildTeam-ID", "Country-Code"}; } @Override @@ -377,19 +382,20 @@ public void onCommand(CommandSender sender, String[] args) { } // Check if build team exits - try { - if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - Builder builder = Builder.byName(args[2]); - if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is already reviewer for this build team!")); - return; - } - BuildTeam.addReviewer(Integer.parseInt(args[1]), builder.getUUID().toString()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added '" + builder.getName() + "' as reviewer to build team with ID " + args[1] + "!")); - } catch (Exception ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + if (buildTeam == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); + return; } + + Builder builder = Builder.byName(args[2]); + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == buildTeam.getID())) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is already reviewer for this build team!")); + return; + } + boolean successful = buildTeam.addReviewer(builder); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added '" + builder.getName() + "' as reviewer to build team with ID " + buildTeam.getName() + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -423,20 +429,22 @@ public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} // Check if build team exits - try { - if (DataProvider.BUILD_TEAM.getBuildTeams().stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) return; - - Builder builder = Builder.byName(args[2]); - if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is not a reviewer for this build team!")); - return; - } - BuildTeam.removeReviewer(Integer.parseInt(args[1]), builder.getUUID().toString()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed '" + builder.getName() + "' as reviewer from build team with ID " + args[1] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + + if (buildTeam == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); + return; } + + Builder builder = Builder.byName(args[2]); + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == buildTeam.getID())) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is not a reviewer for this build team!")); + return; + } + + boolean successful = buildTeam.removeReviewer(builder.getUUID().toString()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed '" + builder.getName() + "' as reviewer from build team with ID " + args[1] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index e903747c..9f5436c7 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -35,8 +35,7 @@ import java.util.List; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; -import static net.kyori.adventure.text.format.NamedTextColor.WHITE; +import static net.kyori.adventure.text.format.NamedTextColor.*; public class CMD_Setup_City extends SubCommand { @@ -96,7 +95,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(text("--------------------------", DARK_GRAY)); for (CityProject c : cities) { sender.sendMessage(text(" » ", DARK_GRAY) - .append(text(c.getID())) + .append(text(c.getID(), AQUA)) .append(text(" - Country: " + c.getCountry().getCode() + " - Server: " + c.getServerName() + " - Visible: " + c.isVisible(), WHITE))); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 66664984..570fc593 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -34,21 +34,6 @@ public BuildTeam getBuildTeam(int id) { return null; } - public String getName(int id) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name FROM plotsystem_buildteams WHERE id = ?") - .setValue(id).executeQuery()) { - - if (rs.next()) return rs.getString(1); - DatabaseConnection.closeResultSet(rs); - } - return null; - } - - public List getCountries(int id) { - // TODO: implement - return List.of(); - } - public List getReviewers(int id) { // TODO: implement return List.of(); @@ -61,8 +46,11 @@ public List getBuildTeamsByReviewer(UUID reviewerUUID) { public List getBuildTeams() { List buildTeams = new ArrayList<>(); - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id, name FROM plotsystem_buildteams").executeQuery()) { - while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1), rs.getString(2))); + List countries = new ArrayList<>(); + List reviewers = new ArrayList<>(); + // TODO: also get countries and reviewers (currently empty lists) + try (ResultSet rs = DatabaseConnection.createStatement("SELECT build_team_id, name FROM build_team").executeQuery()) { + while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1), rs.getString(2), countries, reviewers)); DatabaseConnection.closeResultSet(rs); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); @@ -70,45 +58,38 @@ public List getBuildTeams() { return buildTeams; } - public void addBuildTeam(String name) throws SQLException { - int id = DatabaseConnection.getTableID("plotsystem_buildteams"); - DatabaseConnection.createStatement("INSERT INTO plotsystem_buildteams (id, name) VALUES (?, ?)") - .setValue(id) - .setValue(name).executeUpdate(); + public boolean addBuildTeam(String name) { + // TODO: implement + return false; } - public void removeBuildTeam(int serverId) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteams WHERE id = ?") - .setValue(serverId).executeUpdate(); + public boolean removeBuildTeam(int id) { + // TODO: implement + return false; } - public void setBuildTeamName(int id, String newName) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_buildteams SET name = ? WHERE id = ?") - .setValue(newName) - .setValue(id).executeUpdate(); + public boolean setBuildTeamName(int id, String newName) { + // TODO: implement + return false; } - public void addCountry(int id, int countryId) throws SQLException { - DatabaseConnection.createStatement("INSERT plotsystem_buildteam_has_countries SET country_id = ?, buildteam_id = ?") - .setValue(countryId) - .setValue(id).executeUpdate(); + public boolean addCountry(int id, String countryCode) { + // TODO: implement + return false; } - public void removeCountry(int id, int countryId) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_buildteam_has_countries WHERE country_id = ? AND buildteam_id = ?") - .setValue(countryId) - .setValue(id).executeUpdate(); + public boolean removeCountry(int id, String countryCode) { + // TODO: implement + return false; } - public void addReviewer(int id, String reviewerUUID) throws SQLException { - DatabaseConnection.createStatement("INSERT plotsystem_builder_is_reviewer SET builder_uuid = ?, buildteam_id = ?") - .setValue(reviewerUUID) - .setValue(id).executeUpdate(); + public boolean addReviewer(int id, String reviewerUUID) { + // TODO: implement + return false; } - public void removeReviewer(int id, String reviewerUUID) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_builder_is_reviewer WHERE builder_uuid = ? AND buildteam_id = ?") - .setValue(reviewerUUID) - .setValue(id).executeUpdate(); + public boolean removeReviewer(int id, String reviewerUUID) { + // TODO: implement + return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index d4880088..9d6b1d53 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -21,6 +21,11 @@ public Plot getPlotById(int plotId) { return null; } + public List getPlots(Status status) { + // TODO: implement + return List.of(); + } + public List getPlots(CityProject city, Status... statuses) { // TODO: implement return List.of(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 10547c9a..992afabd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -184,11 +184,12 @@ protected void setPaginatedItemClickEventsAsync(List source) { clickPlayer.closeInventory(); Builder builder = Builder.byUUID(clickPlayer.getUniqueId()); - int cityID = city.getID(); + String cityID = city.getID(); try { - PlotDifficulty plotDifficultyForCity = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(cityID, builder).get(); - if (plotDifficultyForCity == null || Plot.getPlots(cityID, plotDifficultyForCity, Status.unclaimed).isEmpty()) { + PlotDifficulty plotDifficultyForCity = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(city, builder).get(); + List unclaimedPlots = DataProvider.PLOT.getPlots(city, plotDifficultyForCity, Status.unclaimed); + if (plotDifficultyForCity == null || unclaimedPlots.isEmpty()) { clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(clickPlayer, LangPaths.Message.Error.NO_PLOTS_LEFT))); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); return; @@ -200,7 +201,7 @@ protected void setPaginatedItemClickEventsAsync(List source) { return; } - new DefaultPlotGenerator(cityID, plotDifficultyForCity, builder); + new DefaultPlotGenerator(city, plotDifficultyForCity, builder); } catch (SQLException | ExecutionException | InterruptedException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(clickPlayer, LangPaths.Message.Error.ERROR_OCCURRED))); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 6c7e2d1b..4d8a5aad 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -28,20 +28,20 @@ import java.sql.SQLException; import java.util.List; +import java.util.Optional; import java.util.UUID; public class BuildTeam { private final int ID; - private final String name; + private String name; + private final List countries; + private final List reviewers; - public BuildTeam(int ID) throws SQLException { - this.ID = ID; - this.name = DataProvider.BUILD_TEAM.getName(ID); - } - - public BuildTeam(int ID, String name) { + public BuildTeam(int ID, String name, List countries, List reviewers) { this.ID = ID; this.name = name; + this.countries = countries; + this.reviewers = reviewers; } public int getID() { @@ -53,38 +53,54 @@ public String getName() { } public List getCountries() { - return DataProvider.BUILD_TEAM.getCountries(ID); + return countries; } public List getReviewers() { return DataProvider.BUILD_TEAM.getReviewers(ID); } - public static void addBuildTeam(String name) throws SQLException { - DataProvider.BUILD_TEAM.addBuildTeam(name); - } - - public static void removeBuildTeam(int serverID) throws SQLException { - DataProvider.BUILD_TEAM.removeBuildTeam(serverID); - } - - public static void setBuildTeamName(int id, String newName) throws SQLException { - DataProvider.BUILD_TEAM.setBuildTeamName(id, newName); + public boolean setName(String newName) { + if (DataProvider.BUILD_TEAM.setBuildTeamName(ID, newName)) { + this.name = newName; + return true; + } + return false; } - public static void addCountry(int id, int countryID) throws SQLException { - DataProvider.BUILD_TEAM.addCountry(id, countryID); + public boolean addCountry(Country country) { + if (DataProvider.BUILD_TEAM.addCountry(ID, country.getCode())) { + this.countries.add(country); + return true; + } + return false; } - public static void removeCountry(int id, int countryID) throws SQLException { - DataProvider.BUILD_TEAM.removeCountry(id, countryID); + public boolean removeCountry(String countryCode) { + Optional removeCountry = countries.stream().filter(c -> c.getCode().equalsIgnoreCase(countryCode)).findFirst(); + if (removeCountry.isEmpty()) return false; + if (DataProvider.BUILD_TEAM.removeCountry(ID, countryCode)) { + this.countries.remove(removeCountry.get()); + return true; + } + return false; } - public static void removeReviewer(int id, String reviewerUUID) throws SQLException { - DataProvider.BUILD_TEAM.removeReviewer(id, reviewerUUID); + public boolean removeReviewer(String reviewerUUID) { + Optional removeReviewer = reviewers.stream().filter(r -> r.getUUID().toString().equals(reviewerUUID)).findFirst(); + if (removeReviewer.isEmpty()) return false; + if (DataProvider.BUILD_TEAM.removeReviewer(ID, reviewerUUID)) { + this.reviewers.remove(removeReviewer.get()); + return true; + } + return false; } - public static void addReviewer(int id, String reviewerUUID) throws SQLException { - DataProvider.BUILD_TEAM.addReviewer(id, reviewerUUID); + public boolean addReviewer(Builder reviewer) { + if (DataProvider.BUILD_TEAM.addReviewer(ID, reviewer.getUUID().toString())) { + this.reviewers.add(reviewer); + return true; + } + return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index e1053f3c..1e9a89f6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -48,7 +48,6 @@ import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class CityProject { - private final String ID; private final String countryCode; private String serverName; @@ -113,7 +112,7 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { ItemStack cpItem = getCountry().getCountryItem(); try { PlotDifficulty plotDifficulty = selectedPlotDifficulty != null ? - selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(getID(), Builder.byUUID(player.getUniqueId())).get(); + selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(this, Builder.byUUID(player.getUniqueId())).get(); int plotsOpen = DataProvider.PLOT.getPlots(this, Status.unclaimed).size(); int plotsInProgress = DataProvider.PLOT.getPlots(this, Status.unfinished, Status.unreviewed).size(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index d2a6db57..69e08c91 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -411,72 +411,6 @@ public boolean isRejected() { return (getStatus() == Status.unfinished || getStatus() == Status.unreviewed) && getTotalScore() != -1; // -1 == null } - - public static List getPlots() throws SQLException { - return listPlots(DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots").executeQuery()); - } - - public static List getPlots(Status... statuses) throws SQLException { - ResultSet rs = DatabaseConnection.createStatement(getStatusQuery("", statuses)).executeQuery(); - return listPlots(rs); - } - - // Temporary fix to receive plots of builder as member - private static List getPlotsAsMember(Builder builder, Status... status) throws SQLException { - List plots = new ArrayList<>(); - for (Status stat : status) { - plots.addAll(listPlots(DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots WHERE status = '" + stat.name() + "' AND INSTR(member_uuids, '" + builder.getUUID() + "') > 0 ORDER BY CAST(status AS CHAR)").executeQuery())); - } - return plots; - } - - public static List getPlots(int cityID, Status... statuses) throws SQLException { - return listPlots(DatabaseConnection.createStatement(getStatusQuery(" AND city_project_id = '" + cityID + "'", statuses)).executeQuery()); - } - - public static List getPlots(List cities, Status... statuses) throws SQLException { - if (cities.isEmpty()) { - return new ArrayList<>(); - } - StringBuilder query = new StringBuilder(" AND (city_project_id = "); - - for (int i = 0; i < cities.size(); i++) { - query.append(cities.get(i).getID()); - query.append((i != cities.size() - 1) ? " OR city_project_id = " : ")"); - } - - return listPlots(DatabaseConnection.createStatement(getStatusQuery(query.toString(), statuses)).executeQuery()); - } - - public static List getPlots(int cityID, PlotDifficulty plotDifficulty, Status status) throws SQLException { - return listPlots(DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots WHERE city_project_id = ? AND difficulty_id = ? AND status = ?") - .setValue(cityID) - .setValue(plotDifficulty.ordinal() + 1) - .setValue(status.name()) - .executeQuery()); - } - - private static String getStatusQuery(String additionalQuery, Status... statuses) { - StringBuilder query = new StringBuilder("SELECT id FROM plotsystem_plots WHERE status = "); - - for (int i = 0; i < statuses.length; i++) { - query.append("'").append(statuses[i].name()).append("'").append(additionalQuery); - query.append((i != statuses.length - 1) ? " OR status = " : ""); - } - return query.toString(); - } - - private static List listPlots(ResultSet rs) throws SQLException { - List plots = new ArrayList<>(); - - while (rs.next()) { - plots.add(new Plot(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - return plots; - } - public static double getMultiplierByDifficulty(PlotDifficulty plotDifficulty) throws SQLException { ResultSet rs = DatabaseConnection.createStatement("SELECT multiplier FROM plotsystem_difficulties WHERE id = ?") .setValue(plotDifficulty.ordinal() + 1).executeQuery(); @@ -512,12 +446,12 @@ public static boolean hasPlotDifficultyScoreRequirement(Builder builder, PlotDif return playerScore >= scoreRequirement; } - public static CompletableFuture getPlotDifficultyForBuilder(String cityID, Builder builder) throws SQLException { + public static CompletableFuture getPlotDifficultyForBuilder(CityProject city, Builder builder) throws SQLException { // Check if plot difficulties are available boolean easyHasPlots = false, mediumHasPlots = false, hardHasPlots = false; - if (!getPlots(cityID, PlotDifficulty.EASY, Status.unclaimed).isEmpty()) easyHasPlots = true; - if (!getPlots(cityID, PlotDifficulty.MEDIUM, Status.unclaimed).isEmpty()) mediumHasPlots = true; - if (!getPlots(cityID, PlotDifficulty.HARD, Status.unclaimed).isEmpty()) hardHasPlots = true; + if (!DataProvider.PLOT.getPlots(city, PlotDifficulty.EASY, Status.unclaimed).isEmpty()) easyHasPlots = true; + if (!DataProvider.PLOT.getPlots(city, PlotDifficulty.MEDIUM, Status.unclaimed).isEmpty()) mediumHasPlots = true; + if (!DataProvider.PLOT.getPlots(city, PlotDifficulty.HARD, Status.unclaimed).isEmpty()) hardHasPlots = true; if (hardHasPlots && hasPlotDifficultyScoreRequirement(builder, PlotDifficulty.HARD)) { // Return hard return CompletableFuture.completedFuture(PlotDifficulty.HARD); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 2ac77ccd..92d25685 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -25,7 +25,9 @@ package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; @@ -54,8 +56,8 @@ public class DefaultPlotGenerator extends AbstractPlotGenerator { public final static Map playerPlotGenerationHistory = new HashMap<>(); - public DefaultPlotGenerator(int cityID, PlotDifficulty plotDifficulty, Builder builder) throws SQLException { - this(Plot.getPlots(cityID, plotDifficulty, Status.unclaimed).get(new Random().nextInt(Plot.getPlots(cityID, plotDifficulty, Status.unclaimed).size())), builder); + public DefaultPlotGenerator(CityProject city, PlotDifficulty plotDifficulty, Builder builder) throws SQLException { + this(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).get(new Random().nextInt(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).size())), builder); } public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) throws SQLException { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index c1b7ac8c..132eaf5b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -118,8 +118,9 @@ public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { for (Status status : statuses) if (status == plot.getStatus()) return plot; return null; } else if (PlotWorld.isCityPlotWorld(worldName)) { - int cityID = Integer.parseInt(worldName.substring(2)); - List plots = Plot.getPlots(cityID, statuses); + String cityID = worldName.substring(2); // TODO: clarify if this should be intended behaviour + CityProject city = DataProvider.CITY_PROJECT.getCityProjectById(cityID); + List plots = DataProvider.PLOT.getPlots(city, statuses); if (plots.isEmpty()) return null; if (plots.size() == 1) return plots.getFirst(); @@ -300,7 +301,7 @@ public static CompletableFuture convertTerraToPlotXZ(AbstractPlot plot public static void checkPlotsForLastActivity() { Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> { try { - List plots = Plot.getPlots(Status.unfinished); + List plots = DataProvider.PLOT.getPlots(Status.unfinished); FileConfiguration config = PlotSystem.getPlugin().getConfig(); long millisInDays = config.getLong(ConfigPaths.INACTIVITY_INTERVAL) * 24 * 60 * 60 * 1000; // Remove all plots which have no activity for the last x days @@ -329,7 +330,7 @@ public static void syncPlotSchematicFiles() { Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> DataProvider.CITY_PROJECT.getCityProjects(false).forEach(c -> { try { if (c.getCountry().getServer().getFTPConfiguration() != null) { - List plots = Plot.getPlots(c.getID(), Status.unclaimed); + List plots = DataProvider.PLOT.getPlots(c, Status.unclaimed); plots.forEach(Plot::getOutlinesSchematic); } } catch (SQLException ex) { From 65f83c6115ae5757141a86d1ced0a0a264076009 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Wed, 29 Jan 2025 21:48:08 +0100 Subject: [PATCH 019/175] remove getReviewers method from build team dataprovider --- .../core/database/providers/BuildTeamProvider.java | 5 ----- .../java/com/alpsbte/plotsystem/core/system/BuildTeam.java | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 570fc593..9e60702f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -34,11 +34,6 @@ public BuildTeam getBuildTeam(int id) { return null; } - public List getReviewers(int id) { - // TODO: implement - return List.of(); - } - public List getBuildTeamsByReviewer(UUID reviewerUUID) { // TODO: implement return List.of(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 4d8a5aad..356ad553 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -57,7 +57,7 @@ public List getCountries() { } public List getReviewers() { - return DataProvider.BUILD_TEAM.getReviewers(ID); + return reviewers; } public boolean setName(String newName) { From 2a1665405a252b64c6a41e49d99b4b73bb250661 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Wed, 29 Jan 2025 22:31:32 +0100 Subject: [PATCH 020/175] delete redundant Server.java model and implement ServerProvider.java --- .../commands/admin/setup/CMD_Setup_City.java | 14 +- .../admin/setup/CMD_Setup_Country.java | 8 +- .../admin/setup/CMD_Setup_Server.java | 121 ++++-------------- .../core/database/DataProvider.java | 1 + .../database/providers/ServerProvider.java | 26 ++++ .../plotsystem/core/system/Server.java | 111 ---------------- .../core/system/plot/utils/PlotUtils.java | 1 - .../plotsystem/utils/io/FTPManager.java | 1 - 8 files changed, 68 insertions(+), 215 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/Server.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 9f5436c7..670a812a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -146,7 +146,12 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 255 characters!")); return; } - // TODO: verify if server exists + // Check if server exists + if (!DataProvider.SERVER.serverExists(serverName)) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + serverName + "!")); + sendInfo(sender); + return; + } boolean added = DataProvider.CITY_PROJECT.addCityProject(cityProjectId, country.getCode(), serverName); if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); @@ -236,7 +241,12 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 255 characters!")); return; } - // TODO: verify if server exists + // Check if server exists + if (!DataProvider.SERVER.serverExists(serverName)) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + serverName + "!")); + sendInfo(sender); + return; + } boolean successful = cityProject.setServer(serverName); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed server of City Project with ID " + args[1] + " to '" + serverName + "'!")); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index b7d98cf5..a576a03c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -39,6 +39,7 @@ import java.util.List; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.*; public class CMD_Setup_Country extends SubCommand { @@ -94,15 +95,18 @@ public void onCommand(CommandSender sender, String[] args) { } sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + countries.size() + " Countries registered in the database:")); - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); for (Country c : countries) { try { sender.sendMessage(" §6> §b" + c.getCode() + " §f- Server: " + c.getServer().getID() + " (" + c.getServer().getName() + ")"); + sender.sendMessage(text(" » ", DARK_GRAY) + .append(text(c.getCode(), AQUA)) + .append(text(" - Server: " + c.getServer().getID(), WHITE))); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } } - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index 16cfb6bb..9c6a1688 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -24,24 +24,17 @@ package com.alpsbte.plotsystem.commands.admin.setup; -import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; -import com.alpsbte.plotsystem.core.system.FTPConfiguration; -import com.alpsbte.plotsystem.core.system.Server; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.utils.Utils; -import org.apache.commons.io.FileUtils; import org.bukkit.command.CommandSender; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.SQLException; import java.util.List; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; public class CMD_Setup_Server extends SubCommand { @@ -54,7 +47,6 @@ private void register() { registerSubCommand(new CMD_Setup_Server_List(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_Server_Add(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_Server_Remove(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_Server_SetFTP(getBaseCommand(), this)); } @Override @@ -90,22 +82,18 @@ public CMD_Setup_Server_List(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - List servers = Server.getServers(); + List servers = DataProvider.SERVER.getServers(); if (servers.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no Servers registered in the database!")); return; } sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + servers.size() + " Servers registered in the database:")); - sender.sendMessage("§8--------------------------"); - for (Server s : servers) { - try { - sender.sendMessage(" §6> §b" + s.getID() + " (" + s.getName() + ") §f- FTP-Configuration: " + (s.getFTPConfiguration() == null ? "None" : s.getFTPConfiguration().getID())); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + sender.sendMessage(text("--------------------------", DARK_GRAY)); + for (String server : servers) { + sender.sendMessage(text(" » ", DARK_GRAY).append(text(server, AQUA))); } - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); } @Override @@ -137,22 +125,15 @@ public CMD_Setup_Server_Add(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { if (args.length <= 1) {sendInfo(sender); return;} - if (args[1].length() > 45) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 45 characters!")); + if (args[1].length() > 255) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 255 characters!")); sendInfo(sender); return; } - try { - Server server = Server.addServer(args[1]); - Path serverPath = Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(server.getID())); - if (serverPath.toFile().exists()) FileUtils.deleteDirectory(serverPath.toFile()); - if (!serverPath.toFile().mkdirs()) throw new IOException(); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added server!")); - } catch (SQLException | IOException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + boolean successful = DataProvider.SERVER.addServer(args[1]); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added server!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -183,23 +164,18 @@ public CMD_Setup_Server_Remove(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 1) {sendInfo(sender); return;} // Check if server exists - try { - if (Server.getServers().stream().noneMatch(s -> s.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + args[1] + "!")); - sendInfo(sender); - return; - } - Server.removeServer(Integer.parseInt(args[1])); - Path serverPath = Paths.get(PlotUtils.getDefaultSchematicPath(), args[1]); - if (serverPath.toFile().exists()) FileUtils.deleteDirectory(serverPath.toFile()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed server with ID " + args[1] + "!")); - } catch (SQLException | IOException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (!DataProvider.SERVER.serverExists(args[1])) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + args[1] + "!")); + sendInfo(sender); + return; } + + boolean successful = DataProvider.SERVER.removeServer(args[1]); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed server with ID " + args[1] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -214,7 +190,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"Server-ID"}; + return new String[]{"Name"}; } @Override @@ -222,55 +198,4 @@ public String getPermission() { return "plotsystem.admin.pss.server.remove"; } } - - public static class CMD_Setup_Server_SetFTP extends SubCommand { - public CMD_Setup_Server_SetFTP(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - - // Check if server exists - try { - if (Server.getServers().stream().noneMatch(s -> s.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + args[1] + "!")); - sendInfo(sender); - return; - } - if (!args[2].equalsIgnoreCase("none") && (AlpsUtils.tryParseInt(args[2]) == null || FTPConfiguration.getFTPConfigurations().stream().noneMatch(f -> f.getID() == Integer.parseInt(args[2])))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any ftp configurations with ID " + args[2] + "!")); - sendInfo(sender); - return; - } - int ftpID = AlpsUtils.tryParseInt(args[2]) != null ? Integer.parseInt(args[2]) : -1; - Server.setFTP(Integer.parseInt(args[1]), ftpID); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set FTP Configuration of server with ID " + args[1] + " to " + (ftpID == -1 ? "None" : ftpID) + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - } - - @Override - public String[] getNames() { - return new String[]{"setftp"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"Server-ID", "FTP-ID/None"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.server.setftp"; - } - } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 21c7970b..ee219b76 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -33,4 +33,5 @@ public class DataProvider { public static DifficultyProvider DIFFICULTY = new DifficultyProvider(); public static CityProjectProvider CITY_PROJECT = new CityProjectProvider(); public static CountryProvider COUNTRY = new CountryProvider(); + public static ServerProvider SERVER = new ServerProvider(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java new file mode 100644 index 00000000..031b1aff --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java @@ -0,0 +1,26 @@ +package com.alpsbte.plotsystem.core.database.providers; + +import java.util.List; + +public class ServerProvider { + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public boolean serverExists(String serverName) { + // TODO: implement + return false; + } + + public List getServers() { + // TODO: implement + return null; + } + + public boolean addServer(String name) { + // TODO: implement + return false; + } + + public boolean removeServer(String name) { + // TODO: implement + return false; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Server.java b/src/main/java/com/alpsbte/plotsystem/core/system/Server.java deleted file mode 100644 index d45c10ce..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Server.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.system; - -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; - -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import static net.kyori.adventure.text.Component.text; - -public class Server { - private final int ID; - private int ftpConfigurationID; - - private String name; - - public Server(int ID) throws SQLException { - this.ID = ID; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT ftp_configuration_id, name FROM plotsystem_servers WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - this.ftpConfigurationID = rs.getInt(1); - if (rs.wasNull()) this.ftpConfigurationID = -1; - - this.name = rs.getString(2); - } - - DatabaseConnection.closeResultSet(rs); - } - } - - public int getID() { - return ID; - } - - public String getName() { - return name; - } - - public FTPConfiguration getFTPConfiguration() throws SQLException { - return ftpConfigurationID != -1 ? new FTPConfiguration(ftpConfigurationID) : null; - } - - public static List getServers() { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_servers").executeQuery()) { - List servers = new ArrayList<>(); - while (rs.next()) { - servers.add(new Server(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - - return servers; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); - } - - public static Server addServer(String name) throws SQLException { - int id = DatabaseConnection.getTableID("plotsystem_servers"); - DatabaseConnection.createStatement("INSERT INTO plotsystem_servers (id, name) VALUES (?, ?)") - .setValue(id) - .setValue(name).executeUpdate(); - return new Server(id); - } - - public static void removeServer(int serverID) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_servers WHERE id = ?") - .setValue(serverID).executeUpdate(); - } - - public static void setFTP(int serverID, int ftpID) throws SQLException { - if (ftpID != -1) { - DatabaseConnection.createStatement("UPDATE plotsystem_servers SET ftp_configuration_id = ? WHERE id = ?") - .setValue(ftpID) - .setValue(serverID).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_servers SET ftp_configuration_id = DEFAULT WHERE id = ?") - .setValue(serverID).executeUpdate(); - } - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 132eaf5b..83ffbb29 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -29,7 +29,6 @@ import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Server; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java b/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java index f02a3391..f1732710 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.utils.io; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.system.Server; import org.apache.commons.vfs2.*; import org.apache.commons.vfs2.impl.StandardFileSystemManager; import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder; From fd90219862a611ed8f5d410ceef21aec262595de Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 17:52:43 +0100 Subject: [PATCH 021/175] start reworking plot generation with database rework --- .../com/alpsbte/plotsystem/PlotSystem.java | 1 - .../alpsbte/plotsystem/commands/CMD_Tpll.java | 4 - .../admin/setup/CMD_Setup_Country.java | 9 +- .../core/database/providers/PlotProvider.java | 57 ++++ .../plotsystem/core/menus/FeedbackMenu.java | 3 +- .../plotsystem/core/system/Review.java | 25 +- .../core/system/plot/AbstractPlot.java | 76 ++--- .../plotsystem/core/system/plot/Plot.java | 254 +++++--------- .../plot/generator/AbstractPlotGenerator.java | 68 ++-- .../plot/generator/DefaultPlotGenerator.java | 10 +- .../core/system/plot/utils/PlotUtils.java | 321 +++++++----------- .../core/system/plot/world/CityPlotWorld.java | 2 +- .../core/system/plot/world/OnePlotWorld.java | 2 +- .../core/system/plot/world/PlotWorld.java | 3 +- .../plotsystem/utils/io/FTPManager.java | 136 -------- 15 files changed, 348 insertions(+), 623 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 913c9baa..c084e242 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -188,7 +188,6 @@ public void onEnable() { DecentHologramDisplay.registerPlugin(this); HologramRegister.init(); PlotUtils.checkPlotsForLastActivity(); - PlotUtils.syncPlotSchematicFiles(); Utils.ChatUtils.checkForChatInputExpiry(); PlotUtils.Effects.startTimer(); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index ca06202c..7efa6832 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -46,7 +46,6 @@ import java.io.IOException; import java.math.RoundingMode; -import java.sql.SQLException; import java.text.DecimalFormat; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; @@ -129,9 +128,6 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N df.setRoundingMode(RoundingMode.FLOOR); player.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.TELEPORTING_TPLL, df.format(lat), df.format(lon)))); }); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); } catch (IOException | OutOfProjectionBoundsException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A coordinate conversion error occurred!"), ex); player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index a576a03c..2ee40ea8 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -97,14 +97,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + countries.size() + " Countries registered in the database:")); sender.sendMessage(text("--------------------------", DARK_GRAY)); for (Country c : countries) { - try { - sender.sendMessage(" §6> §b" + c.getCode() + " §f- Server: " + c.getServer().getID() + " (" + c.getServer().getName() + ")"); - sender.sendMessage(text(" » ", DARK_GRAY) - .append(text(c.getCode(), AQUA)) - .append(text(" - Server: " + c.getServer().getID(), WHITE))); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + sender.sendMessage(text(" » ", DARK_GRAY).append(text(c.getCode(), AQUA))); } sender.sendMessage(text("--------------------------", DARK_GRAY)); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 9d6b1d53..66a26c14 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -5,11 +5,15 @@ import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; +import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Status; +import java.time.LocalDate; import java.util.ArrayList; import java.util.List; +import java.util.UUID; public class PlotProvider { public Plot getPlotById(int plotId) { @@ -66,4 +70,57 @@ public Review getReview(int plotId) { // TODO: implement return null; } + + public byte[] getInitialSchematic(int plotId) { + // TODO: implement + return null; + } + + public byte[] getCompletedSchematic(int plotId) { + // TODO: implement + return null; + } + + public boolean setCompletedSchematic(int plotId, byte[] completedSchematic) { + // TODO: implement + // set to default if completedSchematic is null (for undoing review) + return false; + } + + public boolean setPlotOwner(int plotId, UUID ownerUUID) { + // TODO: implement + // (should also be able to be set to null in case a plot gets abandoned) + return false; + } + + public boolean setLastActivity(int plotId, LocalDate activityDate) { + // TODO: implement + // set last_activity to null if activityDate is null + return false; + } + + public boolean setStatus(int plotId, Status status) { + // TODO: implement + return false; + } + + public boolean setPlotMembers(int plotId, List members) { + // TODO: implement + return false; + } + + public boolean setPlotType(int plotId, PlotType type) { + // TODO: implement + return false; + } + + public boolean deletePlot(int plotId) { + // TODO: implement + return false; + } + + public TutorialPlot getTutorialPlotById(int tutorialPlotId) { + // TODO: implement + return null; + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index b37a0074..47df0c8a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -28,6 +28,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -56,7 +57,7 @@ public class FeedbackMenu extends AbstractMenu { public FeedbackMenu(Player player, int plotID) { super(3, LangUtil.getInstance().get(player, LangPaths.MenuTitle.FEEDBACK, String.valueOf(plotID)), player); - this.plot = new Plot(plotID); + this.plot = DataProvider.PLOT.getPlotById(plotID); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java index 1492e536..df4a6838 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java @@ -30,12 +30,8 @@ import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Category; import com.alpsbte.plotsystem.utils.enums.Status; -import com.alpsbte.plotsystem.utils.io.FTPManager; import org.bukkit.Bukkit; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Files; import java.sql.Date; import java.sql.ResultSet; import java.sql.SQLException; @@ -223,26 +219,9 @@ public static void undoReview(Review review) { plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID()); } - int cityId = plot.getCity().getID(); - Server plotServer = plot.getCity().getCountry().getServer(); - boolean hasFTPConfiguration = plotServer.getFTPConfiguration() != null; - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - plot.getWorld().loadWorld(); - - try { - Files.deleteIfExists(plot.getCompletedSchematic().toPath()); - - if (hasFTPConfiguration) { - FTPManager.deleteSchematic(FTPManager.getFTPUrl(plotServer, cityId), plot.getID() + ".schem"); - FTPManager.deleteSchematic(FTPManager.getFTPUrl(plotServer, cityId), plot.getID() + ".schematic"); - } - } catch (IOException | SQLException | URISyntaxException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while undoing review!"), ex); - } - - plot.getWorld().unloadWorld(true); - }); + DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); + // TODO: extract sql to data provider DatabaseConnection.createStatement("UPDATE plotsystem_plots SET review_id = DEFAULT(review_id) WHERE id = ?") .setValue(review.getPlotID()).executeUpdate(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 5a72c3b4..852140fc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -28,40 +28,39 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.utils.PlotPermissions; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.conversion.CoordinateConversion; import com.alpsbte.plotsystem.utils.conversion.projection.OutOfProjectionBoundsException; import com.alpsbte.plotsystem.utils.enums.Status; -import com.fastasyncworldedit.core.FaweAPI; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.Vector3; -import com.sk89q.worldedit.regions.CuboidRegion; import org.jetbrains.annotations.NotNull; -import java.io.File; +import java.io.ByteArrayInputStream; import java.io.IOException; -import java.sql.SQLException; +import java.time.LocalDate; import java.util.ArrayList; -import java.util.Date; import java.util.List; import static net.kyori.adventure.text.Component.text; public abstract class AbstractPlot { public static final double PLOT_VERSION = 3; - + public static final ClipboardFormat CLIPBOARD_FORMAT = BuiltInClipboardFormat.FAST_V2; protected final int ID; protected Builder plotOwner; protected OnePlotWorld onePlotWorld; protected PlotPermissions plotPermissions; protected PlotType plotType; - protected double plotVersion = -1; + protected double plotVersion; protected List outline; protected List blockOutline; @@ -79,9 +78,8 @@ public int getID() { /** * @return builder who has claimed the plot - * @throws SQLException SQL database exception */ - public abstract Builder getPlotOwner() throws SQLException; + public abstract Builder getPlotOwner(); /** * @return plot world, can be one or city plot world @@ -91,48 +89,37 @@ public int getID() { /** * @return the outline of the plot which contains all corner points of the polygon */ - public abstract List getOutline() throws SQLException, IOException; + public abstract List getOutline() throws IOException; /** * @return last date on which the plot owner teleported to the plot - * @throws SQLException SQL database exception */ - public abstract Date getLastActivity() throws SQLException; + public abstract LocalDate getLastActivity(); /** * Sets the last activity to the current date and time * * @param setNull if true, set last activity to null - * @throws SQLException SQL database exception */ - public abstract void setLastActivity(boolean setNull) throws SQLException; + public abstract boolean setLastActivity(boolean setNull); public abstract Status getStatus(); - public abstract void setStatus(@NotNull Status status) throws SQLException; + public abstract boolean setStatus(@NotNull Status status); /** * Returns the plot type the player has selected when creating the plot * * @return the plot type - * @throws SQLException SQL database exception */ - public abstract PlotType getPlotType() throws SQLException; + public abstract PlotType getPlotType(); public abstract double getVersion(); - protected abstract File getSchematicFile(String fileName); - /** * @return schematic file with outlines only */ - public abstract File getOutlinesSchematic(); - - /** - * @return schematic file with environment only - */ - public abstract File getEnvironmentSchematic(); - + public abstract byte[] getInitialSchematicBytes(); /** * Returns geographic coordinates in numeric format @@ -160,14 +147,18 @@ public String getGeoCoordinates() throws IOException { * @see com.alpsbte.plotsystem.utils.conversion.CoordinateConversion#convertFromGeo(double, double) */ public BlockVector3 getCoordinates() throws IOException { - Clipboard clipboard = FaweAPI.load(getOutlinesSchematic()); - if (clipboard != null) return clipboard.getOrigin(); + ByteArrayInputStream inputStream = new ByteArrayInputStream(getInitialSchematicBytes()); + try (ClipboardReader reader = CLIPBOARD_FORMAT.getReader(inputStream)) { + Clipboard clipboard = reader.read(); + if (clipboard != null) return clipboard.getOrigin(); + } return null; } public BlockVector3 getCenter() { - try { - Clipboard clipboard = FaweAPI.load(getOutlinesSchematic()); + ByteArrayInputStream inputStream = new ByteArrayInputStream(getInitialSchematicBytes()); + try (ClipboardReader reader = CLIPBOARD_FORMAT.getReader(inputStream)){ + Clipboard clipboard = reader.read(); if (clipboard != null) { Vector3 clipboardCenter = clipboard.getRegion().getCenter(); return BlockVector3.at(clipboardCenter.x(), this.getWorld().getPlotHeightCentered(), clipboardCenter.z()); @@ -198,18 +189,13 @@ public String getGoogleEarthLink() throws IOException { return "https://earth.google.com/web/@" + getGeoCoordinates() + ",0a,1000d,20y,-0h,0t,0r"; } - protected List getOutlinePoints(String outlinePoints) throws SQLException, IOException { + protected List getOutlinePoints(String outlinePoints) { List locations = new ArrayList<>(); - if (outlinePoints == null) { - CuboidRegion plotRegion = PlotUtils.getPlotAsRegion(this); - if (plotRegion != null) locations.addAll(plotRegion.polygonize(4)); - } else { - String[] list = outlinePoints.split("\\|"); - - for (String s : list) { - String[] locs = s.split(","); - locations.add(BlockVector2.at(Double.parseDouble(locs[0]), Double.parseDouble(locs[1]))); - } + String[] list = outlinePoints.split("\\|"); + + for (String s : list) { + String[] locs = s.split(","); + locations.add(BlockVector2.at(Double.parseDouble(locs[0]), Double.parseDouble(locs[1]))); } this.outline = locations; return locations; @@ -218,7 +204,7 @@ protected List getOutlinePoints(String outlinePoints) throws SQLEx /** * @return the outline of the polygon with one point per Block */ - public final List getBlockOutline() throws SQLException, IOException { + public final List getBlockOutline() throws IOException { if (this.blockOutline != null) return this.blockOutline; @@ -233,8 +219,8 @@ public final List getBlockOutline() throws SQLException, IOExcepti points.addAll(Utils.getLineBetweenPoints(b1, b2, distance)); } - BlockVector2 first = outline.get(0); - BlockVector2 last = outline.get(outline.size() - 1); + BlockVector2 first = outline.getFirst(); + BlockVector2 last = outline.getLast(); points.addAll(Utils.getLineBetweenPoints(last, first, (int) first.distance(last))); this.blockOutline = points; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 69e08c91..584b5c7e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -31,7 +31,6 @@ import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; @@ -39,83 +38,94 @@ import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Slot; import com.alpsbte.plotsystem.utils.enums.Status; -import com.alpsbte.plotsystem.utils.io.FTPManager; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.*; -import java.net.URISyntaxException; -import java.nio.file.Paths; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; -import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.stream.Collectors; import static net.kyori.adventure.text.Component.text; public class Plot extends AbstractPlot { - private CityProject city; + private final CityProject city; + private final PlotDifficulty difficulty; + private final Builder plotCreator; + private final Date createdDate; + private final String outlineString; + private CityPlotWorld cityPlotWorld; private Status status; - - // TODO: delete constructor - public Plot(int id) { + private LocalDate lastActivity; + private List plotMembers; + + // missing: + // outlineBounds + // initialSchem + // is_pasted + public Plot( + int id, + Status status, + CityProject city, + PlotDifficulty difficulty, + Builder createdBy, + Date createdDate, + double plotVersion, + String outline, + LocalDate lastActivity, + List members, + PlotType type + ) { super(id); + this.status = status; + this.city = city; + this.difficulty = difficulty; + this.plotCreator = createdBy; + this.createdDate = createdDate; + this.plotVersion = plotVersion; + this.outlineString = outline; + this.lastActivity = lastActivity; + this.plotMembers = members; + this.plotType = type; } - public CityProject getCity() { - // TODO: implement - return null; + return city; } public PlotDifficulty getDifficulty() { - // TODO: implement - return null; + return difficulty; } @Override public Builder getPlotOwner() { - // TODO: implement - - if (plotOwner != null) - return plotOwner; - return null; + return plotOwner; } - public void setPlotOwner(String UUID) throws SQLException { - if (UUID == null) { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET owner_uuid = DEFAULT(owner_uuid) WHERE id = ?") - .setValue(this.ID).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET owner_uuid = ? WHERE id = ?") - .setValue(UUID).setValue(this.ID).executeUpdate(); + public boolean setPlotOwner(@Nullable Builder newPlotOwner) { + if (DataProvider.PLOT.setPlotOwner(ID, newPlotOwner == null ? null : newPlotOwner.getUUID())) { + plotOwner = newPlotOwner; + return true; } - - plotOwner = null; + return false; } public List getPlotMembers() { - return DataProvider.PLOT.getPlotMembers(ID); + return plotMembers; } - public void setPlotMembers(@NotNull List plotMembers) throws SQLException { - // Convert plot member list to string - String plotMemberAsString = plotMembers.stream().map(member -> member.getUUID().toString()).collect(Collectors.joining(",")); - - if (!plotMembers.isEmpty()) { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET member_uuids = ? WHERE id = ?") - .setValue(plotMemberAsString).setValue(this.ID).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET member_uuids = DEFAULT(member_uuids) WHERE id = ?") - .setValue(this.ID).executeUpdate(); + public boolean setPlotMembers(@NotNull List plotMembers) { + if (DataProvider.PLOT.setPlotMembers(ID, plotMembers)) { + this.plotMembers = plotMembers; + return true; } + return false; } @SuppressWarnings("unchecked") @@ -134,50 +144,28 @@ public T getWorld() { } @Override - public List getOutline() throws SQLException, IOException { + public List getOutline() throws IOException { if (outline != null) return this.outline; - try (ResultSet rs = DatabaseConnection.createStatement("SELECT outline FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - List pointVectors = new ArrayList<>(); - if (rs.next()) { - String points = rs.getString(1); - pointVectors = getOutlinePoints((rs.wasNull() || points.isEmpty() || getVersion() <= 2) ? null : points); - } - - DatabaseConnection.closeResultSet(rs); - return pointVectors; - } + List pointVectors; + pointVectors = getOutlinePoints((outlineString.isEmpty() || getVersion() <= 2) ? null : outlineString); + return pointVectors; } @Override - public Date getLastActivity() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT last_activity FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - Date d = rs.getDate(1); - DatabaseConnection.closeResultSet(rs); - return d; - } - - DatabaseConnection.closeResultSet(rs); - - return null; - } + public LocalDate getLastActivity() { + return lastActivity; } @Override - public void setLastActivity(boolean setNull) throws SQLException { - if (setNull) { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET last_activity = DEFAULT(last_activity) WHERE id = ?") - .setValue(this.ID).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET last_activity = ? WHERE id = ?") - .setValue(java.sql.Date.valueOf(LocalDate.now())).setValue(this.ID).executeUpdate(); + public boolean setLastActivity(boolean setNull) { + LocalDate activityDate = setNull ? null : LocalDate.now(); + if (DataProvider.PLOT.setLastActivity(ID, activityDate)) { + this.lastActivity = activityDate; + return true; } + return false; } @Override @@ -186,9 +174,12 @@ public Status getStatus() { } @Override - public void setStatus(@NotNull Status status) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET status = ? WHERE id = ?") - .setValue(status.name()).setValue(this.ID).executeUpdate(); + public boolean setStatus(@NotNull Status status) { + if (DataProvider.PLOT.setStatus(ID, status)) { + this.status = status; + return true; + } + return false; } public int getTotalScore() { @@ -215,109 +206,28 @@ public int getSharedScore() throws SQLException { } @Override - public PlotType getPlotType() throws SQLException { - if (plotType != null) return plotType; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT type FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int typeId = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - - plotType = PlotType.byId(typeId); - return plotType; - } - - DatabaseConnection.closeResultSet(rs); - return null; - } + public PlotType getPlotType() { + return plotType; } - public void setPlotType(PlotType type) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET type = ? WHERE id = ?") - .setValue(type.ordinal()).setValue(this.ID).executeUpdate(); - plotType = type; + public boolean setPlotType(PlotType type) { + if (DataProvider.PLOT.setPlotType(ID, type)) { + this.plotType = type; + return true; + } + return false; } @Override public double getVersion() { - if (plotVersion != -1) return plotVersion; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT version FROM plotsystem_plots WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - double version = rs.getDouble(1); - if (!rs.wasNull()) { - plotVersion = version; - } else { - plotVersion = 2; // Plot version was implemented since v3, so we assume that the plot is v2. - } - - DatabaseConnection.closeResultSet(rs); - return plotVersion; - } - - DatabaseConnection.closeResultSet(rs); - } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - return PLOT_VERSION; + return plotVersion; } @Override - public File getOutlinesSchematic() { - return getSchematicFile(String.valueOf(getID())); - } + public byte[] getInitialSchematicBytes() {return DataProvider.PLOT.getInitialSchematic(ID);} - @Override - public File getEnvironmentSchematic() { - return getSchematicFile(getID() + "-env"); - } - - @Override - protected File getSchematicFile(String fileName) { - try { - return CompletableFuture.supplyAsync(() -> { - try { - File file = Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(getCity().getCountry().getServer().getID()), String.valueOf(getCity().getID()), fileName + ".schem").toFile(); - - if (!file.exists()) { - // if .schem doesn't exist, it looks for old .schematic format for backwards compatibility - file = Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(getCity().getCountry().getServer().getID()), String.valueOf(getCity().getID()), fileName + ".schematic").toFile(); - } - - if (!file.exists()) { - if (getCity().getCountry().getServer().getFTPConfiguration() != null) { - if (!FTPManager.downloadSchematic(FTPManager.getFTPUrl(getCity().getCountry().getServer(), getCity().getID()), file)) { - file = Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(getCity().getCountry().getServer().getID()), String.valueOf(getCity().getID()), fileName + ".schem").toFile(); - FTPManager.downloadSchematic(FTPManager.getFTPUrl(getCity().getCountry().getServer(), getCity().getID()), file); - } - } - } - - return file; - } catch (SQLException | URISyntaxException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return null; - }).get(); - } catch (InterruptedException | ExecutionException ex) { - return null; - } - } - - public File getCompletedSchematic() { - try { - File file = Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(getCity().getCountry().getServer().getID()), "finishedSchematics", String.valueOf(getCity().getID()), getID() + ".schem").toFile(); - if (!file.exists()) { - // if .schem doesn't exist, it looks for old .schematic format for backwards compatibility - file = Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(getCity().getCountry().getServer().getID()), "finishedSchematics", String.valueOf(getCity().getID()), getID() + ".schematic").toFile(); - } - return file; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return null; + public byte[] getCompletedSchematic() { + return DataProvider.PLOT.getCompletedSchematic(ID); } @Deprecated @@ -377,7 +287,7 @@ public void setPasted(boolean pasted) throws SQLException { .setValue(pasted).setValue(this.ID).executeUpdate(); } - public void addPlotMember(Builder member) throws SQLException { + public void addPlotMember(Builder member) { List members = getPlotMembers(); if (members.size() < 3 && members.stream().noneMatch(m -> m.getUUID().equals(member.getUUID()))) { Slot slot = member.getFreeSlot(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 5a2d7576..45b3dec8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -38,13 +38,13 @@ import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.fastasyncworldedit.core.FaweAPI; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.function.mask.BlockTypeMask; import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.mask.RegionMask; @@ -72,7 +72,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.SQLException; import java.util.HashSet; @@ -94,7 +94,7 @@ public abstract class AbstractPlotGenerator { * @param plot - plot which should be generated * @param builder - builder of the plot */ - public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) throws SQLException { + public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) { this(plot, builder, builder.getPlotType()); } @@ -105,7 +105,7 @@ public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builde * @param builder - builder of the plot * @param plotType - type of the plot */ - public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder, @NotNull PlotType plotType) throws SQLException { + public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder, @NotNull PlotType plotType) { this(plot, builder, plotType, plot.getVersion() <= 2 || plotType.hasOnePlotPerWorld() ? new OnePlotWorld(plot) : new CityPlotWorld((Plot) plot)); } @@ -129,7 +129,7 @@ private AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder build if (plotType.hasOnePlotPerWorld() || !world.isWorldGenerated()) { new PlotWorldGenerator(world.getWorldName()); } else if (!world.isWorldLoaded() && !world.loadWorld()) throw new Exception("Could not load world"); - generateOutlines(plot.getOutlinesSchematic(), plot.getVersion() >= 3 ? plot.getEnvironmentSchematic() : null); + generateOutlines(); createPlotProtection(); } catch (Exception ex) { exception = ex; @@ -159,23 +159,19 @@ private AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder build /** * Generates plot schematic and outlines - * - * @param plotSchematic - plot schematic file - * @param environmentSchematic - environment schematic file */ - protected void generateOutlines(@NotNull File plotSchematic, @Nullable File environmentSchematic) throws IOException, WorldEditException, SQLException { + protected void generateOutlines() throws IOException, WorldEditException { Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); - if (plotVersion >= 3 && plotType.hasEnvironment() && environmentSchematic != null && environmentSchematic.exists()) { - pasteSchematic(airMask, environmentSchematic, world, false); - } - pasteSchematic(airMask, plotSchematic, world, true); + if (plotVersion >= 3 && plotType.hasEnvironment()) { + pasteSchematic(airMask, plot.getInitialSchematicBytes(), world, false); + } else pasteSchematic(airMask, PlotUtils.getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true); } /** * Creates plot protection */ - protected void createPlotProtection() throws StorageException, SQLException, IOException { + protected void createPlotProtection() throws StorageException, IOException { RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionManager regionManager = regionContainer.get(BukkitAdapter.adapt(world.getBukkitWorld())); @@ -300,25 +296,35 @@ public Builder getBuilder() { * @param world - world to paste in * @param clearArea - clears the plot area with air before pasting */ - public static void pasteSchematic(@Nullable Mask pasteMask, File schematicFile, PlotWorld world, boolean clearArea) throws IOException, WorldEditException, SQLException { - if (world.loadWorld()) { - World weWorld = new BukkitWorld(world.getBukkitWorld()); - try (EditSession editSession = WorldEdit.getInstance().newEditSession(BukkitAdapter.adapt(world.getBukkitWorld()))) { - if (clearArea) { - Polygonal2DRegion polyRegion = new Polygonal2DRegion(weWorld, world.getPlot().getOutline(), 0, PlotWorld.MAX_WORLD_HEIGHT); - editSession.setMask(new RegionMask(polyRegion)); - editSession.setBlocks((Region) polyRegion, Objects.requireNonNull(BlockTypes.AIR).getDefaultState()); - } - } + public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, PlotWorld world, boolean clearArea) throws IOException, WorldEditException { + // load world + if (!world.loadWorld()) return; + World weWorld = new BukkitWorld(world.getBukkitWorld()); + + // set outline region with air + if (clearArea) { try (EditSession editSession = WorldEdit.getInstance().newEditSession(BukkitAdapter.adapt(world.getBukkitWorld()))) { - if (pasteMask != null) editSession.setMask(pasteMask); - Clipboard clipboard = FaweAPI.load(schematicFile); - Operation clipboardHolder = new ClipboardHolder(clipboard) - .createPaste(editSession) - .to(BlockVector3.at(world.getPlot().getCenter().x(), world.getPlotHeight(), world.getPlot().getCenter().z())) - .build(); - Operations.complete(clipboardHolder); + Polygonal2DRegion polyRegion = new Polygonal2DRegion(weWorld, world.getPlot().getOutline(), 0, PlotWorld.MAX_WORLD_HEIGHT); + editSession.setMask(new RegionMask(polyRegion)); + editSession.setBlocks((Region) polyRegion, Objects.requireNonNull(BlockTypes.AIR).getDefaultState()); } } + + // load schematic + Clipboard clipboard; + ByteArrayInputStream inputStream = new ByteArrayInputStream(schematicFile); + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { + clipboard = reader.read(); + } + + // paste schematic + try (EditSession editSession = WorldEdit.getInstance().newEditSession(BukkitAdapter.adapt(world.getBukkitWorld()))) { + if (pasteMask != null) editSession.setMask(pasteMask); + Operation clipboardHolder = new ClipboardHolder(clipboard) + .createPaste(editSession) + .to(BlockVector3.at(world.getPlot().getCenter().x(), world.getPlotHeight(), world.getPlot().getCenter().z())) + .build(); + Operations.complete(clipboardHolder); + } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 92d25685..f24141ac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -40,9 +40,7 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.sk89q.worldedit.WorldEditException; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.time.LocalDateTime; @@ -64,7 +62,7 @@ public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder super(plot, builder); } - public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder, PlotType plotType) throws SQLException { + public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder, PlotType plotType) { super(plot, builder, plotType); } @@ -93,8 +91,8 @@ protected boolean init() { } @Override - protected void generateOutlines(@NotNull File plotSchematic, @Nullable File environmentSchematic) throws IOException, WorldEditException, SQLException { - super.generateOutlines(plotSchematic, environmentSchematic); + protected void generateOutlines() throws IOException, WorldEditException { + super.generateOutlines(); // If the player is playing in his own world, then additionally generate the plot in the city world if (PlotWorld.isOnePlotWorld(world.getWorldName()) && plotVersion >= 3 && plot.getStatus() != Status.completed) { @@ -129,7 +127,7 @@ protected void onComplete(boolean failed, boolean unloadWorld) throws SQLExcepti getBuilder().setSlot(getBuilder().getFreeSlot(), plot.getID()); plot.setStatus(Status.unfinished); ((Plot) plot).setPlotType(plotType); - ((Plot) plot).setPlotOwner(getBuilder().getPlayer().getUniqueId().toString()); + ((Plot) plot).setPlotOwner(getBuilder()); PlotUtils.Cache.clearCache(getBuilder().getUUID()); plot.getWorld().teleportPlayer(getBuilder().getPlayer()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 83ffbb29..1b0675d8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -40,10 +40,8 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.alpsbte.plotsystem.utils.io.FTPManager; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.fastasyncworldedit.core.FaweAPI; import com.github.fierioziy.particlenativeapi.api.ParticleNativeAPI; import com.github.fierioziy.particlenativeapi.api.Particles_1_8; import com.github.fierioziy.particlenativeapi.plugin.ParticleNativePlugin; @@ -52,7 +50,7 @@ import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.extent.clipboard.BlockArrayClipboard; import com.sk89q.worldedit.extent.clipboard.Clipboard; -import com.sk89q.worldedit.extent.clipboard.io.BuiltInClipboardFormat; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; @@ -76,15 +74,13 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; +import java.io.*; import java.math.RoundingMode; import java.net.URISyntaxException; -import java.nio.file.Files; import java.nio.file.Paths; import java.sql.SQLException; import java.text.DecimalFormat; +import java.time.LocalDate; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; @@ -112,12 +108,14 @@ public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { if (PlotWorld.isOnePlotWorld(worldName)) { int id = Integer.parseInt(worldName.substring(2)); - AbstractPlot plot = worldName.toLowerCase(Locale.ROOT).startsWith("p-") ? new Plot(id) : new TutorialPlot(id); + AbstractPlot plot = worldName.toLowerCase(Locale.ROOT).startsWith("p-") + ? DataProvider.PLOT.getPlotById(id) + : DataProvider.PLOT.getTutorialPlotById(id); if (statuses == null) return plot; for (Status status : statuses) if (status == plot.getStatus()) return plot; return null; } else if (PlotWorld.isCityPlotWorld(worldName)) { - String cityID = worldName.substring(2); // TODO: clarify if this should be intended behaviour + String cityID = worldName.substring(2); CityProject city = DataProvider.CITY_PROJECT.getCityProjectById(cityID); List plots = DataProvider.PLOT.getPlots(city, statuses); @@ -130,11 +128,14 @@ public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { double distance = 100000000; Plot chosenPlot = plots.getFirst(); - for (Plot plot : plots) - if (plot.getPlotType() == PlotType.CITY_INSPIRATION_MODE && plot.getCenter().withY((int) playerVector.y()).distance(playerVector.toBlockPoint()) < distance) { - distance = plot.getCenter().distance(playerVector.toBlockPoint()); + for (Plot plot : plots) { + if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE) continue; + BlockVector3 plotCenter = plot.getCenter(); + if (plotCenter.withY((int) playerVector.y()).distance(playerVector.toBlockPoint()) < distance) { + distance = plotCenter.distance(playerVector.toBlockPoint()); chosenPlot = plot; } + } return chosenPlot; } @@ -151,147 +152,126 @@ public static boolean isPlayerOnPlot(AbstractPlot plot, Player player) { } public static CuboidRegion getPlotAsRegion(AbstractPlot plot) throws IOException { - Clipboard clipboard = FaweAPI.load(plot.getOutlinesSchematic()); - if (clipboard != null) { - if (plot.getVersion() >= 3) { - return new CuboidRegion( - clipboard.getMinimumPoint().withY(plot.getWorld().getPlotHeight()), - clipboard.getMaximumPoint().withY(PlotWorld.MAX_WORLD_HEIGHT)); - } else { - BlockVector3 plotCenter = plot.getCenter(); - - // Calculate min and max points of schematic - int regionCenterModX = clipboard.getRegion().getWidth() % 2 == 0 ? 1 : 0; - int regionCenterModZ = clipboard.getRegion().getLength() % 2 == 0 ? 1 : 0; - int outlinesClipboardCenterX = (int) Math.floor(clipboard.getRegion().getWidth() / 2d); - int outlinesClipboardCenterZ = (int) Math.floor(clipboard.getRegion().getLength() / 2d); - - BlockVector3 schematicMinPoint = BlockVector3.at( - plotCenter.x() - (outlinesClipboardCenterX - regionCenterModX), - PlotWorld.MIN_WORLD_HEIGHT, - plotCenter.z() - (outlinesClipboardCenterZ - regionCenterModZ) - ); - - BlockVector3 schematicMaxPoint = BlockVector3.at( - plotCenter.x() + outlinesClipboardCenterX, - PlotWorld.MAX_WORLD_HEIGHT, - plotCenter.z() + outlinesClipboardCenterZ - ); - - return new CuboidRegion(schematicMinPoint, schematicMaxPoint); - } + Clipboard clipboard; + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(new ByteArrayInputStream(plot.getInitialSchematicBytes()))) { + clipboard = reader.read(); } - return null; + if (clipboard == null) return null; + + // No longer supported! + if (plot.getVersion() < 3) return null; + + return new CuboidRegion( + clipboard.getMinimumPoint().withY(plot.getWorld().getPlotHeight()), + clipboard.getMaximumPoint().withY(PlotWorld.MAX_WORLD_HEIGHT)); } public static boolean isPlotWorld(World world) { return PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().isMVWorld(world) && (PlotWorld.isOnePlotWorld(world.getName()) || PlotWorld.isCityPlotWorld(world.getName())); } + public static byte[] getOutlinesSchematicBytes(AbstractPlot plot, World world) throws IOException { + Clipboard clipboard; + ByteArrayInputStream inputStream = new ByteArrayInputStream(plot.getInitialSchematicBytes()); + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { + clipboard = reader.read(); + } + + Polygonal2DRegion region = new Polygonal2DRegion(BukkitAdapter.adapt(world), plot.getOutline(), clipboard.getMinimumPoint().y(), clipboard.getMaximumPoint().y()); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { + writer.write(new BlockArrayClipboard(region)); + } + return null; + } public static String getDefaultSchematicPath() { return Paths.get(PlotSystem.getPlugin().getDataFolder().getAbsolutePath(), "schematics") + File.separator; } public static boolean savePlotAsSchematic(Plot plot) throws IOException, SQLException, WorldEditException { - Clipboard clipboard = FaweAPI.load(plot.getOutlinesSchematic()); - if (clipboard != null) { - CuboidRegion cuboidRegion = getPlotAsRegion(plot); - - if (cuboidRegion != null) { - BlockVector3 plotCenter = plot.getCenter(); - - // Get plot outline - List plotOutlines = plot.getOutline(); - - // Load finished plot region as cuboid region - if (plot.getWorld().loadWorld()) { - com.sk89q.worldedit.world.World world = new BukkitWorld(plot.getWorld().getBukkitWorld()); - Polygonal2DRegion region = new Polygonal2DRegion(world, plotOutlines, cuboidRegion.getMinimumPoint().y(), cuboidRegion.getMaximumPoint().y()); - - // Copy and write finished plot clipboard to schematic file - File finishedSchematicFile = Paths.get(PlotUtils.getDefaultSchematicPath(), - String.valueOf(plot.getCity().getCountry().getServer().getID()), - "finishedSchematics", String.valueOf(plot.getCity().getID()), plot.getID() + ".schem").toFile(); - - if (!finishedSchematicFile.exists()) { - boolean createdDirs = finishedSchematicFile.getParentFile().mkdirs(); - boolean createdFile = finishedSchematicFile.createNewFile(); - if ((!finishedSchematicFile.getParentFile().exists() && !createdDirs) || (!finishedSchematicFile.exists() && !createdFile)) { - return false; - } - } + if (plot.getVersion() < 3) { + PlotSystem.getPlugin().getComponentLogger().error(text("Saving schematics of legacy plots is no longer allowed!")); + return false; + } - Clipboard cb = new BlockArrayClipboard(region); - if (plot.getVersion() >= 3) { - cb.setOrigin(BlockVector3.at(plotCenter.x(), cuboidRegion.getMinimumY(), (double) plotCenter.z())); - } else { - BlockVector3 terraCenter = plot.getMinecraftCoordinates(); - plotCenter = BlockVector3.at( - (double) terraCenter.x() - (double) clipboard.getMinimumPoint().x() + cuboidRegion.getMinimumPoint().x(), - (double) terraCenter.y() - (double) clipboard.getMinimumPoint().y() + cuboidRegion.getMinimumPoint().y(), - (double) terraCenter.z() - (double) clipboard.getMinimumPoint().z() + cuboidRegion.getMinimumPoint().z() - ); - cb.setOrigin(plotCenter); - } + Clipboard clipboard; + ByteArrayInputStream inputStream = new ByteArrayInputStream(plot.getInitialSchematicBytes()); + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { + clipboard = reader.read(); + } + if (clipboard == null) return false; - ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(Objects.requireNonNull(region.getWorld()), region, clipboard, region.getMinimumPoint()); - Operations.complete(forwardExtentCopy); + CuboidRegion cuboidRegion = getPlotAsRegion(plot); + if (cuboidRegion == null) return false; - try (ClipboardWriter writer = BuiltInClipboardFormat.FAST_V2.getWriter(new FileOutputStream(finishedSchematicFile, false))) { - writer.write(clipboard); - } + BlockVector3 plotCenter = plot.getCenter(); - // Upload to FTP server - if (plot.getCity().getCountry().getServer().getFTPConfiguration() != null) { - CompletableFuture.supplyAsync(() -> { - try { - return FTPManager.uploadSchematic(FTPManager.getFTPUrl(plot.getCity().getCountry().getServer(), plot.getCity().getID()), finishedSchematicFile); - } catch (SQLException | URISyntaxException ex) { - Utils.logSqlException(ex); - } - return null; - }); - } + // Get plot outline + List plotOutlines = plot.getOutline(); - // If plot was created in a void world, copy the result to the city world - if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE && plot.getVersion() >= 3) { - AbstractPlotGenerator.pasteSchematic(null, plot.getCompletedSchematic(), new CityPlotWorld(plot), false); - } - return true; - } - } + // Load finished plot region as cuboid region + if (!plot.getWorld().loadWorld()) return false; + com.sk89q.worldedit.world.World world = new BukkitWorld(plot.getWorld().getBukkitWorld()); + Polygonal2DRegion region = new Polygonal2DRegion(world, plotOutlines, cuboidRegion.getMinimumPoint().y(), cuboidRegion.getMaximumPoint().y()); + + + + // Copy and write finished plot clipboard to schematic + try (Clipboard cb = new BlockArrayClipboard(region)) { + cb.setOrigin(BlockVector3.at(plotCenter.x(), cuboidRegion.getMinimumY(), (double) plotCenter.z())); } - return false; + + ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(Objects.requireNonNull(region.getWorld()), region, clipboard, region.getMinimumPoint()); + Operations.complete(forwardExtentCopy); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { + writer.write(clipboard); + } + + // Set Completed Schematic + DataProvider.PLOT.setCompletedSchematic(plot.getID(), outputStream.toByteArray()); + + // If plot was created in a void world, copy the result to the city world + if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE && plot.getVersion() >= 3) { + AbstractPlotGenerator.pasteSchematic(null, outputStream.toByteArray(), new CityPlotWorld(plot), false); + } + return true; } - public static CompletableFuture convertTerraToPlotXZ(AbstractPlot plot, double[] terraCoords) throws IOException, SQLException { + public static CompletableFuture convertTerraToPlotXZ(AbstractPlot plot, double[] terraCoords) throws IOException { // Load plot outlines schematic as clipboard - Clipboard clipboard = FaweAPI.load(plot.getOutlinesSchematic()); - - if (clipboard != null) { - // Calculate min and max points of schematic - CuboidRegion plotRegion = getPlotAsRegion(plot); - - if (plotRegion != null) { - // Convert terra schematic coordinates into relative plot schematic coordinates - double[] schematicCoords = { - terraCoords[0] - clipboard.getMinimumPoint().x(), - terraCoords[1] - clipboard.getMinimumPoint().z() - }; - - // Add additional plot sizes to relative plot schematic coordinates - double[] plotCoords = { - schematicCoords[0] + plotRegion.getMinimumPoint().x(), - schematicCoords[1] + plotRegion.getMinimumPoint().z() - }; - - // Return coordinates if they are in the schematic plot region - ProtectedRegion protectedPlotRegion = plot.getWorld().getProtectedRegion() != null ? plot.getWorld().getProtectedRegion() : plot.getWorld().getProtectedBuildRegion(); - if (protectedPlotRegion.contains(BlockVector3.at((int) plotCoords[0], plot.getWorld().getPlotHeightCentered(), (int) plotCoords[1]))) { - return CompletableFuture.completedFuture(plotCoords); - } - } + Clipboard clipboard; + ByteArrayInputStream inputStream = new ByteArrayInputStream(plot.getInitialSchematicBytes()); + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { + clipboard = reader.read(); + } + if (clipboard == null) return null; + + // Calculate min and max points of schematic + CuboidRegion plotRegion = getPlotAsRegion(plot); + if (plotRegion == null) return null; + + // Convert terra schematic coordinates into relative plot schematic coordinates + double[] schematicCoords = { + terraCoords[0] - clipboard.getMinimumPoint().x(), + terraCoords[1] - clipboard.getMinimumPoint().z() + }; + + // Add additional plot sizes to relative plot schematic coordinates + double[] plotCoords = { + schematicCoords[0] + plotRegion.getMinimumPoint().x(), + schematicCoords[1] + plotRegion.getMinimumPoint().z() + }; + + // Return coordinates if they are in the schematic plot region + ProtectedRegion protectedPlotRegion = plot.getWorld().getProtectedRegion() != null + ? plot.getWorld().getProtectedRegion() + : plot.getWorld().getProtectedBuildRegion(); + if (protectedPlotRegion.contains(BlockVector3.at((int) plotCoords[0], plot.getWorld().getPlotHeightCentered(), (int) plotCoords[1]))) { + return CompletableFuture.completedFuture(plotCoords); } return null; @@ -299,46 +279,25 @@ public static CompletableFuture convertTerraToPlotXZ(AbstractPlot plot public static void checkPlotsForLastActivity() { Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> { - try { - List plots = DataProvider.PLOT.getPlots(Status.unfinished); - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - long millisInDays = config.getLong(ConfigPaths.INACTIVITY_INTERVAL) * 24 * 60 * 60 * 1000; // Remove all plots which have no activity for the last x days + List plots = DataProvider.PLOT.getPlots(Status.unfinished); + FileConfiguration config = PlotSystem.getPlugin().getConfig(); + long inactivityIntervalDays = config.getLong(ConfigPaths.INACTIVITY_INTERVAL); + for (Plot plot : plots) { + LocalDate lastActivity = plot.getLastActivity(); + if (lastActivity == null) continue; + if (lastActivity.plusDays(inactivityIntervalDays).isAfter(LocalDate.now())) continue; - for (Plot plot : plots) { - if (plot.getLastActivity() != null && plot.getLastActivity().getTime() < (new Date().getTime() - millisInDays)) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - if (Actions.abandonPlot(plot)) { - PlotSystem.getPlugin().getComponentLogger().info(text("Abandoned plot #" + plot.getID() + " due to inactivity!")); - } else { - PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while abandoning plot #" + plot.getID() + " due to inactivity!")); - } - }); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + if (Actions.abandonPlot(plot)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Abandoned plot #" + plot.getID() + " due to inactivity!")); + } else { + PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while abandoning plot #" + plot.getID() + " due to inactivity!")); } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); + }); } }, 0L, 20 * 60 * 60L); // Check every hour } - public static void syncPlotSchematicFiles() { - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if (config.getBoolean(ConfigPaths.SYNC_FTP_FILES_ENABLE)) { - long interval = config.getLong(ConfigPaths.SYNC_FTP_FILES_INTERVAL); - - Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> DataProvider.CITY_PROJECT.getCityProjects(false).forEach(c -> { - try { - if (c.getCountry().getServer().getFTPConfiguration() != null) { - List plots = DataProvider.PLOT.getPlots(c, Status.unclaimed); - plots.forEach(Plot::getOutlinesSchematic); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - }), 0L, 20 * interval); - } - } - public static final class Actions { private Actions() {} public static void submitPlot(Plot plot) throws SQLException { @@ -396,7 +355,7 @@ public static boolean abandonPlot(AbstractPlot plot) { if (regionManager.hasRegion(world.getRegionName())) regionManager.removeRegion(world.getRegionName()); if (regionManager.hasRegion(world.getRegionName() + "-1")) regionManager.removeRegion(world.getRegionName() + "-1"); - AbstractPlotGenerator.pasteSchematic(null, plot.getOutlinesSchematic(), world, true); + AbstractPlotGenerator.pasteSchematic(null, getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true); } else PlotSystem.getPlugin().getComponentLogger().warn(text("Region Manager is null!")); playersToTeleport.forEach(p -> p.teleport(Utils.getSpawnLocation())); @@ -414,6 +373,7 @@ public static boolean abandonPlot(AbstractPlot plot) { if (plot.getPlotType() != PlotType.TUTORIAL) { Plot dPlot = (Plot) plot; if (dPlot.isReviewed()) { + // TODO: extract to data provider DatabaseConnection.createStatement("UPDATE plotsystem_plots SET review_id = DEFAULT(review_id) WHERE id = ?") .setValue(plot.getID()).executeUpdate(); @@ -448,32 +408,7 @@ public static boolean abandonPlot(AbstractPlot plot) { public static boolean deletePlot(Plot plot) { if (abandonPlot(plot)) { - try { - CompletableFuture.runAsync(() -> { - try { - Server plotServer = plot.getCity().getCountry().getServer(); - - String schemFileEnding = ".schematic"; - Files.deleteIfExists(Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(plotServer.getID()), "finishedSchematics", String.valueOf(plot.getCity().getID()), plot.getID() + schemFileEnding)); - Files.deleteIfExists(Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(plotServer.getID()), String.valueOf(plot.getCity().getID()), plot.getID() + schemFileEnding)); - Files.deleteIfExists(Paths.get(PlotUtils.getDefaultSchematicPath(), String.valueOf(plotServer.getID()), String.valueOf(plot.getCity().getID()), plot.getID() + "-env.schematic")); - - if (plotServer.getFTPConfiguration() != null) { - FTPManager.deleteSchematic(FTPManager.getFTPUrl(plotServer, plot.getCity().getID()), plot.getID() + schemFileEnding); - FTPManager.deleteSchematic(FTPManager.getFTPUrl(plotServer, plot.getCity().getID()).replaceFirst("finishedSchematics/", ""), plot.getID() + schemFileEnding); - FTPManager.deleteSchematic(FTPManager.getFTPUrl(plotServer, plot.getCity().getID()).replaceFirst("finishedSchematics/", ""), plot.getID() + "-env.schematic"); - } - - DatabaseConnection.createStatement("DELETE FROM plotsystem_plots WHERE id = ?") - .setValue(plot.getID()).executeUpdate(); - } catch (IOException | SQLException | URISyntaxException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text(ex.getMessage()), ex); - throw new CompletionException(ex); - } - }); - } catch (CompletionException ex) { - return false; - } + CompletableFuture.runAsync(() -> DataProvider.PLOT.deletePlot(plot.getID())); return true; } PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to delete plot with the ID " + plot.getID() + "!")); @@ -576,7 +511,7 @@ public static void showOutlines() { } } } - } catch (SQLException | IOException ex) { + } catch (IOException ex) { Utils.logSqlException(ex); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index badc7b24..da044d1f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -44,7 +44,7 @@ import static net.kyori.adventure.text.Component.text; public class CityPlotWorld extends PlotWorld { - public CityPlotWorld(@NotNull Plot plot) throws SQLException { + public CityPlotWorld(@NotNull Plot plot) { super("C-" + plot.getCity().getID(), plot); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index e97b4a23..a5387ae3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -51,7 +51,7 @@ public class OnePlotWorld extends PlotWorld { private final Builder plotOwner; - public OnePlotWorld(@NotNull AbstractPlot plot) throws SQLException { + public OnePlotWorld(@NotNull AbstractPlot plot) { super((plot instanceof TutorialPlot ? "T-" : "P-") + plot.getID(), plot); this.plotOwner = plot.getPlotOwner(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index b62db7ac..e08a5b1c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core.system.plot.world; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; @@ -246,7 +247,7 @@ public static T getPlotWorldByName(String worldName) { if (isOnePlotWorld(worldName) || isCityPlotWorld(worldName)) { int id = Integer.parseInt(worldName.substring(2)); try { - return worldName.toLowerCase().startsWith("t-") ? new TutorialPlot(id).getWorld() : new Plot(id).getWorld(); + return worldName.toLowerCase().startsWith("t-") ? new TutorialPlot(id).getWorld() : DataProvider.PLOT.getPlotById(id).getWorld(); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java b/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java deleted file mode 100644 index f1732710..00000000 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/FTPManager.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.utils.io; - -import com.alpsbte.plotsystem.PlotSystem; -import org.apache.commons.vfs2.*; -import org.apache.commons.vfs2.impl.StandardFileSystemManager; -import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder; -import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder; - -import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.sql.SQLException; -import java.util.concurrent.CompletableFuture; - -import static net.kyori.adventure.text.Component.text; - -public class FTPManager { - - private static FileSystemOptions fileOptions; - - private final static String DEFAULT_SCHEMATIC_PATH_LINUX = "/var/lib/Plot-System/schematics"; - - static { - try { - fileOptions = new FileSystemOptions(); - SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fileOptions, "no"); - SftpFileSystemConfigBuilder.getInstance().setPreferredAuthentications(fileOptions, "password"); - SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileOptions, false); - - FtpFileSystemConfigBuilder.getInstance().setPassiveMode(fileOptions, true); - FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(fileOptions, false); - } catch (FileSystemException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Exception found with FileSystemManager!"), ex); - } - } - - public static String getFTPUrl(Server server, int cityID) throws SQLException, URISyntaxException { - String schematicsPath = server.getFTPConfiguration().getSchematicPath(); - return new URI(server.getFTPConfiguration().isSFTP() ? "sftp" : "ftp", - server.getFTPConfiguration().getUsername() + ":" + server.getFTPConfiguration().getPassword(), - server.getFTPConfiguration().getAddress(), - server.getFTPConfiguration().getPort(), - String.format("/%s/%s/%s/", schematicsPath == null ? DEFAULT_SCHEMATIC_PATH_LINUX : schematicsPath, "finishedSchematics", cityID), - null, - null).toString(); - } - - public static CompletableFuture uploadSchematic(String ftpURL, File schematic) { - try (StandardFileSystemManager fileManager = new StandardFileSystemManager()) { - fileManager.init(); - - // Get local schematic - FileObject localSchematic = fileManager.toFileObject(schematic); - - // Get remote path and create missing directories - FileObject remote = fileManager.resolveFile(ftpURL, fileOptions); - remote.createFolder(); - - // Create remote schematic and write to it - FileObject remoteSchematic = remote.resolveFile(schematic.getName()); - remoteSchematic.copyFrom(localSchematic, Selectors.SELECT_SELF); - - localSchematic.close(); - remoteSchematic.close(); - } catch (FileSystemException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Exception found with FileSystemManager!"), ex); - } - return CompletableFuture.completedFuture(null); - } - - public static boolean downloadSchematic(String ftpURL, File schematic) { - boolean fileExists = false; - try (StandardFileSystemManager fileManager = new StandardFileSystemManager()) { - fileManager.init(); - - // Get local schematic - FileObject localSchematic = fileManager.toFileObject(schematic); - - // Get remote path - FileObject remote = fileManager.resolveFile(ftpURL.replaceFirst("finishedSchematics/", ""), fileOptions); - - // Get remote schematic and write it to local file - FileObject remoteSchematic = remote.resolveFile(schematic.getName()); - if (remoteSchematic.exists()) { - localSchematic.copyFrom(remoteSchematic, Selectors.SELECT_SELF); - fileExists = true; - } - - localSchematic.close(); - remoteSchematic.close(); - } catch (FileSystemException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Exception found with FileSystemManager!"), ex); - } - return fileExists; - } - - public static void deleteSchematic(String ftpURL, String schematicName) throws FileSystemException { - try (StandardFileSystemManager fileManager = new StandardFileSystemManager()) { - fileManager.init(); - FileObject remote, remoteSchematic; - - remote = fileManager.resolveFile(ftpURL, fileOptions); - remoteSchematic = remote.resolveFile(schematicName); - if (remoteSchematic.exists()) { - remoteSchematic.delete(); - if (remote.getChildren().length == 0) { - remote.delete(); - } - } - } - } -} \ No newline at end of file From 9a0020890b0bb0fd4c6c5920996eacbd53aa4a5f Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 19:14:13 +0100 Subject: [PATCH 022/175] fix issues from merging --- .../commands/plot/CMD_Plot_Abandon.java | 14 ++++++---- .../commands/plot/CMD_Plot_Submit.java | 6 ++--- .../commands/plot/CMD_Plot_UndoSubmit.java | 6 ++--- .../core/menus/companion/CityProjectMenu.java | 16 +++++------ .../core/menus/companion/CompanionMenu.java | 1 - .../core/menus/companion/ContinentMenu.java | 4 +-- .../plotsystem/core/system/CityProject.java | 5 +--- .../plotsystem/core/system/plot/Plot.java | 27 ++++++------------- .../plot/generator/DefaultPlotGenerator.java | 2 +- .../com/alpsbte/plotsystem/utils/Utils.java | 5 ++-- 10 files changed, 36 insertions(+), 50 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java index 77a302c2..8c302eb1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java @@ -39,7 +39,6 @@ import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.jetbrains.annotations.Nullable; import java.util.concurrent.CompletableFuture; @@ -53,10 +52,15 @@ public CMD_Plot_Abandon(BaseCommand baseCommand) { public void onCommand(CommandSender sender, String[] args) { CompletableFuture.runAsync(() -> { Plot plot; + if (!(sender instanceof Player player)) { + sendInfo(sender); + return; + } + if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - } else if (getPlayer(sender) != null && PlotUtils.isPlotWorld(getPlayer(sender).getWorld())) { - AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(getPlayer(sender).getUniqueId()), Status.unfinished); + } else if (PlotUtils.isPlotWorld(player.getWorld())) { + AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); if (!(p instanceof Plot)) { sendInfo(sender); return; @@ -75,7 +79,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_ABANDON_UNFINISHED_PLOTS))); return; } - if (!sender.hasPermission("plotsystem.review") && !Utils.isOwnerOrReviewer(sender, player, plot)) { + if (!Utils.isOwnerOrReviewer(sender, player, plot)) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); return; } @@ -83,7 +87,7 @@ public void onCommand(CommandSender sender, String[] args) { Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (PlotUtils.Actions.abandonPlot(plot)) { sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.ABANDONED_PLOT, plot.getID() + ""))); - if (getPlayer(sender) != null) getPlayer(sender).playSound(getPlayer(sender).getLocation(), Utils.SoundUtils.ABANDON_PLOT_SOUND, 1, 1); + player.playSound(player.getLocation(), Utils.SoundUtils.ABANDON_PLOT_SOUND, 1, 1); } }); }); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java index df517357..d6dd00fa 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java @@ -40,10 +40,10 @@ import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.jetbrains.annotations.Nullable; import java.sql.SQLException; import java.util.List; +import java.util.Objects; import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -82,7 +82,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); return; } - if (!sender.hasPermission("plotsystem.review") && !Utils.isOwnerOrReviewer(sender, player, plot)) { + if (!Utils.isOwnerOrReviewer(sender, player, plot)) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); return; } @@ -116,7 +116,7 @@ public void onCommand(CommandSender sender, String[] args) { langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), sb.toString()); } - player.playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); + Objects.requireNonNull(player).playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); }); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java index 94dd0c5e..5a3f4e89 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java @@ -40,7 +40,6 @@ import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import org.jetbrains.annotations.Nullable; import java.sql.SQLException; import java.util.concurrent.CompletableFuture; @@ -55,8 +54,7 @@ public CMD_Plot_UndoSubmit(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - Player player = getPlayer(sender); - if (getPlayer(sender) == null) { + if (!(sender instanceof Player player)) { Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); return; } @@ -65,7 +63,7 @@ public void onCommand(CommandSender sender, String[] args) { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - } else if (player != null && PlotUtils.isPlotWorld(player.getWorld())) { + } else if (PlotUtils.isPlotWorld(player.getWorld())) { AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); if (!(p instanceof Plot)) { sendInfo(sender); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 3c02f523..4fe69c6e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -53,8 +53,6 @@ import java.util.Map; import java.util.concurrent.ExecutionException; -import static net.kyori.adventure.text.Component.text; - public class CityProjectMenu extends AbstractPaginatedMenu { final Country country; List projects; @@ -137,13 +135,13 @@ public static boolean generateRandomPlot(Player player, @NotNull List getValidCityProjects(PlotDifficulty selectedPlotDifficulty, Player player, Country country) { - return CityProject.getCityProjects(country, true).stream().filter(test -> { + return DataProvider.CITY_PROJECT.getCityProjects(country, true).stream().filter(test -> { if (test instanceof CityProject project) { var pd = selectedPlotDifficulty; try { - if (pd == null) pd = Plot.getPlotDifficultyForBuilder(project.getID(), Builder.byUUID(player.getUniqueId())).get(); + if (pd == null) pd = Plot.getPlotDifficultyForBuilder(project, Builder.byUUID(player.getUniqueId())).get(); if (pd == null) pd = PlotDifficulty.EASY; - return project.isVisible() && project.getOpenPlotsForPlayer(project.getID(), pd) > 0; + + return project.isVisible() && !DataProvider.PLOT.getPlots(project, pd, Status.unclaimed).isEmpty(); } catch (SQLException | ExecutionException | InterruptedException e) { sqlError(player, e); } @@ -213,7 +212,6 @@ protected void setPaginatedItemClickEventsAsync(List source) { clickPlayer.closeInventory(); Builder builder = Builder.byUUID(clickPlayer.getUniqueId()); - String cityID = city.getID(); try { PlotDifficulty plotDifficultyForCity = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(city, builder).get(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 37cab4c7..16458e42 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -57,7 +57,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.Map; import java.util.Optional; import java.util.function.Consumer; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java index 9ab39aa1..4ff59fd1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java @@ -25,8 +25,8 @@ package com.alpsbte.plotsystem.core.menus.companion; import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; -import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.io.LangPaths; @@ -79,7 +79,7 @@ protected void setItemClickEventsAsync() { List layout2 = new java.util.ArrayList<>(layout.values().stream().toList()); while (!layout2.isEmpty()) { var rndContinent = layout2.get(Utils.getRandom().nextInt(layout2.size())); - var successful = CountryMenu.generateRandomPlot(clickPlayer, Country.getCountries(rndContinent), null); + var successful = CountryMenu.generateRandomPlot(clickPlayer, DataProvider.COUNTRY.getCountriesByContinent(rndContinent), null); if (successful) { return; } else { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index e73d0209..a608585a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -26,7 +26,6 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; @@ -35,14 +34,12 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; +import net.kyori.adventure.text.Component; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; -import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.List; import java.util.concurrent.ExecutionException; import static net.kyori.adventure.text.Component.text; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index e92c3f86..78a0d983 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -32,26 +32,18 @@ import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; -import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; -import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Slot; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.alpsbte.plotsystem.utils.io.FTPManager; import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.File; import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Paths; -import java.io.*; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; @@ -139,20 +131,17 @@ public boolean setPlotMembers(@NotNull List plotMembers) { @SuppressWarnings("unchecked") @Override public T getWorld() { - try { - if (getVersion() <= 2 || getPlotType().hasOnePlotPerWorld()) { - if (onePlotWorld == null) onePlotWorld = new OnePlotWorld(this); - return (T) onePlotWorld; - } else { - if (cityPlotWorld == null) cityPlotWorld = new CityPlotWorld(this); - return (T) cityPlotWorld; - } - } catch (SQLException ex) {Utils.logSqlException(ex);} - return null; + if (getVersion() <= 2 || getPlotType().hasOnePlotPerWorld()) { + if (onePlotWorld == null) onePlotWorld = new OnePlotWorld(this); + return (T) onePlotWorld; + } else { + if (cityPlotWorld == null) cityPlotWorld = new CityPlotWorld(this); + return (T) cityPlotWorld; + } } @Override - public List getOutline() throws IOException { + public List getOutline() { if (outline != null) return this.outline; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 84cf601c..4de1a057 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -54,7 +54,7 @@ public class DefaultPlotGenerator extends AbstractPlotGenerator { public static final Map playerPlotGenerationHistory = new HashMap<>(); public DefaultPlotGenerator(CityProject city, PlotDifficulty plotDifficulty, Builder builder) throws SQLException { - this(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).get(Utils.getRandom().nextInt(Plot.getPlots(cityID, plotDifficulty, Status.unclaimed).size())), builder); + this(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).get(Utils.getRandom().nextInt(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).size())), builder); } public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) throws SQLException { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 4e6c325b..eb8226f0 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -46,6 +46,7 @@ import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; @@ -55,7 +56,6 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.sql.SQLException; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; @@ -243,7 +243,8 @@ public static Random getRandom() { return random; } - public static boolean isOwnerOrReviewer(CommandSender sender, @Nullable Player player, Plot plot) throws SQLException { + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public static boolean isOwnerOrReviewer(CommandSender sender, @Nullable Player player, Plot plot) { boolean hasPermission = sender.hasPermission("plotsystem.review") || (player != null && Objects.requireNonNull(plot).getPlotOwner().getUUID().equals(player.getUniqueId())); if (!hasPermission) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); From f21e8c6a01c51fcfb3e99e366d85a8b32bcc85a1 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 19:59:13 +0100 Subject: [PATCH 023/175] finish country model and CMD_Setup_Country.java --- .../admin/setup/CMD_Setup_Country.java | 84 +++++++++---------- .../database/providers/CountryProvider.java | 16 ++++ .../plotsystem/core/system/Country.java | 33 +++----- 3 files changed, 69 insertions(+), 64 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 2ee40ea8..efb4006f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -52,7 +52,7 @@ private void register() { registerSubCommand(new CMD_Setup_Country_List(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_Country_Add(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_Country_Remove(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_Country_SetHead(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_Country_SetMaterial(getBaseCommand(), this)); } @Override @@ -132,25 +132,26 @@ public CMD_Setup_Country_Add(BaseCommand baseCommand, SubCommand subCommand) { public void onCommand(CommandSender sender, String[] args) { if (args.length <= 3 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - if (args[2].length() > 45) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country name cannot be longer than 45 characters!")); + String code = args[1]; + if (code.length() > 2) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country code cannot be longer than 2 characters!")); return; } Continent continent; try { - continent = Continent.valueOf(args[3].toUpperCase()); + continent = Continent.valueOf(args[2].toUpperCase()); } catch (IllegalArgumentException e) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Unknown continent! " + Arrays.toString(Continent.values()))); return; } - try { - Country.addCountry(Integer.parseInt(args[1]), args[2], continent); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + + String material = args[3]; + String customModelData = args.length > 4 ? args[4] : null; + + boolean successful = DataProvider.COUNTRY.addCountry(code, continent, material, customModelData); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -165,7 +166,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"Server-ID", "Name", "Continent"}; + return new String[]{"Code", "Continent", "Material", "CustomModelData?"}; } @Override @@ -181,21 +182,18 @@ public CMD_Setup_Country_Remove(BaseCommand baseCommand, SubCommand subCommand) @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 1) {sendInfo(sender); return;} + String code = args[1]; // Check if country exists - try { - if (DataProvider.COUNTRY.getCountryByCode(args[1]) == null) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with ID " + args[1] + "!")); - sendInfo(sender); - return; - } - Country.removeCountry(Integer.parseInt(args[1])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (DataProvider.COUNTRY.getCountryByCode(code) == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with code " + code + "!")); + sendInfo(sender); + return; } + boolean successful = DataProvider.COUNTRY.removeCountry(code); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -210,7 +208,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"Country-ID"}; + return new String[]{"Country-Code"}; } @Override @@ -219,36 +217,38 @@ public String getPermission() { } } - public static class CMD_Setup_Country_SetHead extends SubCommand { - public CMD_Setup_Country_SetHead(BaseCommand baseCommand, SubCommand subCommand) { + public static class CMD_Setup_Country_SetMaterial extends SubCommand { + public CMD_Setup_Country_SetMaterial(BaseCommand baseCommand, SubCommand subCommand) { super(baseCommand, subCommand); } @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null || AlpsUtils.tryParseInt(args[2]) == null) { + if (args.length <= 2) { sendInfo(sender); return; } + String code = args[1]; + String material = args[2]; + String customModelData = args.length > 3 ? args[3] : null; + // Check if country exists - try { - if (DataProvider.COUNTRY.getCountryByCode(args[1]) == null) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with name " + args[1] + "!")); - sendInfo(sender); - return; - } - Country.setHeadID(Integer.parseInt(args[1]), Integer.parseInt(args[2])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set head id of country " + args[1] + " to " + args[2] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + Country country = DataProvider.COUNTRY.getCountryByCode(code); + if (country == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with name " + args[1] + "!")); + sendInfo(sender); + return; } + + boolean successful = country.setMaterialAndModelData(material, customModelData); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully updated country with code " + country + "! Material: " + material + " CustomModelData: " + (customModelData == null ? "NULL" : customModelData))); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override public String[] getNames() { - return new String[]{"sethead"}; + return new String[]{"setmaterial"}; } @Override @@ -258,12 +258,12 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"Country-ID", "Head-ID"}; + return new String[]{"Country-Code", "Material", "CustomModelData?"}; } @Override public String getPermission() { - return "plotsystem.admin.pss.country.sethead"; + return "plotsystem.admin.pss.country.setmaterial"; } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index 4a25259c..dba53dcb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -2,6 +2,7 @@ import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.enums.Continent; +import org.jetbrains.annotations.Nullable; import java.util.List; @@ -22,4 +23,19 @@ public Country getCountryByCode(String code) { return null; } + + public boolean setMaterialAndCustomModelData(String material, @Nullable String customModelData) { + // TODO: implement + return false; + } + + public boolean addCountry(String code, Continent continent, String material, @Nullable String customModelData) { + // TODO: implement + return false; + } + + public boolean removeCountry(String code) { + // TODO: implement + return false; + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index c816c561..13327696 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.utils.enums.Continent; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; import java.sql.SQLException; import java.util.List; @@ -41,7 +42,7 @@ public class Country { private String material; private String customModelData; - private Continent continent; + private final Continent continent; public Country(String code, Continent continent, String material, String customModelData) { this.code = code; @@ -67,28 +68,16 @@ public String getName(Player player) { return code; } - public ItemStack getCountryItem() { - return Utils.getConfiguredItem(material, customModelData); - } - - @Deprecated - public static void addCountry(int serverID, String name, Continent continent) throws SQLException { - DatabaseConnection.createStatement("INSERT INTO plotsystem_countries (id, name, server_id, continent) VALUES (?, ?, ?, ?)") - .setValue(DatabaseConnection.getTableID("plotsystem_countries")) - .setValue(name) - .setValue(serverID).setValue(continent.databaseEnum).executeUpdate(); + public boolean setMaterialAndModelData(String material, @Nullable String customModelData) { + if (DataProvider.COUNTRY.setMaterialAndCustomModelData(material, customModelData)) { + this.material = material; + this.customModelData = customModelData; + return true; + } + return false; } - @Deprecated() - public static void removeCountry(int countryID) throws SQLException { - DatabaseConnection.createStatement("DELETE FROM plotsystem_countries WHERE id = ?") - .setValue(countryID).executeUpdate(); - } - - @Deprecated - public static void setHeadID(int countryID, int headID) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_countries SET head_id = ? WHERE id = ?") - .setValue(headID) - .setValue(countryID).executeUpdate(); + public ItemStack getCountryItem() { + return Utils.getConfiguredItem(material, customModelData); } } \ No newline at end of file From f7092a526ae69abab061fbda7e32d8a97ca28c58 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 20:58:18 +0100 Subject: [PATCH 024/175] finish difficulty model and CMD_Setup_Difficulty.java --- .../commands/admin/setup/CMD_Setup.java | 13 - .../admin/setup/CMD_Setup_Country.java | 2 - .../admin/setup/CMD_Setup_Difficulty.java | 48 ++-- .../commands/admin/setup/CMD_Setup_FTP.java | 262 ------------------ .../admin/setup/CMD_Setup_Server.java | 2 +- .../providers/DifficultyProvider.java | 28 +- .../plotsystem/core/system/Country.java | 2 - .../plotsystem/core/system/Difficulty.java | 67 ++--- 8 files changed, 69 insertions(+), 355 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_FTP.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java index 7d49fce1..262f7d2d 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java @@ -33,7 +33,6 @@ public class CMD_Setup extends BaseCommand { public CMD_Setup() { registerSubCommand(new CMD_Setup_BuildTeam(this)); - registerSubCommand(new CMD_Setup_FTP(this)); registerSubCommand(new CMD_Setup_Server(this)); registerSubCommand(new CMD_Setup_Country(this)); registerSubCommand(new CMD_Setup_City(this)); @@ -68,16 +67,4 @@ public String[] getParameter() { public String getPermission() { return null; } - - public static String appendArgs(String[] args, int startIndex) { - StringBuilder name = new StringBuilder(); - for (int i = startIndex; i < args.length; i++) { - name.append(args[i]); - // Add space between words - if (i != args.length - 1) { - name.append(" "); - } - } - return name.toString(); - } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index efb4006f..696208f5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -34,7 +33,6 @@ import com.alpsbte.plotsystem.utils.enums.Continent; import org.bukkit.command.CommandSender; -import java.sql.SQLException; import java.util.Arrays; import java.util.List; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java index b790aa70..512b7d6c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java @@ -25,17 +25,17 @@ package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Difficulty; import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.command.CommandSender; -import java.sql.SQLException; import java.util.List; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.*; public class CMD_Setup_Difficulty extends SubCommand { @@ -83,13 +83,15 @@ public CMD_Setup_Difficulty_List(BaseCommand baseCommand, SubCommand subCommand) @Override public void onCommand(CommandSender sender, String[] args) { - List difficulties = Difficulty.getDifficulties(); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + difficulties.size() + " Difficulties registered in the database:")); - sender.sendMessage("§8--------------------------"); + List difficulties = DataProvider.DIFFICULTY.getDifficulties(); + sender.sendMessage(text("--------------------------", DARK_GRAY)); for (Difficulty d : difficulties) { - sender.sendMessage(" §6> §b" + d.getID() + " (" + d.getDifficulty().name() + ") §f- Multiplier: " + d.getMultiplier() + " - Score Requirement: " + d.getScoreRequirement()); + sender.sendMessage(text(" » ", DARK_GRAY) + .append(text(d.getID(), AQUA)) + .append(text("Multiplier: " + d.getMultiplier(), WHITE)) + .append(text(" - Score Requirement: " + d.getScoreRequirement(), WHITE))); } - sender.sendMessage("§8--------------------------"); + sender.sendMessage(text("--------------------------", DARK_GRAY)); } @Override @@ -120,20 +122,18 @@ public CMD_Setup_Difficulty_SetMultiplier(BaseCommand baseCommand, SubCommand su @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null || AlpsUtils.tryParseDouble(args[2]) == null) { + if (args.length <= 2 || AlpsUtils.tryParseDouble(args[2]) == null) { sendInfo(sender); return; } // Check if difficulty exists - try { - if (Difficulty.getDifficulties().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; - Difficulty.setMultiplier(Integer.parseInt(args[1]), Double.parseDouble(args[2])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set multiplier of Difficulty with ID " + args[1] + " to " + args[2] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + Difficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(args[1]); + if (difficulty == null) return; + + boolean successful = difficulty.setMultiplier(Double.parseDouble(args[2])); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set multiplier of Difficulty with ID " + args[1] + " to " + args[2] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override @@ -164,20 +164,18 @@ public CMD_Setup_Difficulty_SetRequirement(BaseCommand baseCommand, SubCommand s @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null || AlpsUtils.tryParseInt(args[2]) == null) { + if (args.length <= 2 || AlpsUtils.tryParseInt(args[2]) == null) { sendInfo(sender); return; } // Check if difficulty exists - try { - if (Difficulty.getDifficulties().stream().noneMatch(c -> c.getID() == Integer.parseInt(args[1]))) return; - Difficulty.setScoreRequirement(Integer.parseInt(args[1]), Integer.parseInt(args[2])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set score requirement of Difficulty with ID " + args[1] + " to " + args[2] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + Difficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(args[1]); + if (difficulty == null) return; + + boolean successful = difficulty.setScoreRequirement(Integer.parseInt(args[2])); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set score requirement of Difficulty with ID " + args[1] + " to " + args[2] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_FTP.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_FTP.java deleted file mode 100644 index 8dfee205..00000000 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_FTP.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.commands.admin.setup; - -import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.commands.BaseCommand; -import com.alpsbte.plotsystem.commands.SubCommand; -import com.alpsbte.plotsystem.core.system.FTPConfiguration; -import com.alpsbte.plotsystem.utils.Utils; -import org.bukkit.command.CommandSender; - -import java.sql.SQLException; -import java.util.List; - -import static net.kyori.adventure.text.Component.text; - -public class CMD_Setup_FTP extends SubCommand { - - public CMD_Setup_FTP(BaseCommand baseCommand) { - super(baseCommand); - register(); - } - - private void register() { - registerSubCommand(new CMD_Setup_FTP_List(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_FTP_Add(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_FTP_Remove(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_FTP_SetPath(getBaseCommand(), this)); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - sendInfo(sender); - } - - @Override - public String[] getNames() { - return new String[]{"ftp"}; - } - - @Override - public String getDescription() { - return "Configure SFTP/FTP configurations"; - } - - @Override - public String[] getParameter() { - return new String[0]; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.ftp"; - } - - - public static class CMD_Setup_FTP_List extends SubCommand { - public CMD_Setup_FTP_List(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - List ftpConfigs = FTPConfiguration.getFTPConfigurations(); - if (ftpConfigs.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no FTP Configurations registered in the database!")); - return; - } - - sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + ftpConfigs.size() + " FTP-Configurations registered in the database:")); - sender.sendMessage("§8--------------------------"); - for (FTPConfiguration ftp : ftpConfigs) { - sender.sendMessage(" §6> §b" + ftp.getID() + " §f- Address: " + ftp.getAddress() + " - Port: " + ftp.getPort() + " - SFTP: " + (ftp.isSFTP() ? "True" : "False") + " - Username: " + getCensorString(ftp.getUsername().length()) + " - Password: " + getCensorString(ftp.getPassword().length()) + " - Path: " + ftp.getSchematicPath()); - } - sender.sendMessage("§8--------------------------"); - } - - @Override - public String[] getNames() { - return new String[]{"list"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[0]; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.ftp.list"; - } - - public String getCensorString(int length) { - StringBuilder output = new StringBuilder(); - for (int i = 0; i < length; i++) { - output.append("*"); - } - return output.toString(); - } - } - - public static class CMD_Setup_FTP_Add extends SubCommand { - public CMD_Setup_FTP_Add(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 5 || AlpsUtils.tryParseInt(args[2]) == null) {sendInfo(sender); return;} - if (!args[3].equalsIgnoreCase("true") && !args[3].equalsIgnoreCase("false")) return; - if (args[1].toLowerCase().startsWith("sftp:") || args[1].toLowerCase().startsWith("ftp:")) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Please remove the protocol URL from the host address!")); - return; - } - try { - FTPConfiguration.addFTPConfiguration(args[1], Integer.parseInt(args[2]), args[3].equalsIgnoreCase("true"), args[4], args[5]); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added FTP-Configuration!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - } - - @Override - public String[] getNames() { - return new String[]{"add"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"Address", "Port", "isSFTP (True/False)", "Username", "Password"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.ftp.add"; - } - } - - public static class CMD_Setup_FTP_Remove extends SubCommand { - public CMD_Setup_FTP_Remove(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - - // Check if ftp config exists - try { - if (FTPConfiguration.getFTPConfigurations().stream().noneMatch(f -> f.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any FTP-Configurations with ID " + args[1] + "!")); - sendInfo(sender); - return; - } - FTPConfiguration.removeFTPConfiguration(Integer.parseInt(args[1])); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed FTP-Configuration!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - } - - @Override - public String[] getNames() { - return new String[]{"remove"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"FTP-ID"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.ftp.remove"; - } - } - - public static class CMD_Setup_FTP_SetPath extends SubCommand { - public CMD_Setup_FTP_SetPath(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - - // Check if ftp config exists - try { - if (FTPConfiguration.getFTPConfigurations().stream().noneMatch(f -> f.getID() == Integer.parseInt(args[1]))) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any FTP-Configurations with ID " + args[1] + "!")); - sendInfo(sender); - return; - } - FTPConfiguration.setSchematicPath(Integer.parseInt(args[1]), args[2]); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set path of FTP-Configuration " + args[1] + " to " + args[2] + "!")); - } catch (SQLException ex) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - } - - @Override - public String[] getNames() { - return new String[]{"setpath"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"FTP-ID", "Path"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.ftp.setpath"; - } - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index 9c6a1688..27f86cc9 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -89,7 +89,7 @@ public void onCommand(CommandSender sender, String[] args) { } sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + servers.size() + " Servers registered in the database:")); - sender.sendMessage(text("--------------------------", DARK_GRAY)); + for (String server : servers) { sender.sendMessage(text(" » ", DARK_GRAY).append(text(server, AQUA))); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index 5a4b4df6..e4cfdf03 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -1,20 +1,42 @@ package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.Difficulty; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import java.util.List; + public class DifficultyProvider { - public double getMultiplier(PlotDifficulty difficulty) { + public List getDifficulties() { + // TODO: implement + return List.of(); + } + + public Difficulty getDifficultyById(String id) { // TODO: implement + return null; + } + + public double getMultiplier(PlotDifficulty difficulty) { + // TODO: implement (get from cached list) return 0; } - public int getScoreRequirement(PlotDifficulty difficulty) { + public boolean setMultiplier(String id, double multiplier) { // TODO: implement + return false; + } + + public int getScoreRequirement(PlotDifficulty difficulty) { + // TODO: implement (get from cached list) return 0; } + public boolean setScoreRequirement(String id, int scoreRequirement) { + // TODO: implement + return false; + } + public boolean builderMeetsRequirements(Builder builder, PlotDifficulty plotDifficulty) { int playerScore = builder.getScore(); int scoreRequirement = getScoreRequirement(plotDifficulty); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index 13327696..49301528 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -25,14 +25,12 @@ package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; -import java.sql.SQLException; import java.util.List; public class Country { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java b/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java index 31cb81dd..714a6938 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java @@ -24,41 +24,24 @@ package com.alpsbte.plotsystem.core.system; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import static net.kyori.adventure.text.Component.text; - public class Difficulty { - private final int ID; + private final String ID; + private final PlotDifficulty difficulty; - private PlotDifficulty difficulty; private double multiplier; private int scoreRequirement; - public Difficulty(int ID) throws SQLException { - this.ID = ID; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT name, multiplier, score_requirment FROM plotsystem_difficulties WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - this.difficulty = PlotDifficulty.valueOf(rs.getString(1)); - this.multiplier = rs.getDouble(2); - this.scoreRequirement = rs.getInt(3); - } - - DatabaseConnection.closeResultSet(rs); - } + public Difficulty(PlotDifficulty difficulty, String id, double multiplier, int scoreRequirement) { + this.difficulty = difficulty; + this.ID = id; + this.multiplier = multiplier; + this.scoreRequirement = scoreRequirement; } - public int getID() { + public String getID() { return ID; } @@ -74,29 +57,19 @@ public int getScoreRequirement() { return scoreRequirement; } - public static List getDifficulties() { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_difficulties").executeQuery()) { - List difficulties = new ArrayList<>(); - while (rs.next()) { - difficulties.add(new Difficulty(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - - return difficulties; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + public boolean setMultiplier(double multiplier) { + if (DataProvider.DIFFICULTY.setMultiplier(ID, multiplier)) { + this.multiplier = multiplier; + return true; } - return new ArrayList<>(); + return false; } - public static void setMultiplier(int difficultyID, double multiplier) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_difficulties SET multiplier = ? WHERE id = ?") - .setValue(multiplier).setValue(difficultyID).executeUpdate(); - } - - public static void setScoreRequirement(int difficultyID, int scoreRequirement) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_difficulties SET score_requirment = ? WHERE id = ?") - .setValue(scoreRequirement).setValue(difficultyID).executeUpdate(); + public boolean setScoreRequirement(int scoreRequirement) { + if (DataProvider.DIFFICULTY.setScoreRequirement(ID, scoreRequirement)) { + this.scoreRequirement = scoreRequirement; + return true; + } + return false; } } From 0e85e9840afbac6873a354e7d4dc9fc56474ad6b Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 21:32:50 +0100 Subject: [PATCH 025/175] delete Reviewer class --- .../commands/plot/CMD_Plot_Feedback.java | 4 ++-- .../commands/plot/CMD_Plot_Teleport.java | 8 +++++--- .../alpsbte/plotsystem/core/EventListener.java | 14 ++++++-------- .../database/providers/BuildTeamProvider.java | 5 +++++ .../plotsystem/core/menus/ReviewMenu.java | 14 +++----------- .../plotsystem/core/menus/ReviewPlotMenu.java | 8 ++------ .../core/menus/companion/CountryMenu.java | 1 + .../alpsbte/plotsystem/core/system/Builder.java | 17 ----------------- 8 files changed, 24 insertions(+), 47 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java index 9af8c787..7d1b51ca 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java @@ -55,7 +55,7 @@ public CMD_Plot_Feedback(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { Player player = getPlayer(sender); - if (getPlayer(sender) == null) { + if (player == null) { Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); return; } @@ -64,7 +64,7 @@ public void onCommand(CommandSender sender, String[] args) { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - } else if (player != null && PlotUtils.isPlotWorld(player.getWorld())) { + } else if (PlotUtils.isPlotWorld(player.getWorld())) { AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); if (!(p instanceof Plot)) { sendInfo(sender); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index d6bedf0d..c0db3428 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -40,6 +40,7 @@ import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; import java.sql.SQLException; import java.util.concurrent.CompletableFuture; @@ -54,7 +55,8 @@ public CMD_Plot_Teleport(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (getPlayer(sender) == null) { + Player player = getPlayer(sender); + if (player == null) { Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return; } @@ -71,7 +73,7 @@ public void onCommand(CommandSender sender, String[] args) { if (plot == null || plot.getStatus() == Status.unclaimed) { if (sender.hasPermission("plotsystem.admin") && plot != null) { - Builder builder = Builder.byUUID(getPlayer(sender).getUniqueId()); + Builder builder = Builder.byUUID(player.getUniqueId()); if (builder == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); return; @@ -91,7 +93,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - plot.getWorld().teleportPlayer(getPlayer(sender)); + plot.getWorld().teleportPlayer(player); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 01e5f52b..1429d973 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -27,6 +27,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; +import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; @@ -315,16 +316,13 @@ private void sendNotices(Player player, Builder builder) { } // Informing reviewer about new reviews - try { - if (player.hasPermission("plotsystem.admin") || DataProvider.BUILDER.isAnyReviewer(builder.getUUID())) { - List unreviewedPlots = DataProvider.PLOT.getPlots(builder.getAsReviewer().getCountries(), Status.unreviewed); + if (player.hasPermission("plotsystem.admin") || DataProvider.BUILDER.isAnyReviewer(builder.getUUID())) { + List reviewerCountries = DataProvider.BUILD_TEAM.getReviewerCountries(builder); + List unreviewedPlots = DataProvider.PLOT.getPlots(reviewerCountries, Status.unreviewed); - if (!unreviewedPlots.isEmpty()) { - PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, player); - } + if (!unreviewedPlots.isEmpty()) { + PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, player); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about unreviewed plots!"), ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 9e60702f..1d36de90 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -87,4 +87,9 @@ public boolean removeReviewer(int id, String reviewerUUID) { // TODO: implement return false; } + + public List getReviewerCountries(Builder builder) { + // TODO: implement + return List.of(); + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 5f8750fa..59e36f3e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -26,7 +26,6 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; @@ -44,13 +43,10 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import static net.kyori.adventure.text.Component.text; - public class ReviewMenu extends AbstractPaginatedMenu { private List countries = new ArrayList<>(); private Country filteredCountry = null; @@ -62,13 +58,9 @@ public ReviewMenu(Player player) { @Override protected List getSource() { List plots = new ArrayList<>(); - try { - countries = Builder.byUUID(getMenuPlayer().getUniqueId()).getAsReviewer().getCountries(); - plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unreviewed)); - plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unfinished)); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + countries = DataProvider.BUILD_TEAM.getReviewerCountries(Builder.byUUID(getMenuPlayer().getUniqueId())); + plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unreviewed)); + plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unfinished)); return plots; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java index 7b7ce4f3..acc753b6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java @@ -275,12 +275,8 @@ protected void setItemClickEventsAsync() { } // Delete plot world after reviewing - try { - if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) - plot.getWorld().deleteWorld(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) + plot.getWorld().deleteWorld(); clickPlayer.sendMessage(reviewerConfirmationMessage); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1f, 1f); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index 9ffa9483..38fd17bc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -47,6 +47,7 @@ import org.ipvp.canvas.mask.Mask; import org.jetbrains.annotations.NotNull; +import java.util.ArrayList; import java.util.List; import java.util.Map; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 87f9ce3b..fe3bd4df 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -31,7 +31,6 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.sql.SQLException; import java.util.*; public class Builder { @@ -150,20 +149,4 @@ public static Builder byUUID(UUID uuid) { public static Builder byName(String name) { return DataProvider.BUILDER.getBuilderByName(name); } - - public Reviewer getAsReviewer() throws SQLException { - return new Reviewer(getUUID()); - } - - public static class Reviewer { - private final List buildTeams; - - public Reviewer(UUID reviewerUUID) { - this.buildTeams = DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(reviewerUUID); - } - - public List getCountries() { - return DataProvider.BUILDER.getReviewerCountries(buildTeams); - } - } } From de48a19456293830474f1ae0a45ff2d1571749ff Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 22:33:59 +0100 Subject: [PATCH 026/175] Cleanup EventListener and change plottype to be of PlotType type instead of int --- .../plotsystem/core/EventListener.java | 100 ++++++++---------- .../database/providers/BuilderProvider.java | 8 ++ .../plotsystem/core/menus/PlotTypeMenu.java | 6 +- .../plotsystem/core/system/BuildTeam.java | 2 - .../plotsystem/core/system/Builder.java | 10 +- .../plotsystem/core/system/Payout.java | 1 - .../plotsystem/core/system/Review.java | 21 ++-- .../utils/PlotMemberInvitation.java | 15 +-- 8 files changed, 75 insertions(+), 88 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 1429d973..47248e37 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -41,7 +41,6 @@ import com.alpsbte.plotsystem.utils.chat.PlayerFeedbackChatInput; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.core.menus.ReviewMenu; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; @@ -57,6 +56,7 @@ import io.papermc.paper.event.player.AsyncChatEvent; import li.cinnazeyy.langlibs.core.event.LanguageChangeEvent; import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.title.Title; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; @@ -74,14 +74,18 @@ import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; -import java.sql.ResultSet; import java.sql.SQLException; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.UUID; +import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class EventListener implements Listener { @EventHandler @@ -89,35 +93,19 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { // User has joined for the first time // Adding user to the database Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - // Add Items - Utils.updatePlayerInventorySlots(event.getPlayer()); - - // Check if player even exists in database. - try (ResultSet rs = DatabaseConnection.createStatement("SELECT * FROM plotsystem_builders WHERE uuid = ?") - .setValue(event.getPlayer().getUniqueId().toString()).executeQuery()) { - - if (!rs.first()) { - DatabaseConnection.createStatement("INSERT INTO plotsystem_builders (uuid, name) VALUES (?, ?)") - .setValue(event.getPlayer().getUniqueId().toString()) - .setValue(event.getPlayer().getName()) - .executeUpdate(); - } + Player player = event.getPlayer(); - DatabaseConnection.closeResultSet(rs); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + // Add Items + Utils.updatePlayerInventorySlots(player); + // Create builder if it does not exist in database. + boolean successful = DataProvider.BUILDER.addBuilderIfNotExists(player.getUniqueId(), player.getName()); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("BUILDER COULD NOT BE CREATED!!")); - // Check if player has changed his name - Builder builder = Builder.byUUID(event.getPlayer().getUniqueId()); - try { - if (!builder.getName().equals(event.getPlayer().getName())) { - DatabaseConnection.createStatement("UPDATE plotsystem_builders SET name = ? WHERE uuid = ?") - .setValue(event.getPlayer().getName()).setValue(event.getPlayer().getUniqueId().toString()).executeUpdate(); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + // Check if player has changed their name + Builder builder = Builder.byUUID(player.getUniqueId()); + if (!builder.getName().equals(player.getName())) { + builder.setName(player.getName()); } sendNotices(event.getPlayer(), builder); @@ -135,29 +123,7 @@ public void onPlayerInteractEvent(PlayerInteractEvent event) { } // Open/Close iron trap door when right-clicking - if (event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { - if (event.getHand() != EquipmentSlot.OFF_HAND) { - if (!event.getPlayer().isSneaking()) { - if (event.getClickedBlock() != null && event.getClickedBlock().getType() == Material.IRON_TRAPDOOR) { - RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); - RegionQuery query = regionContainer.createQuery(); - - if (query.testBuild(BukkitAdapter.adapt(event.getPlayer().getLocation()), PlotSystem.DependencyManager.getWorldGuard().wrapPlayer(event.getPlayer()), Flags.INTERACT)) { - BlockState state = event.getClickedBlock().getState(); - Openable tp = (Openable) state.getBlockData(); - if (!tp.isOpen()) { - tp.setOpen(true); - event.getPlayer().playSound(event.getClickedBlock().getLocation(), "block.iron_trapdoor.open", 1f, 1f); - } else { - tp.setOpen(false); - event.getPlayer().playSound(event.getClickedBlock().getLocation(), "block.iron_trapdoor.close", 1f, 1f); - } - state.update(); - } - } - } - } - } + handleIronTrapdoorClick(event); } @EventHandler @@ -211,7 +177,7 @@ public void onInventoryClickEvent(InventoryClickEvent event) { if (event.getWhoClicked().getGameMode() == GameMode.CREATIVE) { if (event.getCursor().isSimilar(CompanionMenu.getMenuItem((Player) event.getWhoClicked())) || event.getCursor().isSimilar(ReviewMenu.getMenuItem((Player) event.getWhoClicked()))) { - event.setCursor(ItemStack.empty()); + event.getView().setCursor(ItemStack.empty()); event.setCancelled(true); } } @@ -277,6 +243,29 @@ public void onLanguageChange(LanguageChangeEvent event) { Utils.updatePlayerInventorySlots(event.getPlayer()); } + private void handleIronTrapdoorClick(PlayerInteractEvent event) { + if (!event.getAction().equals(Action.RIGHT_CLICK_AIR) && !event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return; + if (event.getHand() == EquipmentSlot.OFF_HAND) return; + if (event.getPlayer().isSneaking()) return; + if (event.getClickedBlock() == null || event.getClickedBlock().getType() != Material.IRON_TRAPDOOR) return; + + RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = regionContainer.createQuery(); + + if (!query.testBuild(BukkitAdapter.adapt(event.getPlayer().getLocation()), PlotSystem.DependencyManager.getWorldGuard().wrapPlayer(event.getPlayer()), Flags.INTERACT)) return; + + BlockState state = event.getClickedBlock().getState(); + Openable tp = (Openable) state.getBlockData(); + if (!tp.isOpen()) { + tp.setOpen(true); + event.getPlayer().playSound(event.getClickedBlock().getLocation(), "block.iron_trapdoor.open", 1f, 1f); + } else { + tp.setOpen(false); + event.getPlayer().playSound(event.getClickedBlock().getLocation(), "block.iron_trapdoor.close", 1f, 1f); + } + state.update(); + } + private void sendNotices(Player player, Builder builder) { // Inform player about update if (player.hasPermission("plotsystem.admin") && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.CHECK_FOR_UPDATES) && PlotSystem.UpdateChecker.updateAvailable()) { @@ -298,7 +287,12 @@ private void sendNotices(Player player, Builder builder) { if (!reviewedPlots.isEmpty()) { PlotUtils.ChatFormatting.sendFeedbackMessage(reviewedPlots, player); - player.sendTitle("", "§6§l" + reviewedPlots.size() + " §a§lPlot" + (reviewedPlots.size() == 1 ? " " : "s ") + (reviewedPlots.size() == 1 ? "has" : "have") + " been reviewed!", 20, 150, 20); + String subtitleText = " Plot" + (reviewedPlots.size() == 1 ? " " : "s ") + (reviewedPlots.size() == 1 ? "has" : "have") + " been reviewed!"; + player.showTitle(Title.title( + empty(), + text(reviewedPlots.size(), GOLD).decoration(BOLD, true).append(text(subtitleText, GREEN).decoration(BOLD, true)), + Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofSeconds(1))) + ); } } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his plot feedback!"), ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 1652d778..4fdfc7d8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -75,6 +75,14 @@ public Builder getBuilderByName(String name) { return null; } + public boolean addBuilderIfNotExists(UUID uuid, String name) { + // TODO: implement + // check if builder already exists, if so return TRUE!! + // if successfully added -> TRUE + // else -> FALSE + return false; + } + public boolean setName(UUID uuid, String name) { try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("UPDATE builder SET name = ? WHERE uuid = ?;")) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index c4000ef9..00c462a1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -106,19 +106,19 @@ protected void setMenuItemsAsync() { protected void setItemClickEventsAsync() { // Set click event for plot type items getMenu().getSlot(11).setClickHandler(((clickPlayer, clickInformation) -> { - builder.setPlotTypeSetting(PlotType.FOCUS_MODE); + builder.setPlotType(PlotType.FOCUS_MODE); getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); reloadMenuAsync(); })); getMenu().getSlot(13).setClickHandler(((clickPlayer, clickInformation) -> { - builder.setPlotTypeSetting(PlotType.LOCAL_INSPIRATION_MODE); + builder.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); reloadMenuAsync(); })); getMenu().getSlot(15).setClickHandler(((clickPlayer, clickInformation) -> { - builder.setPlotTypeSetting(PlotType.CITY_INSPIRATION_MODE); + builder.setPlotType(PlotType.CITY_INSPIRATION_MODE); getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); reloadMenuAsync(); })); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 356ad553..3965cf51 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -26,10 +26,8 @@ import com.alpsbte.plotsystem.core.database.DataProvider; -import java.sql.SQLException; import java.util.List; import java.util.Optional; -import java.util.UUID; public class BuildTeam { private final int ID; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index fe3bd4df..bcc4bc36 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -40,9 +40,9 @@ public class Builder { private int firstSlot; private int secondSlot; private int thirdSlot; - private int plotType; + private PlotType plotType; - public Builder(UUID UUID, String name, int score, int first_slot, int second_slot, int third_slot, int plot_type) { + public Builder(UUID UUID, String name, int score, int first_slot, int second_slot, int third_slot, PlotType plot_type) { this.uuid = UUID; this.name = name; this.score = score; @@ -104,11 +104,11 @@ public boolean setSlot(Slot slot, int plotId) { } public PlotType getPlotType() { - return PlotType.byId(plotType); + return plotType; } - public boolean setPlotType(int plotType) { - if (DataProvider.BUILDER.setPlotType(this.uuid, plotType)) { + public boolean setPlotType(PlotType plotType) { + if (DataProvider.BUILDER.setPlotType(this.uuid, plotType.getId())) { this.plotType = plotType; return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java b/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java index b6d8e423..603eb4c3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; import java.sql.ResultSet; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java index df4a6838..66cf34a2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java @@ -106,20 +106,13 @@ public int getRating(Category category) throws SQLException { String[] scoreAsString = rs.getString("rating").split(","); DatabaseConnection.closeResultSet(rs); - switch (category) { - case ACCURACY: - return Integer.parseInt(scoreAsString[0]); - case BLOCKPALETTE: - return Integer.parseInt(scoreAsString[1]); - case DETAILING: - return Integer.parseInt(scoreAsString[2]); - case TECHNIQUE: - return Integer.parseInt(scoreAsString[3]); - case ALL: - return Integer.parseInt(scoreAsString[0]) + Integer.parseInt(scoreAsString[1]) + Integer.parseInt(scoreAsString[2]) + Integer.parseInt(scoreAsString[3]); - default: - return 0; - } + return switch (category) { + case ACCURACY -> Integer.parseInt(scoreAsString[0]); + case BLOCKPALETTE -> Integer.parseInt(scoreAsString[1]); + case DETAILING -> Integer.parseInt(scoreAsString[2]); + case TECHNIQUE -> Integer.parseInt(scoreAsString[3]); + case ALL -> Integer.parseInt(scoreAsString[0]) + Integer.parseInt(scoreAsString[1]) + Integer.parseInt(scoreAsString[2]) + Integer.parseInt(scoreAsString[3]); + }; } DatabaseConnection.closeResultSet(rs); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java index f8757b20..5c825e14 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java @@ -36,7 +36,6 @@ import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitScheduler; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -56,7 +55,7 @@ public class PlotMemberInvitation { private final BukkitScheduler scheduler = PlotSystem.getPlugin().getServer().getScheduler(); private int taskID; - public PlotMemberInvitation(Player invitee, Plot plot) throws SQLException { + public PlotMemberInvitation(Player invitee, Plot plot) { this.invitee = invitee; this.plot = plot; @@ -87,14 +86,10 @@ public PlotMemberInvitation(Player invitee, Plot plot) throws SQLException { PlotMemberInvitation invitation = this; taskID = scheduler.scheduleSyncDelayedTask(PlotSystem.getPlugin(), () -> { invitationsList.remove(invitation); - try { - invitee.sendMessage(Utils.ChatUtils.getAlertFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(invitee, - LangPaths.Message.Error.PLAYER_INVITE_EXPIRED, TEXT_HIGHLIGHT_START + plot.getPlotOwner().getName() + TEXT_HIGHLIGHT_END)))); - plot.getPlotOwner().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(plot.getPlotOwner().getPlayer(), - LangPaths.Message.Error.PLAYER_INVITE_TO_EXPIRED, TEXT_HIGHLIGHT_START + invitee.getName() + TEXT_HIGHLIGHT_END)))); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + invitee.sendMessage(Utils.ChatUtils.getAlertFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(invitee, + LangPaths.Message.Error.PLAYER_INVITE_EXPIRED, TEXT_HIGHLIGHT_START + plot.getPlotOwner().getName() + TEXT_HIGHLIGHT_END)))); + plot.getPlotOwner().getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(plot.getPlotOwner().getPlayer(), + LangPaths.Message.Error.PLAYER_INVITE_TO_EXPIRED, TEXT_HIGHLIGHT_START + invitee.getName() + TEXT_HIGHLIGHT_END)))); }, 20 * 30); } From 35314a08722551f090ab6fe31cbef4dd4f642be1 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 22:34:48 +0100 Subject: [PATCH 027/175] =?UTF-8?q?delete=20FTPConfiguration.java!!=20?= =?UTF-8?q?=F0=9F=8E=89=F0=9F=8E=89=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/system/FTPConfiguration.java | 134 ------------------ 1 file changed, 134 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/FTPConfiguration.java diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/FTPConfiguration.java b/src/main/java/com/alpsbte/plotsystem/core/system/FTPConfiguration.java deleted file mode 100644 index 3877fcb5..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/system/FTPConfiguration.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.system; - -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; - -import java.io.File; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -import static net.kyori.adventure.text.Component.text; - -public class FTPConfiguration { - private final int ID; - - private String schematicPath; - private String address; - private int port; - private boolean isSFTP; - private String username; - private String password; - - public FTPConfiguration(int ID) throws SQLException { - this.ID = ID; - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT schematics_path, address, port, isSFTP, username, password FROM plotsystem_ftp_configurations WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - this.schematicPath = rs.getString(1); - this.address = rs.getString(2); - this.port = rs.getInt(3); - this.isSFTP = rs.getBoolean(4); - this.username = rs.getString(5); - this.password = rs.getString(6); - } - - DatabaseConnection.closeResultSet(rs); - } - } - - public int getID() { - return ID; - } - - public String getSchematicPath() { - if (schematicPath != null) { - schematicPath = !schematicPath.startsWith("/") ? File.separator + schematicPath : schematicPath; - schematicPath = schematicPath.endsWith("/") ? schematicPath.substring(0, schematicPath.length() - 1) : schematicPath; - } - return schematicPath; - } - - public String getAddress() { - return address; - } - - public int getPort() { - return port; - } - - public boolean isSFTP() { - return isSFTP; - } - - public String getUsername() { - return username; - } - - public String getPassword() { - return password; - } - - public static List getFTPConfigurations() { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_ftp_configurations").executeQuery()) { - List ftpConfigurations = new ArrayList<>(); - while (rs.next()) { - ftpConfigurations.add(new FTPConfiguration(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - - return ftpConfigurations; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return new ArrayList<>(); - } - - public static void addFTPConfiguration(String address, int port, boolean isSFTP, String username, String password) throws SQLException { - DatabaseConnection.createStatement("INSERT INTO plotsystem_ftp_configurations (id, address, port, isSFTP, username, password) VALUES (?, ?, ?, ?, ?, ?)") - .setValue(DatabaseConnection.getTableID("plotsystem_ftp_configurations")) - .setValue(address).setValue(port).setValue(isSFTP ? 1 : 0).setValue(username).setValue(password).executeUpdate(); - } - - public static void removeFTPConfiguration(int ID) throws SQLException { - if (getFTPConfigurations().stream().anyMatch(ftp -> ftp.getID() == ID)) { - DatabaseConnection.createStatement("DELETE FROM plotsystem_ftp_configurations WHERE id = ?") - .setValue(ID).executeUpdate(); - } - } - - public static void setSchematicPath(int ID, String path) throws SQLException { - if (getFTPConfigurations().stream().anyMatch(ftp -> ftp.getID() == ID)) { - DatabaseConnection.createStatement("UPDATE plotsystem_ftp_configurations SET schematics_path = ? WHERE id = ?") - .setValue(path).setValue(ID).executeUpdate(); - } - } -} From f812d25b647eb9f75ffc62eff5175e42856f9b40 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 9 Feb 2025 22:58:14 +0100 Subject: [PATCH 028/175] delete Payout.java --- .../leaderboards/ScoreLeaderboard.java | 34 +------- .../plotsystem/core/system/Payout.java | 82 ------------------- 2 files changed, 2 insertions(+), 114 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/Payout.java diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index a3eae44d..748cfc42 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -29,7 +29,6 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.holograms.HologramConfiguration; import com.alpsbte.plotsystem.core.holograms.HologramRegister; -import com.alpsbte.plotsystem.core.system.Payout; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; @@ -47,7 +46,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.sql.SQLException; import java.text.DecimalFormat; import java.util.*; import java.util.logging.Level; @@ -115,14 +113,14 @@ public List> getContent(UUID playerUUID) { ArrayList> lines = new ArrayList<>(); for (int index = 0; index < 10; index++) { - lines.add(new LeaderboardPositionLineWithPayout(index + 1, null, 0)); + lines.add(new HologramRegister.LeaderboardPositionLine(index + 1, null, 0)); } Map playerRankings = DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard); if (playerRankings != null) { for (int i = 0; i < playerRankings.size(); i++) { String key = (String) playerRankings.keySet().toArray()[i]; - lines.set(i, new LeaderboardPositionLineWithPayout(i + 1, key, playerRankings.get(key))); + lines.set(i, new HologramRegister.LeaderboardPositionLine(i + 1, key, playerRankings.get(key))); } } return lines; @@ -216,32 +214,4 @@ public String getYPath() { public String getZPath() { return ConfigPaths.SCORE_LEADERBOARD_Z; } - - private class LeaderboardPositionLineWithPayout extends HologramRegister.LeaderboardPositionLine { - private final int position; - - public LeaderboardPositionLineWithPayout(int position, String username, int score) { - super(position, username, score); - this.position = position; - } - - @Override - public String getLine() { - try { - String line = super.getLine(); - Payout payout = sortByLeaderboard != LeaderboardTimeframe.LIFETIME ? Payout.getPayout(sortByLeaderboard, position) : null; - if (payout == null) return line; - String payoutAmount = payout.getPayoutAmount(); - try { - // if payout amount can be number, prefix with dollar sign - Integer.valueOf(payoutAmount); - payoutAmount = "$" + payoutAmount; - } catch (NumberFormatException ignored) {} - - return line + " §7- §e§l" + payoutAmount; - } catch (SQLException e) { - return super.getLine() + " §7- §cSQL ERR"; - } - } - } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java b/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java deleted file mode 100644 index 603eb4c3..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Payout.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2022, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.system; - -import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; - -import java.sql.ResultSet; -import java.sql.SQLException; - -public class Payout { - private final int id; - private final LeaderboardTimeframe timeframe; - private final int position; - private final String payoutAmount; - - private Payout(int id, LeaderboardTimeframe timeframe, int position, String payoutAmount) { - this.id = id; - this.timeframe = timeframe; - this.position = position; - this.payoutAmount = payoutAmount; - } - - public static Payout getPayout(LeaderboardTimeframe timeframe, int position) throws SQLException { - if (timeframe == LeaderboardTimeframe.LIFETIME) { - throw new IllegalArgumentException("Invalid option LIFETIME"); - } - if (position < 1 || position > 10) { - throw new IllegalArgumentException("Illegal position " + position); - } - - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id, timeframe, position, payout_amount FROM plotsystem_payouts WHERE timeframe = ? AND position = ?") - .setValue(timeframe.name()).setValue(position).executeQuery()) { - Payout instance = null; - - if (rs.next()) { - instance = new Payout(rs.getInt(1), LeaderboardTimeframe.valueOf(rs.getString(2)), rs.getInt(3), rs.getString(4)); - } - - DatabaseConnection.closeResultSet(rs); - return instance; - } - } - - public int getId() { - return id; - } - - public LeaderboardTimeframe getTimeframe() { - return timeframe; - } - - public int getPosition() { - return position; - } - - public String getPayoutAmount() { - return payoutAmount; - } -} \ No newline at end of file From b9b60bd90705b0705174d506bf31fd94e92b1580 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sun, 9 Feb 2025 23:23:49 +0100 Subject: [PATCH 029/175] update CityProjects data provider --- .../commands/admin/setup/CMD_Setup_City.java | 12 +- .../database/providers/BuilderProvider.java | 44 ++---- .../providers/CityProjectProvider.java | 133 ++++++++++++++---- .../core/menus/companion/CityProjectMenu.java | 4 +- .../plotsystem/core/system/Builder.java | 10 +- .../plotsystem/core/system/CityProject.java | 28 ++-- .../plotsystem/core/system/Country.java | 2 +- .../core/system/plot/utils/PlotUtils.java | 2 +- 8 files changed, 151 insertions(+), 84 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 670a812a..accedfde 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -85,7 +85,7 @@ public CMD_Setup_City_List(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - List cities = DataProvider.CITY_PROJECT.getCityProjects(false); + List cities = DataProvider.CITY_PROJECT.get(false); if (cities.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no City Projects registered in the database!")); return; @@ -153,7 +153,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean added = DataProvider.CITY_PROJECT.addCityProject(cityProjectId, country.getCode(), serverName); + boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, country.getCode(), serverName); if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); } @@ -190,14 +190,14 @@ public void onCommand(CommandSender sender, String[] args) { String cityProjectId = args[1]; // Check if City Project exists - CityProject cityProject = DataProvider.CITY_PROJECT.getCityProjectById(cityProjectId); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(cityProjectId); if (cityProject == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any City Project with ID " + cityProjectId + "!")); sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all City Projects!")); return; } - boolean removed = DataProvider.CITY_PROJECT.removeCityProject(cityProjectId); + boolean removed = DataProvider.CITY_PROJECT.remove(cityProjectId); if (removed) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed City Project with ID " + cityProjectId + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while removing city project!")); } @@ -233,7 +233,7 @@ public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2) {sendInfo(sender); return;} // Check if City Project exits - CityProject cityProject = DataProvider.CITY_PROJECT.getCityProjectById(args[1]); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[1]); if (cityProject == null) return; String serverName = args[2]; @@ -284,7 +284,7 @@ public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2) {sendInfo(sender); return;} // Check if City Project exits - CityProject cityProject = DataProvider.CITY_PROJECT.getCityProjectById(args[1]); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[1]); if (cityProject == null) return; if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 4fdfc7d8..bb514078 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -24,11 +24,11 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Slot; @@ -39,7 +39,7 @@ import java.util.*; public class BuilderProvider { - public static final HashMap builders = new HashMap<>(); + public static final Map builders = new HashMap<>(); public Builder getBuilderByUUID(UUID uuid) { if (builders.containsKey(uuid)) return builders.get(uuid); @@ -54,9 +54,7 @@ public Builder getBuilderByUUID(UUID uuid) { rs.getInt(4), rs.getInt(5), rs.getInt(6)); } } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return null; } @@ -69,9 +67,7 @@ public Builder getBuilderByName(String name) { String uuid = rs.getString(1); if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return null; } @@ -91,9 +87,7 @@ public boolean setName(UUID uuid, String name) { stmt.executeUpdate(); if (builders.containsKey(uuid)) builders.get(uuid).setName(name); return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } @@ -106,9 +100,7 @@ public boolean addScore(UUID uuid, int score) { stmt.executeUpdate(); return true; } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } @@ -131,9 +123,7 @@ public boolean setSlot(UUID uuid, int plotID, Slot slot) { } } return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } @@ -154,9 +144,7 @@ public boolean setPlotType(UUID uuid, int plotTypeId) { } } return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } @@ -169,9 +157,7 @@ public int getCompletedBuildsCount(UUID uuid) { try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) return rs.getInt(1); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return 0; } @@ -185,9 +171,7 @@ public Slot getFreeSlot(UUID uuid) { if (rs.getString(i) == null) return Slot.values()[i - 1]; } } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return null; } @@ -220,9 +204,7 @@ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimefram } } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return null; } @@ -242,9 +224,7 @@ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { return playerEntries; } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(ex.getMessage()); - } + } catch (SQLException ex) { Utils.logSqlException(ex); } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 65a3d12b..d7510838 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -1,50 +1,135 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.utils.Utils; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; public class CityProjectProvider { - public CityProject getCityProjectById(String id) { - // TODO: implement - return null; - } + public static final List cityProjects = new ArrayList<>(); - public List getCityProjectsByCountryCode(String countryCode) { - // TODO: implement - return List.of(); + public CityProject getById(String id) { + return cityProjects.stream().filter(c -> c.getID().equals(id)).findFirst() + .orElseGet(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT country_code, server_name, is_visible FROM city_project " + + "WHERE city_project_id = ?;")) { + stmt.setString(1, id); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return new CityProject(id, rs.getString(1), rs.getString(2), + rs.getBoolean(3)); + } + } + } catch (SQLException ex) { Utils.logSqlException(ex); } + return null; + }); } - public List getCityProjects(Country country, boolean onlyVisible) { - // TODO: implement - return List.of(); + public List getByCountryCode(String countryCode, boolean onlyVisible) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT city_project_id FROM city_project WHERE country_code = ? " + + "AND is_visible = ?;")) { + stmt.setString(1, countryCode); + stmt.setBoolean(2, onlyVisible); + + try (ResultSet rs = stmt.executeQuery()) { + List cityProjects = new ArrayList<>(); + while (rs.next()) cityProjects.add(getById(rs.getString(1))); + return cityProjects; + } + } catch (SQLException ex) { Utils.logSqlException(ex); } + return null; } - public List getCityProjects(boolean onlyVisible) { - // TODO: implement - return List.of(); + public List get(boolean onlyVisible) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT city_project_id FROM city_project WHERE is_visible = ?;")) { + stmt.setBoolean(1, onlyVisible); + + try (ResultSet rs = stmt.executeQuery()) { + List cityProjects = new ArrayList<>(); + while (rs.next()) cityProjects.add(getById(rs.getString(1))); + return cityProjects; + } + } catch (SQLException ex) { Utils.logSqlException(ex); } + return null; } - public boolean addCityProject(String id, String countryCode, String serverName) { - // TODO: implement (isVisible can be default) - // return false if error occurred + public boolean add(String id, String countryCode, String serverName) { + if (getById(id) != null) return true; + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO city_project (city_project_id, country_code, server_name) " + + "VALUES (?, ?, ?);")) { + stmt.setString(1, id); + stmt.setString(2, countryCode); + stmt.setString(3, serverName); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } - public boolean removeCityProject(String id) { - // TODO: implement - // return false if error occurred + public boolean remove(String id) { + CityProject cityProject = getById(id); + if (cityProject == null) return false; + + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("DELETE FROM city_project WHERE city_project_id = ?;")) { + stmt.setString(1, id); + boolean result = stmt.executeUpdate() > 0; + if (result) cityProjects.remove(cityProject); + return result; + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } - public boolean setCityProjectVisibility(String id, boolean isVisible) { - // TODO: implement + public boolean setVisibility(String id, boolean isVisible) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE city_project SET is_visible = ? WHERE city_project_id = ?;")) { + stmt.setBoolean(1, isVisible); + stmt.setString(2, id); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } - public boolean setCityProjectServer(String id, String serverName) { - // TODO: implement + public boolean setServer(String id, String serverName) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE city_project SET server_name = ? WHERE city_project_id = ?;")) { + stmt.setString(1, serverName); + stmt.setString(2, id); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 4fe69c6e..5a2ea320 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -151,7 +151,7 @@ public static boolean generateRandomPlot(Player player, @NotNull List getValidCityProjects(PlotDifficulty selectedPlotDifficulty, Player player, Country country) { - return DataProvider.CITY_PROJECT.getCityProjects(country, true).stream().filter(test -> { + return DataProvider.CITY_PROJECT.getByCountryCode(country.getCode(), true).stream().filter(test -> { if (test instanceof CityProject project) { var pd = selectedPlotDifficulty; try { @@ -184,7 +184,7 @@ protected Mask getMask() { @Override protected List getSource() { - if (projects == null) projects = DataProvider.CITY_PROJECT.getCityProjects(country, true); + if (projects == null) projects = DataProvider.CITY_PROJECT.getByCountryCode(country.getCode(), true); return projects; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index bcc4bc36..4cc83d4e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -40,16 +40,16 @@ public class Builder { private int firstSlot; private int secondSlot; private int thirdSlot; - private PlotType plotType; + private int plotType; - public Builder(UUID UUID, String name, int score, int first_slot, int second_slot, int third_slot, PlotType plot_type) { + public Builder(UUID UUID, String name, int score, int first_slot, int second_slot, int third_slot, int plotType) { this.uuid = UUID; this.name = name; this.score = score; this.firstSlot = first_slot; this.secondSlot = second_slot; this.thirdSlot = third_slot; - this.plotType = plot_type; + this.plotType = plotType; } public java.util.UUID getUUID() { @@ -104,12 +104,12 @@ public boolean setSlot(Slot slot, int plotId) { } public PlotType getPlotType() { - return plotType; + return PlotType.byId(plotType); } public boolean setPlotType(PlotType plotType) { if (DataProvider.BUILDER.setPlotType(this.uuid, plotType.getId())) { - this.plotType = plotType; + this.plotType = plotType.getId(); return true; } return false; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index a608585a..af4f071f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.database.providers.CityProjectProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; @@ -57,6 +58,7 @@ public CityProject(String id, String countryCode, String serverName, boolean isV this.countryCode = countryCode; this.serverName = serverName; this.isVisible = isVisible; + CityProjectProvider.cityProjects.add(this); } public String getID() { @@ -72,13 +74,25 @@ public String getServerName() { } public boolean setServer(String serverName) { - if (DataProvider.CITY_PROJECT.setCityProjectServer(ID, serverName)) { + if (DataProvider.CITY_PROJECT.setServer(ID, serverName)) { this.serverName = serverName; return true; } return false; } + public boolean isVisible() { + return isVisible; + } + + public boolean setVisible(boolean isVisible) { + if (DataProvider.CITY_PROJECT.setVisibility(ID, isVisible)) { + this.isVisible = isVisible; + return true; + } + return false; + } + public String getName(Player player) { // TODO: implement (get from language file) return "CityProject WIP"; @@ -95,18 +109,6 @@ public ArrayList getDescriptionComponents(Player player) { return descriptionLines; } - public boolean isVisible() { - return isVisible; - } - - public boolean setVisible(boolean isVisible) { - if (DataProvider.CITY_PROJECT.setCityProjectVisibility(ID, isVisible)) { - this.isVisible = isVisible; - return true; - } - return false; - } - public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { ItemStack cpItem = getCountry().getCountryItem(); try { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index 49301528..e73ba5a2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -58,7 +58,7 @@ public Country(String code, Continent continent, String material, String customM public Continent getContinent() {return continent;} public List getCityProjects() { - return DataProvider.CITY_PROJECT.getCityProjectsByCountryCode(code); + return DataProvider.CITY_PROJECT.getByCountryCode(code, true); } public String getName(Player player) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 5af23947..4041e35d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -116,7 +116,7 @@ public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { return null; } else if (PlotWorld.isCityPlotWorld(worldName)) { String cityID = worldName.substring(2); - CityProject city = DataProvider.CITY_PROJECT.getCityProjectById(cityID); + CityProject city = DataProvider.CITY_PROJECT.getById(cityID); List plots = DataProvider.PLOT.getPlots(city, statuses); if (plots.isEmpty()) return null; From 805f17d236c7163826f0cd405ec0f9d4a90178a7 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sun, 9 Feb 2025 23:24:09 +0100 Subject: [PATCH 030/175] update TutorialPlot data provider --- .../plotsystem/commands/CMD_Companion.java | 24 +- .../plotsystem/core/EventListener.java | 22 +- .../core/database/DataProvider.java | 4 + .../core/database/providers/PlotProvider.java | 43 ++- .../providers/TutorialPlotProvider.java | 101 ++++++ .../core/menus/tutorial/TutorialsMenu.java | 10 +- .../core/system/plot/AbstractPlot.java | 2 +- .../plotsystem/core/system/plot/Plot.java | 4 +- .../core/system/plot/TutorialPlot.java | 338 ++++-------------- .../plot/generator/TutorialPlotGenerator.java | 5 +- .../system/tutorial/AbstractPlotTutorial.java | 85 ++--- .../system/tutorial/AbstractTutorial.java | 8 +- .../tutorial/AbstractTutorialHologram.java | 2 +- .../system/tutorial/BeginnerTutorial.java | 19 +- .../core/system/tutorial/PlotTutorial.java | 2 +- .../core/system/tutorial/Tutorial.java | 2 +- .../system/tutorial/TutorialCategory.java | 2 +- .../system/tutorial/TutorialDataModel.java | 87 ----- .../tutorial/TutorialEventListener.java | 2 +- 19 files changed, 293 insertions(+), 469 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialDataModel.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java index 4923b2c1..9a3ef0a6 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java @@ -42,10 +42,6 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; - -import static net.kyori.adventure.text.Component.text; - public class CMD_Companion extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { @@ -57,18 +53,14 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Player player = getPlayer(sender); if (player == null) return true; - try { - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - Tutorial tutorial = AbstractTutorial.getActiveTutorial(player.getUniqueId()); - if (tutorial != null) { - new TutorialStagesMenu(player, tutorial.getId()); - } else if (config.getBoolean(ConfigPaths.TUTORIAL_ENABLE) && config.getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && - !TutorialPlot.isPlotCompleted(player, TutorialCategory.BEGINNER.getId()) && player.hasPermission("plotsystem.tutorial")) { - new TutorialsMenu(player); - } else CompanionMenu.open((Player) sender); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + FileConfiguration config = PlotSystem.getPlugin().getConfig(); + Tutorial tutorial = AbstractTutorial.getActiveTutorial(player.getUniqueId()); + if (tutorial != null) { + new TutorialStagesMenu(player, tutorial.getId()); + } else if (config.getBoolean(ConfigPaths.TUTORIAL_ENABLE) && config.getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && + TutorialPlot.isInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId()) && player.hasPermission("plotsystem.tutorial")) { + new TutorialsMenu(player); + } else CompanionMenu.open((Player) sender); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 47248e37..029ad321 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -218,7 +218,7 @@ public void onPlayerChatEvent(AsyncChatEvent event) throws SQLException { if (player == null) { event.getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance() .get(event.getPlayer(), LangPaths.Message.Error.PLAYER_NOT_FOUND))); - } else if (!player.isOnline() || !TutorialPlot.isPlotCompleted(player, TutorialCategory.BEGINNER.getId())) { + } else if (!player.isOnline() || TutorialPlot.isInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { event.getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance() .get(event.getPlayer(), LangPaths.Message.Error.PLAYER_IS_NOT_ONLINE))); } else if (inviteeInput.getPlot().getPlotMembers().contains(Builder.byUUID(player.getUniqueId()))) { @@ -321,19 +321,15 @@ private void sendNotices(Player player, Builder builder) { // Start or notify the player if he has not completed the beginner tutorial yet (only if required) - try { - if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && - !TutorialPlot.isPlotCompleted(player, TutorialCategory.BEGINNER.getId())) { - if (!player.hasPlayedBefore()) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), - () -> player.performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); - } else { - AbstractPlotTutorial.sendTutorialRequiredMessage(player, TutorialCategory.BEGINNER.getId()); - player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); - } + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && + TutorialPlot.isInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { + if (!player.hasPlayedBefore()) { + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), + () -> player.performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); + } else { + AbstractPlotTutorial.sendTutorialRequiredMessage(player, TutorialCategory.BEGINNER.getId()); + player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index ee219b76..1cd95976 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -24,6 +24,9 @@ package com.alpsbte.plotsystem.core.database; +import com.alpsbte.plotsystem.core.database.providers.BuildTeamProvider; +import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; +import com.alpsbte.plotsystem.core.database.providers.PlotProvider; import com.alpsbte.plotsystem.core.database.providers.*; public class DataProvider { @@ -34,4 +37,5 @@ public class DataProvider { public static CityProjectProvider CITY_PROJECT = new CityProjectProvider(); public static CountryProvider COUNTRY = new CountryProvider(); public static ServerProvider SERVER = new ServerProvider(); + public static TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 66a26c14..8334bc22 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -1,15 +1,21 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; -import com.alpsbte.plotsystem.utils.enums.Status; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -17,11 +23,36 @@ public class PlotProvider { public Plot getPlotById(int plotId) { - // TODO: implement - - // set status - // set owner - + try (Connection con = DatabaseConnection.getConnection()) { + try (PreparedStatement stmt = con.prepareStatement("SELECT city_project_id, difficulty_id, status," + + " score, outline_bounds, last_activity_date, plot_version FROM plot WHERE plot_id = ?")) { + stmt.setInt(1, plotId); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + Status status = Status.valueOf(rs.getString(3)); + if (status != Status.unclaimed) { + try (PreparedStatement stmt2 = con.prepareStatement("SELECT uuid, 'owner' AS role FROM " + + "builder_is_plot_owner WHERE plot_id = ? UNION SELECT uuid, 'member' AS role FROM " + + "builder_is_plot_member WHERE plot_id = ?;")) { + stmt2.setInt(1, plotId); + stmt2.setInt(2, plotId); + UUID plotOwner; + List memberUUIDs = new ArrayList<>(); + try (ResultSet rs2 = stmt2.executeQuery()) { + while (rs2.next()) { + UUID uuid = UUID.fromString(rs2.getString(1)); + String role = rs2.getString(2); + if (role.equals("owner")) plotOwner = uuid; + else memberUUIDs.add(uuid); + } + } + } + } + } + } + } + } catch (SQLException ex) { Utils.logSqlException(ex); } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java new file mode 100644 index 00000000..b32a1099 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -0,0 +1,101 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.alpsbte.plotsystem.core.database.providers; + +import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; +import com.alpsbte.plotsystem.utils.Utils; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class TutorialPlotProvider { + public static final List tutorialPlots = new ArrayList<>(); + public static final LinkedList freeTutorialPlotIds = new LinkedList<>(); + + public TutorialPlot getById(int tutorialId, String playerUUID) { + return tutorialPlots.stream().filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString() + .equals(playerUUID)).findFirst() + .orElseGet(() -> { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT stage_id, is_complete, last_stage_complete_date FROM " + + "tutorial WHERE tutorial_id = ? AND uuid = ?;")) { + stmt.setInt(1, tutorialId); + stmt.setString(2, playerUUID); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int plotId = freeTutorialPlotIds.isEmpty() ? 0 : freeTutorialPlotIds.poll(); + return new TutorialPlot(plotId, tutorialId, playerUUID, rs.getInt(1), + rs.getBoolean(2), rs.getDate(3).toLocalDate()); + } + } + } catch (SQLException ex) { Utils.logSqlException(ex); } + return null; + }); + } + + public boolean add(int tutorialId, String playerUUID) { + if (getById(tutorialId, playerUUID) != null) return false; + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);")) { + stmt.setInt(1, tutorialId); + stmt.setString(2, playerUUID); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } + return false; + } + + public boolean setStageId(int tutorialId, String playerUUID, int stageId) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE tutorial SET stage_id = ?, last_stage_complete_date = ? WHERE " + + "tutorial_id = ? AND uuid = ?;")) { + stmt.setInt(1, stageId); + stmt.setObject(2, LocalDate.now()); + stmt.setInt(3, tutorialId); + stmt.setString(4, playerUUID); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } + return false; + } + + public boolean setComplete(int tutorialId, String playerUUID) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE tutorial SET is_complete = ?, last_stage_complete_date = ? WHERE " + + "tutorial_id = ? AND uuid = ?;")) { + stmt.setBoolean(1, true); + stmt.setObject(2, LocalDate.now()); + stmt.setInt(3, tutorialId); + stmt.setString(4, playerUUID); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } + return false; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index acc00cd9..0b8c2833 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -28,6 +28,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; @@ -92,9 +93,8 @@ protected void setPreviewItems() { protected void setMenuItemsAsync() { // Set tutorial items try { - plot = TutorialPlot.getPlot(getMenuPlayer().getUniqueId().toString(), TutorialCategory.BEGINNER.getId()); - // TutorialPlot beginnerTutorial = getPlotById(TutorialCategory.BEGINNER.getId()); - if (plot != null) isBeginnerTutorialCompleted = plot.isCompleted(); + plot = DataProvider.TUTORIAL_PLOT.getById(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()); + if (plot != null) isBeginnerTutorialCompleted = plot.isComplete(); // Set beginner tutorial item getMenu().getSlot(22).setItem(getTutorialItem(TutorialCategory.BEGINNER.getId(), beginnerTutorialItemName, @@ -151,7 +151,7 @@ private void setTutorialClickEvent(int tutorialId, ClickType clickType) { if (clickType == ClickType.LEFT) { // TutorialPlot plot = getPlotById(tutorialId); try { - if (plot == null || !plot.isCompleted()) { + if (plot == null || !plot.isComplete()) { getMenuPlayer().closeInventory(); if (!AbstractTutorial.loadTutorial(getMenuPlayer(), tutorialId)) { if (AbstractTutorial.getActiveTutorial(getMenuPlayer().getUniqueId()) != null) { @@ -184,7 +184,7 @@ private ItemStack getTutorialItem(int tutorialId, String itemName, String title, private static ItemStack constructTutorialItem(Player player, int tutorialId, TutorialPlot plot, ItemStack itemStack, String title, String desc) throws SQLException { // Create tutorial item lore int highestPlotStage = plot != null ? plot.getStageID() : 0; - boolean isPlotCompleted = plot != null && plot.isCompleted(); + boolean isPlotCompleted = plot != null && plot.isComplete(); LoreBuilder loreBuilder = new LoreBuilder() .addLine(text(desc, GRAY), true) .emptyLine() diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 852140fc..f71af166 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2021-2022, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 78a0d983..969ea6f7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -221,7 +221,9 @@ public double getVersion() { } @Override - public byte[] getInitialSchematicBytes() {return DataProvider.PLOT.getInitialSchematic(ID);} + public byte[] getInitialSchematicBytes() { + return DataProvider.PLOT.getInitialSchematic(ID); + } public byte[] getCompletedSchematic() { return DataProvider.PLOT.getCompletedSchematic(ID); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index b0c5320c..ef9f4c6a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -25,89 +25,61 @@ package com.alpsbte.plotsystem.core.system.plot; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.database.providers.TutorialPlotProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; -import com.alpsbte.plotsystem.core.system.tutorial.TutorialDataModel; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.TutorialPaths; import com.sk89q.worldedit.math.BlockVector2; import org.apache.commons.io.FileUtils; import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.io.*; +import java.nio.file.Files; import java.nio.file.Paths; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; import java.time.LocalDate; -import java.time.LocalDateTime; import java.util.*; import static net.kyori.adventure.text.Component.text; -public class TutorialPlot extends AbstractPlot implements TutorialDataModel { - private int tutorialId = -1; - private final FileConfiguration tutorialConfig; - - public TutorialPlot(int id) throws SQLException { - super(id); - tutorialConfig = ConfigUtil.getTutorialInstance().configs[getTutorialID()]; - } +public class TutorialPlot extends AbstractPlot { + private final int tutorialId; + private final UUID uuid; + private int stageId; + private boolean isComplete; + private final LocalDate lastStageActivity; - @Override - public UUID getPlayerUUID() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT player_uuid FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { + private int currentSchematicId; + private final FileConfiguration tutorialConfig; - if (rs.next()) { - String uuid = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return UUID.fromString(uuid); - } + public TutorialPlot(int plotId, int tutorialId, String uuid, int stageId, boolean isComplete, LocalDate lastStageActivity) { + super(plotId); + this.tutorialId = tutorialId; + this.uuid = UUID.fromString(uuid); + this.stageId = stageId; + this.isComplete = isComplete; + this.lastStageActivity = lastStageActivity; - DatabaseConnection.closeResultSet(rs); - } - return null; + tutorialConfig = ConfigUtil.getTutorialInstance().configs[tutorialId]; + TutorialPlotProvider.tutorialPlots.add(plotId, this); } - @Override - public int getTutorialID() throws SQLException { - if (tutorialId != -1) return tutorialId; - try (ResultSet rs = DatabaseConnection.createStatement("SELECT tutorial_id FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int id = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - tutorialId = id; - } - - DatabaseConnection.closeResultSet(rs); - } + public int getTutorialID() { return tutorialId; } - @Override - public int getStageID() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT stage_id FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int stage = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return stage; - } + public UUID getUUID() { + return uuid; + } - DatabaseConnection.closeResultSet(rs); - } - return -1; + public int getStageID() { + return stageId; } /** @@ -116,158 +88,66 @@ public int getStageID() throws SQLException { * * @param stageID stage id, 0 is the first stage */ - public void setStageID(int stageID) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots_tutorial SET stage_id = ? WHERE id = ?") - .setValue(stageID).setValue(this.ID).executeUpdate(); - setLastStageCompletionDate(Timestamp.valueOf(LocalDateTime.now())); - } - - @Override - public boolean isCompleted() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT is_completed FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - int isCompleted = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return isCompleted == 1; - } - - DatabaseConnection.closeResultSet(rs); + public boolean setStageID(int stageID) { + if (DataProvider.TUTORIAL_PLOT.setStageId(tutorialId, uuid.toString(), stageID)) { + this.stageId = stageID; + return true; } return false; } - /** - * Sets the completed status of the tutorial and updates the completion date. - */ - public void setCompleted() throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots_tutorial SET is_completed = ? WHERE id = ?") - .setValue(1).setValue(this.ID).executeUpdate(); - setCompletionDate(Timestamp.valueOf(LocalDateTime.now())); - } - - @Override - public Date getCreationDate() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT create_date FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - Date d = rs.getDate(1); - DatabaseConnection.closeResultSet(rs); - return d; - } - - DatabaseConnection.closeResultSet(rs); - } - return null; - } - - @Override - public Date getLastStageCompletionDate() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT last_stage_complete_date FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - Date d = rs.getDate(1); - DatabaseConnection.closeResultSet(rs); - return d; - } - - DatabaseConnection.closeResultSet(rs); - } - return null; + public boolean isComplete() { + return isComplete; } /** - * Sets the date when the last stage was completed. - * - * @param date date of the last stage completion + * Sets the completed status of the tutorial and updates the completion date. */ - private void setLastStageCompletionDate(Date date) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots_tutorial SET last_stage_complete_date = ? WHERE id = ?") - .setValue(date).setValue(this.ID).executeUpdate(); - } - - @Override - public Date getCompletionDate() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT complete_date FROM plotsystem_plots_tutorial WHERE id = ?") - .setValue(this.ID).executeQuery()) { - - if (rs.next()) { - Date d = rs.getDate(1); - DatabaseConnection.closeResultSet(rs); - return d; - } - - DatabaseConnection.closeResultSet(rs); + public boolean setComplete() { + if (DataProvider.TUTORIAL_PLOT.setComplete(tutorialId, uuid.toString())) { + this.isComplete = true; + return true; } - return null; - } - - /** - * Sets the date when the tutorial was completed. - * - * @param date date of the completion - */ - private void setCompletionDate(Date date) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots_tutorial SET complete_date = ? WHERE id = ?") - .setValue(date).setValue(this.ID).executeUpdate(); + return false; } @Override - public Builder getPlotOwner() throws SQLException { - if (plotOwner != null) return plotOwner; - plotOwner = Builder.byUUID(getPlayerUUID()); - return plotOwner; + public Builder getPlotOwner() { + return Builder.byUUID(uuid); } @Override @SuppressWarnings("unchecked") - public T getWorld() throws SQLException { - try { - if (onePlotWorld == null) onePlotWorld = new OnePlotWorld(this); - return (T) onePlotWorld; - } catch (SQLException ex) {PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex);} - return null; + public T getWorld() { + if (onePlotWorld == null) onePlotWorld = new OnePlotWorld(this); + return (T) onePlotWorld; } @Override - public List getOutline() throws SQLException, IOException { + public List getOutline() { String plotOutlines = tutorialConfig.getString(TutorialPaths.Beginner.PLOT_OUTLINES); - return getOutlinePoints(plotOutlines); + return getOutlinePoints(plotOutlines == null ? "" : plotOutlines); } - /** - * @deprecated Use {@link TutorialDataModel#getLastStageCompletionDate()} instead. - */ @Override - public Date getLastActivity() throws SQLException { - return getLastStageCompletionDate(); // Temporary to fix backwards compatibility + public LocalDate getLastActivity() { + return lastStageActivity; } - /** - * @deprecated Use {@link TutorialPlot#setLastStageCompletionDate(Date)} instead. - */ @Override - public void setLastActivity(boolean setNull) throws SQLException { - setLastStageCompletionDate(java.sql.Date.valueOf(LocalDate.now())); // Temporary to fix backwards compatibility + public boolean setLastActivity(boolean setNull) { + return true; } - /** - * @deprecated Use {@link TutorialDataModel#isCompleted()} instead. - */ @Override - public Status getStatus() throws SQLException { - return isCompleted() ? Status.completed : Status.unfinished; // Temporary to fix backwards compatibility + public Status getStatus() { + return isComplete ? Status.completed : Status.unfinished; } - /** - * @deprecated Use {@link TutorialPlot#setCompleted()} instead. - */ @Override - public void setStatus(@NotNull Status status) throws SQLException { - if (status == Status.completed) setCompleted(); // Temporary to fix backwards compatibility + public boolean setStatus(@NotNull Status status) { + if (status == Status.completed) return setComplete(); + return false; } @Override @@ -277,110 +157,30 @@ public PlotType getPlotType() { @Override public double getVersion() { - return 3; + return AbstractPlot.PLOT_VERSION; } @Override - protected File getSchematicFile(String fileName) { - File newSchem = Paths.get(PlotUtils.getDefaultSchematicPath(), "tutorials", fileName + ".schem").toFile(); - if (newSchem.exists()) return newSchem; - File oldSchem = Paths.get(PlotUtils.getDefaultSchematicPath(), "tutorials", fileName + ".schematic").toFile(); - if (oldSchem.exists()) return oldSchem; - + public byte[] getInitialSchematicBytes() { + File schematic; + String fileName = getTutorialID() + "-" + currentSchematicId + ".schem"; + schematic = Paths.get(PlotUtils.getDefaultSchematicPath(), "tutorials", fileName).toFile(); try { - FileUtils.copyInputStreamToFile(Objects.requireNonNull(PlotSystem.getPlugin().getResource("tutorial/schematics/" + fileName + ".schematic.gz")), oldSchem); + if (!schematic.exists()) FileUtils.copyInputStreamToFile(Objects.requireNonNull(PlotSystem.getPlugin() + .getResource("tutorial/schematics/" + fileName + ".schem.gz")), schematic); + return Files.readAllBytes(schematic.toPath()); } catch (IOException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while copying the schematic file!"), ex); } - return oldSchem; - } - - public File getOutlinesSchematic(int schematicId) { - try { - return getSchematicFile(getTutorialID() + "-" + schematicId); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - return null; - } - } - - @Override - public File getOutlinesSchematic() { - return getOutlinesSchematic(0); - } - - @Override - public File getEnvironmentSchematic() { - try { - return getSchematicFile(getTutorialID() + "-env"); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - return null; - } + return new byte[0]; } - - /** - * Adds a new tutorial plot to the database. - * - * @param UUID uuid of the player - * @param tutorialId id of the tutorial - * @return the new tutorial plot - */ - public static TutorialPlot addTutorialPlot(String UUID, int tutorialId) throws SQLException { - DatabaseConnection.createStatement("INSERT INTO plotsystem_plots_tutorial (player_uuid, tutorial_id) VALUES (?, ?)") - .setValue(UUID).setValue(tutorialId).executeUpdate(); - return getPlot(UUID, tutorialId); + public void setTutorialSchematic(int schematicId) { + currentSchematicId = schematicId; } - /** - * Gets a tutorial plot from the database. - * - * @param UUID uuid of the player - * @param tutorialId id of the tutorial - * @return the tutorial plot - */ - public static TutorialPlot getPlot(String UUID, int tutorialId) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots_tutorial WHERE player_uuid = ? AND tutorial_id = ?") - .setValue(UUID).setValue(tutorialId).executeQuery()) { - - if (rs.next()) { - int id = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - - return new TutorialPlot(id); - } - - DatabaseConnection.closeResultSet(rs); - } - return null; - } - - /** - * Gets all tutorials from the player. - * - * @param builderUUID uuid of the player - * @return list of tutorials - */ - public static List getPlots(UUID builderUUID) throws SQLException { - return listPlots(DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots_tutorial WHERE player_uuid = ?") - .setValue(builderUUID.toString()).executeQuery()); - } - - public static boolean isPlotCompleted(Player player, int tutorialId) throws SQLException { - TutorialPlot plot = TutorialPlot.getPlot(player.getUniqueId().toString(), tutorialId); - if (plot == null) return false; - return plot.isCompleted(); - } - - private static List listPlots(ResultSet rs) throws SQLException { - List plots = new ArrayList<>(); - - while (rs.next()) { - plots.add(new TutorialPlot(rs.getInt(1))); - } - - DatabaseConnection.closeResultSet(rs); - return plots; + public static boolean isInProgress(int tutorialId, UUID playerUUID) { + TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getById(tutorialId, playerUUID.toString()); + return plot == null || !plot.isComplete(); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java index 9d9737ae..1bdcc74f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -59,7 +59,8 @@ protected boolean init() { } public void generateOutlines(int schematicId) throws SQLException, IOException, WorldEditException { - generateOutlines(((TutorialPlot) plot).getOutlinesSchematic(schematicId), null); + ((TutorialPlot) plot).setTutorialSchematic(schematicId); + generateOutlines(); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index fabfbe0b..60d8a477 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,6 +26,8 @@ import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.database.providers.TutorialPlotProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.generator.TutorialPlotGenerator; @@ -49,6 +51,7 @@ import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; import java.util.UUID; +import java.util.concurrent.CompletableFuture; import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.Sound; import static net.kyori.adventure.text.Component.text; @@ -56,33 +59,42 @@ import static net.kyori.adventure.text.format.TextDecoration.BOLD; public abstract class AbstractPlotTutorial extends AbstractTutorial implements PlotTutorial { - protected TutorialPlot plot; + protected TutorialPlot tutorialPlot; private TutorialPlotGenerator plotGenerator; private boolean isPasteSchematic; - protected AbstractPlotTutorial(Player player, int tutorialId, int stageId) throws SQLException { - // TODO: Performance improvements base constructor - super(player, getPlot(player, tutorialId), tutorialId, stageId == -1 ? getPlot(player, tutorialId).getStageID() : stageId); + protected AbstractPlotTutorial(Player player, int tutorialId, int stageId) { + super(player, tutorialId, stageId); - plot = (TutorialPlot) tutorialDataModel; + CompletableFuture.runAsync(() -> { + String playerUUID = player.getUniqueId().toString(); + TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getById(tutorialId, playerUUID); + if (plot == null && DataProvider.TUTORIAL_PLOT.add(tutorialId, playerUUID)) + tutorialPlot = DataProvider.TUTORIAL_PLOT.getById(tutorialId, playerUUID); - // Check if tutorial plot is null - if (plot == null) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not load tutorial. Plot is null!")); - return; - } + // Check if tutorial plot is null + if (tutorialPlot == null) { + PlotSystem.getPlugin().getComponentLogger().error(text("Could not load tutorial. Plot is null!")); + return; + } - // Initialize tutorial worlds and stages - initTutorial(); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + // Initialize tutorial worlds and stages + initTutorial(); - // Start the tutorial - nextStage(); + // Start the tutorial + nextStage(); + }); + }).exceptionally(ex -> { + PlotSystem.getPlugin().getComponentLogger().error(text("Could not load tutorial."), ex); + return null; + }); } @Override protected TutorialNPC initNpc() { return new TutorialNPC( - "ps-tutorial-" + plot.getID(), + "ps-tutorial-" + tutorialPlot.getID(), ChatColor.GOLD + ChatColor.BOLD.toString() + PlotSystem.getPlugin().getConfig().getString(ConfigPaths.TUTORIAL_NPC_NAME), ChatColor.GRAY + "(" + LangUtil.getInstance().get(getPlayer(), LangPaths.Note.Action.RIGHT_CLICK) + ")", PlotSystem.getPlugin().getConfig().getString(ConfigPaths.TUTORIAL_NPC_TEXTURE), @@ -99,7 +111,7 @@ public void setStage(int stageId) { public void onPlotSchematicPaste(UUID playerUUID, int schematicId) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; try { - if (plotGenerator != null && plot.getWorld().isWorldGenerated() && plot.getWorld().isWorldLoaded()) { + if (plotGenerator != null && tutorialPlot.getWorld().isWorldGenerated() && tutorialPlot.getWorld().isWorldLoaded()) { plotGenerator.generateOutlines(schematicId); } } catch (SQLException | IOException | WorldEditException ex) { @@ -118,7 +130,7 @@ public void onPlotPermissionChange(UUID playerUUID, boolean isBuildingAllowed, b @Override protected AbstractStage getStage() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { - return getStages().get(getCurrentStage()).getDeclaredConstructor(Player.class, TutorialPlot.class).newInstance(getPlayer(), plot); + return getStages().get(getCurrentStage()).getDeclaredConstructor(Player.class, TutorialPlot.class).newInstance(getPlayer(), tutorialPlot); } @Override @@ -140,13 +152,9 @@ protected void prepareStage(PrepareStageAction action) { @Override public void saveTutorial(int stageId) { Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - try { - if (stageId >= stages.size()) { - if (!plot.isCompleted()) plot.setCompleted(); - } else if (stageId > plot.getStageID()) plot.setStageID(stageId); - } catch (SQLException ex) { - onException(ex); - } + if (stageId >= stages.size()) { + if (!tutorialPlot.isComplete()) tutorialPlot.setComplete(); + } else if (stageId > tutorialPlot.getStageID()) tutorialPlot.setStageID(stageId); }); } @@ -155,7 +163,7 @@ public void onSwitchWorld(UUID playerUUID, int tutorialWorldIndex) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; try { if (tutorialWorldIndex == 1 && (plotGenerator == null || !plotGenerator.getPlot().getWorld().isWorldGenerated())) { - plotGenerator = new TutorialPlotGenerator(plot, Builder.byUUID(playerUUID)); + plotGenerator = new TutorialPlotGenerator(tutorialPlot, Builder.byUUID(playerUUID)); onPlotSchematicPaste(playerUUID, ((AbstractPlotStage) currentStage).getInitSchematicId()); } super.onSwitchWorld(playerUUID, tutorialWorldIndex); @@ -177,11 +185,10 @@ public void onTutorialComplete(UUID playerUUID) { public void onTutorialStop(UUID playerUUID) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; super.onTutorialStop(playerUUID); - try { - if (plot != null) plot.getWorld().deleteWorld(); - } catch (SQLException ex) { - onException(ex); - } + if (tutorialPlot != null) tutorialPlot.getWorld().deleteWorld(); + int index = TutorialPlotProvider.tutorialPlots.indexOf(tutorialPlot); + TutorialPlotProvider.tutorialPlots.remove(tutorialPlot); + TutorialPlotProvider.freeTutorialPlotIds.add(index); } @Override @@ -190,22 +197,6 @@ public void onException(Exception ex) { super.onException(ex); } - /** - * Gets the tutorial plot for a player with a specific tutorial id. - * If player has not started the tutorial yet, a new plot will be created. - * - * @param player the player to get the plot for. - * @param tutorialId the tutorial id. - * @return the tutorial plot. - * @throws SQLException if a SQL error occurs. - */ - private static TutorialPlot getPlot(Player player, int tutorialId) throws SQLException { - Builder builder = Builder.byUUID(player.getUniqueId()); - TutorialPlot plot = TutorialPlot.getPlot(builder.getUUID().toString(), tutorialId); - if (plot == null) plot = TutorialPlot.addTutorialPlot(builder.getUUID().toString(), tutorialId); - return plot; - } - /** * Sends a message to the player when a new stage is unlocked. * diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java index cae4b01e..74a33cb0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -79,7 +79,6 @@ protected interface PrepareStageAction { private static final long PLAYER_INTERACTION_COOLDOWN = 1000; // The cooldown for player interactions in milliseconds - protected final TutorialDataModel tutorialDataModel; private final int tutorialId; private final UUID playerUUID; private final Player player; @@ -135,11 +134,10 @@ protected interface PrepareStageAction { */ protected abstract void prepareStage(PrepareStageAction action); - protected AbstractTutorial(Player player, TutorialDataModel tutorialDataModel, int tutorialId, int stageId) { + protected AbstractTutorial(Player player, int tutorialId, int stageId) { this.tutorialId = tutorialId; this.playerUUID = player.getUniqueId(); this.player = player; - this.tutorialDataModel = tutorialDataModel; if (stageId < 0) stageId = 0; currentStageIndex = stageId - 1; @@ -336,7 +334,7 @@ public static boolean isPlayerIsOnInteractCoolDown(UUID playerUUID) { * @return true if the tutorial was loaded successfully, otherwise false */ public static boolean loadTutorial(Player player, int tutorialId) { - return loadTutorialByStage(player, tutorialId, -1); + return loadTutorialByStage(player, tutorialId, 0); } /** diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java index 449af366..29e06118 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java index 9c6f1358..08a0425e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -62,22 +62,17 @@ import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class BeginnerTutorial extends AbstractPlotTutorial { - public BeginnerTutorial(Player player, int stageId) throws SQLException { + public BeginnerTutorial(Player player, int stageId) { super(player, TutorialCategory.BEGINNER.getId(), stageId); } @Override protected List initWorlds() { - try { - return Arrays.asList( - new TutorialWorld(getId(), 0, Utils.getSpawnLocation().getWorld().getName()), - new TutorialWorld(getId(), 1, plot.getWorld().getWorldName()), - new TutorialWorld(getId(), 2, Utils.getSpawnLocation().getWorld().getName()) - ); - } catch (SQLException ex) { - onException(ex); - } - return null; + return Arrays.asList( + new TutorialWorld(getId(), 0, Utils.getSpawnLocation().getWorld().getName()), + new TutorialWorld(getId(), 1, tutorialPlot.getWorld().getWorldName()), + new TutorialWorld(getId(), 2, Utils.getSpawnLocation().getWorld().getName()) + ); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java index 1467f52b..f6684a56 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java index ba52c30a..caec5485 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java index 52c3d1a9..f101e127 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialDataModel.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialDataModel.java deleted file mode 100644 index 57ce8c56..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialDataModel.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.system.tutorial; - -import java.sql.SQLException; -import java.util.Date; -import java.util.UUID; - -public interface TutorialDataModel { - /** - * Gets the ID of the individual tutorial from your storage system (database or config). - * - * @return id, negative if not set - */ - int getID(); - - /** - * Gets the UUID of the player who started the tutorial. The UUID is 36 characters long and contains 4 dashes. - * - * @return uuid of the player - */ - UUID getPlayerUUID() throws SQLException; - - /** - * The ID which is assigned to the tutorial. This ID is used to identify the tutorial in the system. - * - * @return tutorial id, negative if not set - */ - int getTutorialID() throws SQLException; - - /** - * Gets the highest stage id which the player has completed. The stage id starts at 0. - * - * @return stage id, negative if not set - */ - int getStageID() throws SQLException; - - /** - * Checks if the player has completed all stages of the tutorial. - * - * @return true if the player has completed the tutorial otherwise false - */ - boolean isCompleted() throws SQLException; - - /** - * Gets the date when the player created the tutorial. - * - * @return create date - */ - Date getCreationDate() throws SQLException; - - /** - * Gets the date when the player last completed a stage. - * - * @return last stage completion date - */ - Date getLastStageCompletionDate() throws SQLException; - - /** - * Gets the date when the player completed the tutorial. - * - * @return completion date - */ - Date getCompletionDate() throws SQLException; -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java index 85f13d7f..4e3e9f0e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal From 300770140ee5c7df392d71301c588fff5f8bd075 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 10 Feb 2025 00:46:12 +0100 Subject: [PATCH 031/175] =?UTF-8?q?fix=20remaining=20compiler=20issues!!?= =?UTF-8?q?=20=F0=9F=8E=89=F0=9F=8E=89=F0=9F=8E=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../providers/TutorialPlotProvider.java | 9 +- .../menus/tutorial/TutorialStagesMenu.java | 15 ++-- .../core/menus/tutorial/TutorialsMenu.java | 4 +- .../core/system/plot/TutorialPlot.java | 2 +- .../plot/generator/DefaultPlotGenerator.java | 12 ++- .../core/system/plot/world/CityPlotWorld.java | 40 ++++----- .../core/system/plot/world/OnePlotWorld.java | 82 +++++++------------ .../core/system/plot/world/PlotWorld.java | 18 ++-- .../system/tutorial/AbstractPlotTutorial.java | 4 +- .../tutorial/AbstractTutorialHologram.java | 2 +- .../system/tutorial/BeginnerTutorial.java | 35 ++++---- .../system/tutorial/stage/StageTimeline.java | 1 - .../stage/tasks/events/BuildEventTask.java | 3 +- .../stage/tasks/events/ChatEventTask.java | 3 +- .../tasks/events/TeleportPointEventTask.java | 4 +- .../events/commands/AbstractCmdEventTask.java | 3 +- .../utils/TutorialNPCTurnTracker.java | 2 +- 17 files changed, 111 insertions(+), 128 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index b32a1099..ec5fa93d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -40,7 +40,12 @@ public class TutorialPlotProvider { public static final List tutorialPlots = new ArrayList<>(); public static final LinkedList freeTutorialPlotIds = new LinkedList<>(); - public TutorialPlot getById(int tutorialId, String playerUUID) { + public TutorialPlot getById(int id) { + // TODO: implement + return null; + } + + public TutorialPlot getByTutorialId(int tutorialId, String playerUUID) { return tutorialPlots.stream().filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString() .equals(playerUUID)).findFirst() .orElseGet(() -> { @@ -63,7 +68,7 @@ public TutorialPlot getById(int tutorialId, String playerUUID) { } public boolean add(int tutorialId, String playerUUID) { - if (getById(tutorialId, playerUUID) != null) return false; + if (getByTutorialId(tutorialId, playerUUID) != null) return false; try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);")) { stmt.setInt(1, tutorialId); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java index 3a3200cc..7350bb48 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; @@ -46,8 +47,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; - import static net.md_5.bungee.api.ChatColor.*; public class TutorialStagesMenu extends AbstractMenu { @@ -125,13 +124,11 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { - try { - plot = TutorialPlot.getPlot(getMenuPlayer().getUniqueId().toString(), tutorialId); - if (plot != null) { - playerHighestStage = plot.getStageID(); - isTutorialCompleted = plot.isCompleted(); - } - } catch (SQLException ex) {Utils.logSqlException(ex);} + plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, getMenuPlayer().getUniqueId().toString()); + if (plot != null) { + playerHighestStage = plot.getStageID(); + isTutorialCompleted = plot.isComplete(); + } // Set tutorial stats item ItemBuilder tutorialItem = new ItemBuilder(Material.valueOf(tutorialItemName)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index 0b8c2833..5558082e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -93,7 +93,7 @@ protected void setPreviewItems() { protected void setMenuItemsAsync() { // Set tutorial items try { - plot = DataProvider.TUTORIAL_PLOT.getById(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()); + plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()); if (plot != null) isBeginnerTutorialCompleted = plot.isComplete(); // Set beginner tutorial item @@ -181,7 +181,7 @@ private ItemStack getTutorialItem(int tutorialId, String itemName, String title, constructTutorialItem(getMenuPlayer(), tutorialId, plot, new ItemStack(Material.valueOf(itemName)), title, desc); } - private static ItemStack constructTutorialItem(Player player, int tutorialId, TutorialPlot plot, ItemStack itemStack, String title, String desc) throws SQLException { + private static ItemStack constructTutorialItem(Player player, int tutorialId, TutorialPlot plot, ItemStack itemStack, String title, String desc) { // Create tutorial item lore int highestPlotStage = plot != null ? plot.getStageID() : 0; boolean isPlotCompleted = plot != null && plot.isComplete(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index ef9f4c6a..959f42e3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -180,7 +180,7 @@ public void setTutorialSchematic(int schematicId) { } public static boolean isInProgress(int tutorialId, UUID playerUUID) { - TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getById(tutorialId, playerUUID.toString()); + TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID.toString()); return plot == null || !plot.isComplete(); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 4de1a057..20f50250 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -39,6 +39,10 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.sk89q.worldedit.WorldEditException; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.function.mask.BlockTypeMask; +import com.sk89q.worldedit.function.mask.Mask; +import com.sk89q.worldedit.world.block.BlockTypes; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -91,7 +95,13 @@ protected boolean init() { @Override protected void generateOutlines() throws IOException, WorldEditException { - super.generateOutlines(); + if (plot instanceof Plot) { + byte[] completedSchematic = ((Plot) plot).getCompletedSchematic(); + if (completedSchematic != null) { + Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); + pasteSchematic(airMask, completedSchematic, world, true); + } else super.generateOutlines(); + } else super.generateOutlines(); // If the player is playing in his own world, then additionally generate the plot in the city world if (PlotWorld.isOnePlotWorld(world.getWorldName()) && plotVersion >= 3 && plot.getStatus() != Status.completed) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index da044d1f..19534cfe 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -24,25 +24,24 @@ package com.alpsbte.plotsystem.core.system.plot.world; -import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; -import com.fastasyncworldedit.core.FaweAPI; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.google.common.annotations.Beta; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import static net.kyori.adventure.text.Component.text; - public class CityPlotWorld extends PlotWorld { public CityPlotWorld(@NotNull Plot plot) { super("C-" + plot.getCity().getID(), plot); @@ -51,26 +50,22 @@ public CityPlotWorld(@NotNull Plot plot) { @Override public boolean teleportPlayer(@NotNull Player player) { if (super.teleportPlayer(player)) { - try { - player.playSound(player.getLocation(), Utils.SoundUtils.TELEPORT_SOUND, 1, 1); - player.setAllowFlight(true); - player.setFlying(true); + player.playSound(player.getLocation(), Utils.SoundUtils.TELEPORT_SOUND, 1, 1); + player.setAllowFlight(true); + player.setFlying(true); - if (getPlot() != null) { - player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getID())))); + if (getPlot() != null) { + player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getID())))); - Utils.updatePlayerInventorySlots(player); - PlotUtils.ChatFormatting.sendLinkMessages(getPlot(), player); + Utils.updatePlayerInventorySlots(player); + PlotUtils.ChatFormatting.sendLinkMessages(getPlot(), player); - if (getPlot().getPlotOwner().getUUID().equals(player.getUniqueId())) { - getPlot().setLastActivity(false); - } + if (getPlot().getPlotOwner().getUUID().equals(player.getUniqueId())) { + getPlot().setLastActivity(false); } - - return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } + + return true; } return false; } @@ -101,7 +96,12 @@ public int getPlotHeightCentered() throws IOException { */ @Beta public int getWorldHeight() throws IOException { - Clipboard clipboard = FaweAPI.load(getPlot().getOutlinesSchematic()); + Clipboard clipboard; + ByteArrayInputStream inputStream = new ByteArrayInputStream(getPlot().getInitialSchematicBytes()); + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { + clipboard = reader.read(); + } + int plotHeight = clipboard != null ? clipboard.getMinimumPoint().y() : MIN_WORLD_HEIGHT; // Plots created below min world height are not supported diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index a5387ae3..c40823fd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -37,12 +37,9 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.sk89q.worldedit.WorldEditException; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import java.io.File; import java.io.IOException; import java.sql.SQLException; @@ -78,31 +75,21 @@ public boolean loadWorld() { if (getPlot() == null || isWorldGenerated()) return super.loadWorld(); // Generate plot if it doesn't exist - try { - if (getPlot().getPlotType() == PlotType.TUTORIAL || - !((Plot) getPlot()).getCompletedSchematic().exists()) - generateWorld(TutorialPlotGenerator.class); - - new DefaultPlotGenerator(getPlot(), plotOwner, getPlot().getPlotType()) { - @Override - protected void generateOutlines(@NotNull File plotSchematic, @Nullable File environmentSchematic) throws SQLException, IOException, WorldEditException { - super.generateOutlines(((Plot) getPlot()).getCompletedSchematic(), environmentSchematic); - } - - @Override - protected boolean init() { - return true; - } - - @Override - protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { - getPlot().getPermissions().clearAllPerms(); - super.onComplete(true, false); - } - }; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + if (getPlot().getPlotType() == PlotType.TUTORIAL || ((Plot) getPlot()).getCompletedSchematic() == null) + generateWorld(TutorialPlotGenerator.class); + + new DefaultPlotGenerator(getPlot(), plotOwner, getPlot().getPlotType()) { + @Override + protected boolean init() { + return true; + } + + @Override + protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { + getPlot().getPermissions().clearAllPerms(); + super.onComplete(true, false); + } + }; if (!isWorldGenerated() || !isWorldLoaded()) { PlotSystem.getPlugin().getComponentLogger().warn(text("Could not regenerate world " + getWorldName() + " for plot " + getPlot().getID() + "!")); @@ -113,12 +100,8 @@ protected void onComplete(boolean failed, boolean unloadWorld) throws SQLExcepti @Override public boolean unloadWorld(boolean movePlayers) { - boolean isTutorialPlot = false; - try { - isTutorialPlot = getPlot().getPlotType() == PlotType.TUTORIAL; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + boolean isTutorialPlot; + isTutorialPlot = getPlot().getPlotType() == PlotType.TUTORIAL; if (getPlot() != null) { if (isTutorialPlot) return deleteWorld(); @@ -131,26 +114,21 @@ public boolean unloadWorld(boolean movePlayers) { public boolean teleportPlayer(@NotNull Player player) { if (!super.teleportPlayer(player)) return false; - try { - player.playSound(player.getLocation(), Utils.SoundUtils.TELEPORT_SOUND, 1, 1); - player.setAllowFlight(true); - player.setFlying(true); - - if (getPlot() == null) return true; - if (getPlot().getPlotType() != PlotType.TUTORIAL) { - player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getID())))); - PlotUtils.ChatFormatting.sendLinkMessages(getPlot(), player); - } - Utils.updatePlayerInventorySlots(player); - - if (!getPlot().getPlotOwner().getUUID().equals(player.getUniqueId())) return true; - getPlot().setLastActivity(false); + player.playSound(player.getLocation(), Utils.SoundUtils.TELEPORT_SOUND, 1, 1); + player.setAllowFlight(true); + player.setFlying(true); - return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (getPlot() == null) return true; + if (getPlot().getPlotType() != PlotType.TUTORIAL) { + player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getID())))); + PlotUtils.ChatFormatting.sendLinkMessages(getPlot(), player); } - return false; + Utils.updatePlayerInventorySlots(player); + + if (!getPlot().getPlotOwner().getUUID().equals(player.getUniqueId())) return true; + getPlot().setLastActivity(false); + + return true; } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index e08a5b1c..c9959878 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -27,14 +27,13 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; -import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.generator.AbstractPlotGenerator; import com.alpsbte.plotsystem.utils.Utils; -import com.fastasyncworldedit.core.FaweAPI; import com.onarandombox.MultiverseCore.MultiverseCore; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.extent.clipboard.Clipboard; +import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.managers.RegionManager; @@ -48,9 +47,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.sql.SQLException; import java.util.Locale; import static net.kyori.adventure.text.Component.text; @@ -160,7 +159,11 @@ public int getPlotHeight() throws IOException { @Override public int getPlotHeightCentered() throws IOException { if (plot != null) { - Clipboard clipboard = FaweAPI.load(plot.getOutlinesSchematic()); + Clipboard clipboard; + ByteArrayInputStream inputStream = new ByteArrayInputStream(plot.getInitialSchematicBytes()); + try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { + clipboard = reader.read(); + } if (clipboard != null) { return (int) clipboard.getRegion().getCenter().y() - clipboard.getMinimumPoint().y(); } @@ -246,11 +249,8 @@ public static boolean isCityPlotWorld(String worldName) { public static T getPlotWorldByName(String worldName) { if (isOnePlotWorld(worldName) || isCityPlotWorld(worldName)) { int id = Integer.parseInt(worldName.substring(2)); - try { - return worldName.toLowerCase().startsWith("t-") ? new TutorialPlot(id).getWorld() : DataProvider.PLOT.getPlotById(id).getWorld(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + AbstractPlot plot = worldName.toLowerCase().startsWith("t-") ? DataProvider.TUTORIAL_PLOT.getById(id) : DataProvider.PLOT.getPlotById(id); + return plot == null ? null : plot.getWorld(); } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index 60d8a477..78f685e3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -68,9 +68,9 @@ protected AbstractPlotTutorial(Player player, int tutorialId, int stageId) { CompletableFuture.runAsync(() -> { String playerUUID = player.getUniqueId().toString(); - TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getById(tutorialId, playerUUID); + TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID); if (plot == null && DataProvider.TUTORIAL_PLOT.add(tutorialId, playerUUID)) - tutorialPlot = DataProvider.TUTORIAL_PLOT.getById(tutorialId, playerUUID); + tutorialPlot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID); // Check if tutorial plot is null if (tutorialPlot == null) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java index 29e06118..529ba342 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java @@ -162,7 +162,7 @@ public void reload(UUID playerUUID) { if (readMoreId == -1 && markAsReadClickAction == null) return; setClickListener(clickEvent -> { if (!isMarkAsReadClicked && markAsReadClickAction != null) { - HologramLine line = clickEvent.getPage().getLines().get(clickEvent.getPage().getLines().size() - 1); + HologramLine line = clickEvent.getPage().getLines().getLast(); line.setText(getMarkAsReadClickedActionText()); clickEvent.getHologram().update(player); markAsReadClickAction.onClick(clickEvent); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java index 08a0425e..d20500ce 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java @@ -51,7 +51,6 @@ import org.bukkit.util.Vector; import java.io.IOException; -import java.sql.SQLException; import java.util.*; import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.*; @@ -143,7 +142,7 @@ protected List setHolograms() { public StageTimeline getTimeline() { return new StageTimeline(getPlayer()) .delay(Delay.TIMELINE_START) - .interactNPC(deserialize(getTasks().get(0))) + .interactNPC(deserialize(getTasks().getFirst())) .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) .sendChatMessage(deserialize(getMessages().get(1)), Sound.NPC_TALK, true) .sendChatMessage(deserialize(getMessages().get(2)), Sound.NPC_TALK, true) @@ -244,7 +243,7 @@ protected List setHolograms() { } @Override - public StageTimeline getTimeline() throws SQLException, IOException { + public StageTimeline getTimeline() throws IOException { return new StageTimeline(getPlayer()) .delay(Delay.TIMELINE_START) .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) @@ -255,8 +254,8 @@ public StageTimeline getTimeline() throws SQLException, IOException { text(Stage2.GOOGLE_MAPS, GRAY), ClickEvent.openUrl(getPlot().getGoogleMapsLink())) }, Sound.NPC_TALK, false) .delay(Delay.TASK_START) - .createHolograms(getHolograms().get(0)) - .addTeleportEvent(deserialize(getTasks().get(0)), getPlotPoints(getPlot()), 1, (teleportPoint, isCorrect) -> { + .createHolograms(getHolograms().getFirst()) + .addTeleportEvent(deserialize(getTasks().getFirst()), getPlotPoints(getPlot()), 1, (teleportPoint, isCorrect) -> { if (isCorrect) { setBlockAt(getPlayer().getWorld(), teleportPoint, Material.LIME_CONCRETE_POWDER); getPlayer().playSound(new Location(getPlayer().getWorld(), teleportPoint.getBlockX(), teleportPoint.getBlockY(), teleportPoint.getBlockZ()), @@ -306,7 +305,7 @@ public StageTimeline getTimeline() { .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) .sendChatMessage(deserialize(getMessages().get(1)), Sound.NPC_TALK, false) .delay(Delay.TASK_START) - .addTask(new WandCmdEventTask(getPlayer(), deserialize(getTasks().get(0)))) + .addTask(new WandCmdEventTask(getPlayer(), deserialize(getTasks().getFirst()))) .delay(Delay.TASK_END) .sendChatMessage(deserialize(getMessages().get(2)), Sound.NPC_TALK, true); } @@ -345,7 +344,7 @@ protected List setHolograms() { } @Override - public StageTimeline getTimeline() throws SQLException { + public StageTimeline getTimeline() { List buildingPoints = getPlotPoints(getPlot()); // Map building points to lines @@ -365,7 +364,7 @@ public StageTimeline getTimeline() throws SQLException { }, Sound.NPC_TALK, false) .delay(Delay.TASK_START) .addTask(new PlotPermissionChangeTask(getPlayer(), false, true)) - .addTask(new LineCmdEventTask(getPlayer(), deserialize(getTasks().get(0)), BASE_BLOCK, BASE_BLOCK_ID, buildingLinePoints, ((minPoint, maxPoint) -> { + .addTask(new LineCmdEventTask(getPlayer(), deserialize(getTasks().getFirst()), BASE_BLOCK, BASE_BLOCK_ID, buildingLinePoints, ((minPoint, maxPoint) -> { if (minPoint != null && maxPoint != null) { buildingLinePoints.remove(minPoint); @@ -424,8 +423,8 @@ public StageTimeline getTimeline() throws IOException { text(Stage2.GOOGLE_EARTH, GRAY), ClickEvent.openUrl(getPlot().getGoogleEarthLink())) }, Sound.NPC_TALK, false) .delay(Delay.TASK_START) - .createHolograms(getHolograms().get(0)); - stage.addPlayerChatEvent(deserialize(getTasks().get(0)), HEIGHT, HEIGHT_OFFSET, 3, (isCorrect, attemptsLeft) -> { + .createHolograms(getHolograms().getFirst()); + stage.addPlayerChatEvent(deserialize(getTasks().getFirst()), HEIGHT, HEIGHT_OFFSET, 3, (isCorrect, attemptsLeft) -> { if (!isCorrect && attemptsLeft > 0) { ChatMessageTask.sendTaskMessage(getPlayer(), new Object[]{deserialize(getMessages().get(6))}, false); getPlayer().playSound(getPlayer().getLocation(), Sound.ASSIGNMENT_WRONG, 1f, 1f); @@ -480,13 +479,13 @@ public StageTimeline getTimeline() { .delay(Delay.TIMELINE_START) .addTask(new PlotSchematicPasteTask(getPlayer(), 3)).delay(1) .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) - .createHolograms(deserialize(getTasks().get(0)), getHolograms().get(0), getHolograms().get(1)) + .createHolograms(deserialize(getTasks().getFirst()), getHolograms().get(0), getHolograms().get(1)) .delay(Delay.TASK_END) .deleteHolograms() .delay(2) .addTask(new PlotSchematicPasteTask(getPlayer(), 4)).delay(1) .sendChatMessage(deserialize(getMessages().get(3)), Sound.NPC_TALK, true) - .createHolograms(deserialize(getTasks().get(0)), getHolograms().get(2), getHolograms().get(3), getHolograms().get(4)) + .createHolograms(deserialize(getTasks().getFirst()), getHolograms().get(2), getHolograms().get(3), getHolograms().get(4)) .delay(Delay.TASK_END); } } @@ -528,7 +527,7 @@ public StageTimeline getTimeline() { .sendChatMessage(deserialize(getMessages().get(1)), Sound.NPC_TALK, true) .createHolograms(getHolograms().get(0), getHolograms().get(1)) .addTask(new PlotPermissionChangeTask(getPlayer(), true, false)) - .addTask(new BuildEventTask(getPlayer(), deserialize(getTasks().get(0)), getWindowBuildPoints(), (blockPos, isCorrect) -> { + .addTask(new BuildEventTask(getPlayer(), deserialize(getTasks().getFirst()), getWindowBuildPoints(), (blockPos, isCorrect) -> { if (isCorrect) { getPlayer().playSound(getPlayer().getLocation(), Sound.ASSIGNMENT_COMPLETED, 1f, 1f); } else { @@ -577,8 +576,8 @@ public StageTimeline getTimeline() { return new StageTimeline(getPlayer()) .delay(Delay.TIMELINE_START) .addTask(new PlotSchematicPasteTask(getPlayer(), 6)).delay(1) - .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) - .createHolograms(deserialize(getTasks().get(0)), getHolograms().get(0), getHolograms().get(1), getHolograms().get(2)) + .sendChatMessage(deserialize(getMessages().getFirst()), Sound.NPC_TALK, true) + .createHolograms(deserialize(getTasks().getFirst()), getHolograms().get(0), getHolograms().get(1), getHolograms().get(2)) .delay(Delay.TASK_END); } } @@ -618,8 +617,8 @@ public StageTimeline getTimeline() { return new StageTimeline(getPlayer()) .delay(Delay.TIMELINE_START) .addTask(new PlotSchematicPasteTask(getPlayer(), 7)).delay(1) - .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) - .createHolograms(deserialize(getTasks().get(0)), getHolograms().get(0), getHolograms().get(1)) + .sendChatMessage(deserialize(getMessages().getFirst()), Sound.NPC_TALK, true) + .createHolograms(deserialize(getTasks().getFirst()), getHolograms().get(0), getHolograms().get(1)) .delay(Delay.TASK_END) .deleteHolograms() .delay(2) @@ -642,7 +641,7 @@ public StageTimeline getTimeline() { * * @return list of building points as Vector */ - private static List getPlotPoints(TutorialPlot plot) throws SQLException { + private static List getPlotPoints(TutorialPlot plot) { // Read coordinates from config FileConfiguration config = ConfigUtil.getTutorialInstance().getBeginnerTutorial(); List plotPointsAsString = Arrays.asList( diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java index 8f67fc13..4725b18d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java @@ -37,7 +37,6 @@ import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.ChatMessageTask; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitRunnable; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java index 53042d3b..cd58c450 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java @@ -67,8 +67,7 @@ public void run() { @Override public void performEvent(Event event) { - if (event instanceof BlockPlaceEvent) { - BlockPlaceEvent buildEvent = (BlockPlaceEvent) event; + if (event instanceof BlockPlaceEvent buildEvent) { if (!buildEvent.canBuild()) return; Block placedBlock = buildEvent.getBlockPlaced(); Vector placedBlockVector = new Vector(placedBlock.getX(), placedBlock.getY(), placedBlock.getZ()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java index 078b7fd2..7a9f6e00 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java @@ -56,8 +56,7 @@ public void performTask() { @Override public void performEvent(Event event) { - if (event instanceof AsyncChatEvent) { - AsyncChatEvent chatEvent = (AsyncChatEvent) event; + if (event instanceof AsyncChatEvent chatEvent) { chatEvent.setCancelled(true); TextComponent message = (TextComponent) chatEvent.message(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java index 4194c8e9..10f05cba 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java @@ -69,9 +69,7 @@ public void run() { @Override public void performEvent(Event event) { - if (event instanceof PlayerTeleportEvent) { - PlayerTeleportEvent teleportEvent = (PlayerTeleportEvent) event; - + if (event instanceof PlayerTeleportEvent teleportEvent) { if (teleportPoints.isEmpty()) return; Location teleportLoc = teleportEvent.getTo(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java index ecfde9a1..97b7f3df 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java @@ -60,8 +60,7 @@ public void performTask() { @Override public void performEvent(Event event) { - if (event instanceof PlayerCommandPreprocessEvent) { - PlayerCommandPreprocessEvent cmdEvent = (PlayerCommandPreprocessEvent) event; + if (event instanceof PlayerCommandPreprocessEvent cmdEvent) { if (cmdEvent.getMessage().toLowerCase().startsWith(expectedCommand.toLowerCase())) { if (isCancelCmdEvent) cmdEvent.setCancelled(true); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java index d50e8b54..62a39707 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java @@ -29,7 +29,7 @@ import org.bukkit.Location; public class TutorialNPCTurnTracker implements Runnable { - public static int turnToPlayerDistance = FancyNpcsPlugin.get().getFancyNpcConfig().getTurnToPlayerDistance();; + public static int turnToPlayerDistance = FancyNpcsPlugin.get().getFancyNpcConfig().getTurnToPlayerDistance(); @Override public void run() { From c82604492c7b4a6fc20e14155d0fc17834bca329 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 10 Feb 2025 01:17:38 +0100 Subject: [PATCH 032/175] fix warnings --- README.md | 1 + .../plotsystem/commands/CommandManager.java | 2 +- .../commands/plot/CMD_Plot_Submit.java | 8 +-- .../commands/plot/CMD_Plot_Teleport.java | 12 +--- .../commands/plot/CMD_Plot_UndoSubmit.java | 8 +-- .../core/database/DataProvider.java | 19 +++---- .../database/providers/BuilderProvider.java | 1 + .../core/menus/PlotActionsMenu.java | 36 +++++------- .../plotsystem/core/menus/PlotMemberMenu.java | 11 +--- .../plotsystem/core/menus/ReviewPlotMenu.java | 2 +- .../core/menus/tutorial/TutorialsMenu.java | 32 +++++------ .../core/system/plot/AbstractPlot.java | 4 +- .../plotsystem/core/system/plot/Plot.java | 4 +- .../plot/generator/AbstractPlotGenerator.java | 2 +- .../plot/generator/DefaultPlotGenerator.java | 4 +- .../plot/generator/TutorialPlotGenerator.java | 4 +- .../core/system/plot/utils/PlotUtils.java | 56 +++++++++---------- .../core/system/plot/world/CityPlotWorld.java | 3 +- .../core/system/plot/world/IWorld.java | 3 +- .../core/system/plot/world/OnePlotWorld.java | 17 ++---- .../system/tutorial/AbstractPlotTutorial.java | 15 ++--- .../system/tutorial/stage/AbstractStage.java | 3 +- .../utils/TutorialNPCTurnTracker.java | 2 +- .../system/tutorial/utils/TutorialUtils.java | 6 +- 24 files changed, 99 insertions(+), 156 deletions(-) diff --git a/README.md b/README.md index 4dc8376f..f99c8c59 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,5 @@ +

diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java index 373e55c1..86b8c5c1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java @@ -41,7 +41,7 @@ public class CommandManager { - public final List baseCommands = new ArrayList() {{ + public final List baseCommands = new ArrayList<>() {{ // Default Commands add(new CMD_CancelChat()); add(new CMD_Companion()); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java index d6dd00fa..e105f143 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java @@ -41,7 +41,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.sql.SQLException; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; @@ -95,12 +94,7 @@ public void onCommand(CommandSender sender, String[] args) { Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - try { - PlotUtils.Actions.submitPlot(plot); - } catch (SQLException e) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); - } + PlotUtils.Actions.submitPlot(plot); if (plotMembers.isEmpty()) { // Plot was made alone langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), plot.getPlotOwner().getName()); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index c0db3428..a14c4146 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -42,11 +42,8 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.sql.SQLException; import java.util.concurrent.CompletableFuture; -import static net.kyori.adventure.text.Component.text; - public class CMD_Plot_Teleport extends SubCommand implements ICommand { public CMD_Plot_Teleport(BaseCommand baseCommand) { @@ -78,14 +75,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); return; } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - try { - new DefaultPlotGenerator(plot, builder); - } catch (SQLException e) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); - } - }); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new DefaultPlotGenerator(plot, builder)); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java index 5a3f4e89..17150862 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java @@ -41,7 +41,6 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.sql.SQLException; import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -85,12 +84,7 @@ public void onCommand(CommandSender sender, String[] args) { } Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - try { - PlotUtils.Actions.undoSubmit(plot); - } catch (SQLException e) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); - } + PlotUtils.Actions.undoSubmit(plot); sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.UNDID_SUBMISSION, plot.getID() + ""))); player.playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 1cd95976..79106efd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -24,18 +24,15 @@ package com.alpsbte.plotsystem.core.database; -import com.alpsbte.plotsystem.core.database.providers.BuildTeamProvider; -import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; -import com.alpsbte.plotsystem.core.database.providers.PlotProvider; import com.alpsbte.plotsystem.core.database.providers.*; public class DataProvider { - public static BuilderProvider BUILDER = new BuilderProvider(); - public static BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(); - public static PlotProvider PLOT = new PlotProvider(); - public static DifficultyProvider DIFFICULTY = new DifficultyProvider(); - public static CityProjectProvider CITY_PROJECT = new CityProjectProvider(); - public static CountryProvider COUNTRY = new CountryProvider(); - public static ServerProvider SERVER = new ServerProvider(); - public static TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); + public static final BuilderProvider BUILDER = new BuilderProvider(); + public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(); + public static final PlotProvider PLOT = new PlotProvider(); + public static final DifficultyProvider DIFFICULTY = new DifficultyProvider(); + public static final CityProjectProvider CITY_PROJECT = new CityProjectProvider(); + public static final CountryProvider COUNTRY = new CountryProvider(); + public static final ServerProvider SERVER = new ServerProvider(); + public static final TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index bb514078..b1549388 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -175,6 +175,7 @@ public Slot getFreeSlot(UUID uuid) { return null; } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean canReviewPlot(Builder builder, Plot plot) { // TODO: implement (check for build team) // no need to check for plot owner / plot members as this is handled separately diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 3f670c16..981c7971 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -43,8 +43,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; - import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; import static net.kyori.adventure.text.format.TextDecoration.BOLD; @@ -166,25 +164,21 @@ protected void setItemClickEventsAsync() { // Set click event for plot members item getMenu().getSlot(22).setClickHandler((clickPlayer, clickInformation) -> { - try { - if (plot.isReviewed()) return; - if (plot.getStatus() != Status.unfinished) { - clickPlayer.closeInventory(); - clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.CAN_ONLY_MANAGE_MEMBERS_UNFINISHED))); - return; - } - - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { - new PlotMemberMenu(plot, clickPlayer); - } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { - // Leave Plot - clickPlayer.closeInventory(); - plot.removePlotMember(Builder.byUUID(clickPlayer.getUniqueId())); - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.LEFT_PLOT, Integer.toString(plot.getID())))); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + if (plot.isReviewed()) return; + if (plot.getStatus() != Status.unfinished) { + clickPlayer.closeInventory(); + clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.CAN_ONLY_MANAGE_MEMBERS_UNFINISHED))); + return; + } + + FileConfiguration config = PlotSystem.getPlugin().getConfig(); + if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + new PlotMemberMenu(plot, clickPlayer); + } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { + // Leave Plot + clickPlayer.closeInventory(); + plot.removePlotMember(Builder.byUUID(clickPlayer.getUniqueId())); + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.LEFT_PLOT, Integer.toString(plot.getID())))); } }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index cad4220c..48cc4c02 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -44,7 +44,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; import java.util.List; import static net.kyori.adventure.text.Component.empty; @@ -132,13 +131,9 @@ protected void setItemClickEventsAsync() { getMenu().getSlot(i).setClickHandler((clickPlayer, clickInformation) -> { if (getMenu().getSlot(itemSlot).getItem(clickPlayer).equals(emptyMemberSlotItem)) return; Builder builder = builders.get(itemSlot - 12); - try { - plot.removePlotMember(builder); - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), - LangPaths.Message.Info.REMOVED_PLOT_MEMBER, builder.getName(), Integer.toString(plot.getID())))); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + plot.removePlotMember(builder); + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), + LangPaths.Message.Info.REMOVED_PLOT_MEMBER, builder.getName(), Integer.toString(plot.getID())))); reloadMenuAsync(); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java index acc753b6..390cf6ba 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java @@ -211,7 +211,7 @@ protected void setItemClickEventsAsync() { PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); return; } - } catch (IOException | SQLException | WorldEditException ex) { + } catch (IOException | WorldEditException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index 5558082e..7c003fae 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -50,8 +50,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; - import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; import static net.kyori.adventure.text.format.TextDecoration.BOLD; @@ -92,22 +90,18 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Set tutorial items - try { - plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()); - if (plot != null) isBeginnerTutorialCompleted = plot.isComplete(); - - // Set beginner tutorial item - getMenu().getSlot(22).setItem(getTutorialItem(TutorialCategory.BEGINNER.getId(), beginnerTutorialItemName, - LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.TUTORIAL_BEGINNER), - LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.TUTORIAL_BEGINNER)) - ); - - // Set back item - if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) || isBeginnerTutorialCompleted) - getMenu().getSlot(49).setItem(MenuItems.backMenuItem(getMenuPlayer())); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()); + if (plot != null) isBeginnerTutorialCompleted = plot.isComplete(); + + // Set beginner tutorial item + getMenu().getSlot(22).setItem(getTutorialItem(TutorialCategory.BEGINNER.getId(), beginnerTutorialItemName, + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.TUTORIAL_BEGINNER), + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.TUTORIAL_BEGINNER)) + ); + + // Set back item + if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) || isBeginnerTutorialCompleted) + getMenu().getSlot(49).setItem(MenuItems.backMenuItem(getMenuPlayer())); } @Override @@ -176,7 +170,7 @@ private void setTutorialClickEvent(int tutorialId, ClickType clickType) { getMenuPlayer().playSound(getMenuPlayer().getLocation(), Sound.ENTITY_ITEM_FRAME_ADD_ITEM, 0.8f, 0.8f); } - private ItemStack getTutorialItem(int tutorialId, String itemName, String title, String desc) throws SQLException { + private ItemStack getTutorialItem(int tutorialId, String itemName, String title, String desc) { return (tutorialId != TutorialCategory.BEGINNER.getId()) ? getAdvancedTutorialItem(getMenuPlayer()) : constructTutorialItem(getMenuPlayer(), tutorialId, plot, new ItemStack(Material.valueOf(itemName)), title, desc); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index f71af166..4a708f5f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -89,7 +89,7 @@ public int getID() { /** * @return the outline of the plot which contains all corner points of the polygon */ - public abstract List getOutline() throws IOException; + public abstract List getOutline(); /** * @return last date on which the plot owner teleported to the plot @@ -204,7 +204,7 @@ protected List getOutlinePoints(String outlinePoints) { /** * @return the outline of the polygon with one point per Block */ - public final List getBlockOutline() throws IOException { + public final List getBlockOutline() { if (this.blockOutline != null) return this.blockOutline; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 969ea6f7..17ddd46e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -194,7 +194,7 @@ public void setTotalScore(int score) throws SQLException { } } - public int getSharedScore() throws SQLException { + public int getSharedScore() { int score = getTotalScore(); if (score != -1 && !getPlotMembers().isEmpty()) { return (int) Math.floor(score / (getPlotMembers().size() + 1d)); @@ -284,7 +284,7 @@ public void addPlotMember(Builder member) { } } - public void removePlotMember(Builder member) throws SQLException { + public void removePlotMember(Builder member) { List members = getPlotMembers(); if (!members.isEmpty() && members.stream().anyMatch(m -> m.getUUID().equals(member.getUUID()))) { members.remove(members.stream().filter(m -> m.getUUID().equals(member.getUUID())).findFirst().orElse(null)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 45b3dec8..fa945698 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -171,7 +171,7 @@ protected void generateOutlines() throws IOException, WorldEditException { /** * Creates plot protection */ - protected void createPlotProtection() throws StorageException, IOException { + protected void createPlotProtection() throws StorageException { RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionManager regionManager = regionContainer.get(BukkitAdapter.adapt(world.getBukkitWorld())); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 20f50250..4c92cb28 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -57,11 +57,11 @@ public class DefaultPlotGenerator extends AbstractPlotGenerator { public static final Map playerPlotGenerationHistory = new HashMap<>(); - public DefaultPlotGenerator(CityProject city, PlotDifficulty plotDifficulty, Builder builder) throws SQLException { + public DefaultPlotGenerator(CityProject city, PlotDifficulty plotDifficulty, Builder builder) { this(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).get(Utils.getRandom().nextInt(DataProvider.PLOT.getPlots(city, plotDifficulty, Status.unclaimed).size())), builder); } - public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) throws SQLException { + public DefaultPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) { super(plot, builder); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java index 1bdcc74f..9f3504cb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java @@ -49,7 +49,7 @@ public class TutorialPlotGenerator extends AbstractPlotGenerator { private boolean buildingEnabled = false; private boolean worldEditEnabled = false; - public TutorialPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) throws SQLException { + public TutorialPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) { super(plot, builder, PlotType.TUTORIAL); } @@ -58,7 +58,7 @@ protected boolean init() { return true; } - public void generateOutlines(int schematicId) throws SQLException, IOException, WorldEditException { + public void generateOutlines(int schematicId) throws IOException, WorldEditException { ((TutorialPlot) plot).setTutorialSchematic(schematicId); generateOutlines(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 4041e35d..55e23a2c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -190,7 +190,7 @@ public static String getDefaultSchematicPath() { return Paths.get(PlotSystem.getPlugin().getDataFolder().getAbsolutePath(), "schematics") + File.separator; } - public static boolean savePlotAsSchematic(Plot plot) throws IOException, SQLException, WorldEditException { + public static boolean savePlotAsSchematic(Plot plot) throws IOException, WorldEditException { if (plot.getVersion() < 3) { PlotSystem.getPlugin().getComponentLogger().error(text("Saving schematics of legacy plots is no longer allowed!")); return false; @@ -301,7 +301,7 @@ public static void checkPlotsForLastActivity() { public static final class Actions { private Actions() {} - public static void submitPlot(@NotNull Plot plot) throws SQLException { + public static void submitPlot(@NotNull Plot plot) { plot.setStatus(Status.unreviewed); if (plot.getWorld().isWorldLoaded()) { @@ -318,7 +318,7 @@ public static void submitPlot(@NotNull Plot plot) throws SQLException { } } - public static void undoSubmit(@NotNull Plot plot) throws SQLException { + public static void undoSubmit(@NotNull Plot plot) { plot.setStatus(Status.unfinished); plot.getPermissions().addBuilderPerms(plot.getPlotOwner().getUUID()).save(); @@ -363,7 +363,7 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { if (plot.getWorld().isWorldLoaded()) plot.getWorld().unloadWorld(false); } } - } catch (SQLException | IOException | WorldEditException ex) { + } catch (IOException | WorldEditException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!"), ex); return false; } @@ -480,40 +480,36 @@ public static void tick() { } public static void showOutlines() { - try { - for (Player player : Bukkit.getOnlinePlayers()) { - Builder builder = Builder.byUUID(player.getUniqueId()); + for (Player player : Bukkit.getOnlinePlayers()) { + Builder builder = Builder.byUUID(player.getUniqueId()); - List plots = Cache.getCachedInProgressPlots(builder); - BlockVector2 playerPos2D = BlockVector2.at(player.getLocation().getX(), player.getLocation().getZ()); + List plots = Cache.getCachedInProgressPlots(builder); + BlockVector2 playerPos2D = BlockVector2.at(player.getLocation().getX(), player.getLocation().getZ()); - if (plots.isEmpty()) continue; + if (plots.isEmpty()) continue; - for (Plot plot : plots) { - if ((!plot.getWorld().getWorldName().equals(player.getWorld().getName())) || - (!plot.getPlotOwner().getPlotType().hasEnvironment() || plot.getVersion() <= 2)) { - continue; - } + for (Plot plot : plots) { + if ((!plot.getWorld().getWorldName().equals(player.getWorld().getName())) || + (!plot.getPlotOwner().getPlotType().hasEnvironment() || plot.getVersion() <= 2)) { + continue; + } - List points = plot.getBlockOutline(); + List points = plot.getBlockOutline(); - for (BlockVector2 point : points) - if (point.distanceSq(playerPos2D) < 50 * 50) { - if (!particleAPIEnabled) { - player.spawnParticle(Particle.FLAME, point.x(), player.getLocation().getY() + 1, point.z(), 1, 0.0, 0.0, 0.0, 0); - } else { - Location loc = new Location(player.getWorld(), point.x(), player.getLocation().getY() + 1, point.z()); - // create a particle packet - Object packet = particles.FLAME().packet(true, loc); + for (BlockVector2 point : points) + if (point.distanceSq(playerPos2D) < 50 * 50) { + if (!particleAPIEnabled) { + player.spawnParticle(Particle.FLAME, point.x(), player.getLocation().getY() + 1, point.z(), 1, 0.0, 0.0, 0.0, 0); + } else { + Location loc = new Location(player.getWorld(), point.x(), player.getLocation().getY() + 1, point.z()); + // create a particle packet + Object packet = particles.FLAME().packet(true, loc); - // send this packet to player - particles.sendPacket(player, packet); - } + // send this packet to player + particles.sendPacket(player, packet); } - } + } } - } catch (IOException ex) { - Utils.logSqlException(ex); } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index 19534cfe..b1c201b6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -38,7 +38,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -119,7 +118,7 @@ public int getWorldHeight() throws IOException { * * @return a list of players located on the plot */ - public List getPlayersOnPlot() throws SQLException { + public List getPlayersOnPlot() { List players = new ArrayList<>(); if (getPlot() != null && getPlot().getWorld().isWorldLoaded() && !getPlot().getWorld().getBukkitWorld().getPlayers().isEmpty()) { for (Player player : getPlot().getWorld().getBukkitWorld().getPlayers()) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java index e03f75de..bca5b9bf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java @@ -33,7 +33,6 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; -import java.sql.SQLException; public interface IWorld { /** @@ -96,7 +95,7 @@ public interface IWorld { * @return the origin Y value * @throws IOException if the outline schematic fails to load */ - int getPlotHeight() throws IOException, SQLException; + int getPlotHeight() throws IOException; /** * Calculates the centered Y value in the plot world diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index c40823fd..c79fabf9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -57,17 +57,12 @@ public OnePlotWorld(@NotNull AbstractPlot plot) { public boolean generateWorld(@NotNull Class generator) { if (isWorldGenerated()) return false; - try { - if (generator.isAssignableFrom(DefaultPlotGenerator.class)) { - new DefaultPlotGenerator(getPlot(), plotOwner); - } else if (generator.isAssignableFrom(TutorialPlotGenerator.class)) { - new TutorialPlotGenerator(getPlot(), plotOwner); - } else return false; - return true; - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - return false; + if (generator.isAssignableFrom(DefaultPlotGenerator.class)) { + new DefaultPlotGenerator(getPlot(), plotOwner); + } else if (generator.isAssignableFrom(TutorialPlotGenerator.class)) { + new TutorialPlotGenerator(getPlot(), plotOwner); + } else return false; + return true; } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index 78f685e3..98b2dd7c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -49,7 +49,6 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; -import java.sql.SQLException; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -114,7 +113,7 @@ public void onPlotSchematicPaste(UUID playerUUID, int schematicId) { if (plotGenerator != null && tutorialPlot.getWorld().isWorldGenerated() && tutorialPlot.getWorld().isWorldLoaded()) { plotGenerator.generateOutlines(schematicId); } - } catch (SQLException | IOException | WorldEditException ex) { + } catch (IOException | WorldEditException ex) { onException(ex); } } @@ -161,15 +160,11 @@ public void saveTutorial(int stageId) { @Override public void onSwitchWorld(UUID playerUUID, int tutorialWorldIndex) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; - try { - if (tutorialWorldIndex == 1 && (plotGenerator == null || !plotGenerator.getPlot().getWorld().isWorldGenerated())) { - plotGenerator = new TutorialPlotGenerator(tutorialPlot, Builder.byUUID(playerUUID)); - onPlotSchematicPaste(playerUUID, ((AbstractPlotStage) currentStage).getInitSchematicId()); - } - super.onSwitchWorld(playerUUID, tutorialWorldIndex); - } catch (SQLException ex) { - onException(ex); + if (tutorialWorldIndex == 1 && (plotGenerator == null || !plotGenerator.getPlot().getWorld().isWorldGenerated())) { + plotGenerator = new TutorialPlotGenerator(tutorialPlot, Builder.byUUID(playerUUID)); + onPlotSchematicPaste(playerUUID, ((AbstractPlotStage) currentStage).getInitSchematicId()); } + super.onSwitchWorld(playerUUID, tutorialWorldIndex); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java index 39d0f45d..384de008 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java @@ -29,7 +29,6 @@ import org.bukkit.entity.Player; import java.io.IOException; -import java.sql.SQLException; import java.util.List; public abstract class AbstractStage { @@ -87,7 +86,7 @@ protected AbstractStage(Player player, int id, int initWorldIndex) { * * @return timeline */ - public abstract StageTimeline getTimeline() throws IOException, SQLException; + public abstract StageTimeline getTimeline() throws IOException; public Player getPlayer() { return player; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java index 62a39707..dbfb21f9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java @@ -29,7 +29,7 @@ import org.bukkit.Location; public class TutorialNPCTurnTracker implements Runnable { - public static int turnToPlayerDistance = FancyNpcsPlugin.get().getFancyNpcConfig().getTurnToPlayerDistance(); + public static final int turnToPlayerDistance = FancyNpcsPlugin.get().getFancyNpcConfig().getTurnToPlayerDistance(); @Override public void run() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java index d99374d7..cdcdeecf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java @@ -38,10 +38,10 @@ import static net.kyori.adventure.text.format.NamedTextColor.*; public class TutorialUtils { - public static String TEXT_HIGHLIGHT_START = "", TEXT_HIGHLIGHT_END = ""; - public static String TEXT_CLICK_HIGHLIGHT = ""; + public static final String TEXT_HIGHLIGHT_START = "", TEXT_HIGHLIGHT_END = ""; + public static final String TEXT_CLICK_HIGHLIGHT = ""; - public static Component CHAT_PREFIX_COMPONENT = text("»", DARK_GRAY) + public static final Component CHAT_PREFIX_COMPONENT = text("»", DARK_GRAY) .append(text(" ", GRAY)); public static Component CHAT_TASK_PREFIX_COMPONENT = text("[", DARK_GRAY) .append(text("Tutorial", GOLD).append(text("] ", DARK_GRAY))); From e7f5e948c242783f39f7afe4ca0bde3d1ba53252 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 10 Feb 2025 21:38:55 +0100 Subject: [PATCH 033/175] Add a specific interval for rejected plots Implements #66. --- .../core/system/plot/utils/PlotUtils.java | 24 +++++++++++-------- .../plotsystem/utils/io/ConfigPaths.java | 15 +++--------- src/main/resources/config.yml | 6 ++++- 3 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 55e23a2c..6f81b9cf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -74,7 +74,10 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; import java.math.RoundingMode; import java.net.URISyntaxException; import java.nio.file.Paths; @@ -102,7 +105,7 @@ private PlotUtils() {} * @return the current plot of the player */ @Nullable - public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { + public static AbstractPlot getCurrentPlot(@NotNull Builder builder, Status... statuses) { if (builder.isOnline()) { String worldName = builder.getPlayer().getWorld().getName(); @@ -143,7 +146,7 @@ public static AbstractPlot getCurrentPlot(Builder builder, Status... statuses) { return null; } - public static boolean isPlayerOnPlot(AbstractPlot plot, Player player) { + public static boolean isPlayerOnPlot(@NotNull AbstractPlot plot, Player player) { if (plot.getWorld().isWorldLoaded() && plot.getWorld().getBukkitWorld().getPlayers().contains(player)) { Location playerLoc = player.getLocation(); return plot.getWorld().getProtectedRegion().contains(Vector3.toBlockPoint(playerLoc.getX(), playerLoc.getY(), playerLoc.getZ())); @@ -151,7 +154,7 @@ public static boolean isPlayerOnPlot(AbstractPlot plot, Player player) { return false; } - public static CuboidRegion getPlotAsRegion(AbstractPlot plot) throws IOException { + public static @Nullable CuboidRegion getPlotAsRegion(@NotNull AbstractPlot plot) throws IOException { Clipboard clipboard; try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(new ByteArrayInputStream(plot.getInitialSchematicBytes()))) { clipboard = reader.read(); @@ -186,11 +189,11 @@ public static byte[] getOutlinesSchematicBytes(AbstractPlot plot, World world) t return null; } - public static String getDefaultSchematicPath() { + public static @NotNull String getDefaultSchematicPath() { return Paths.get(PlotSystem.getPlugin().getDataFolder().getAbsolutePath(), "schematics") + File.separator; } - public static boolean savePlotAsSchematic(Plot plot) throws IOException, WorldEditException { + public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException, WorldEditException { if (plot.getVersion() < 3) { PlotSystem.getPlugin().getComponentLogger().error(text("Saving schematics of legacy plots is no longer allowed!")); return false; @@ -241,7 +244,7 @@ public static boolean savePlotAsSchematic(Plot plot) throws IOException, WorldEd return true; } - public static CompletableFuture convertTerraToPlotXZ(AbstractPlot plot, double[] terraCoords) throws IOException { + public static @Nullable CompletableFuture convertTerraToPlotXZ(@NotNull AbstractPlot plot, double[] terraCoords) throws IOException { // Load plot outlines schematic as clipboard Clipboard clipboard; ByteArrayInputStream inputStream = new ByteArrayInputStream(plot.getInitialSchematicBytes()); @@ -282,10 +285,11 @@ public static void checkPlotsForLastActivity() { List plots = DataProvider.PLOT.getPlots(Status.unfinished); FileConfiguration config = PlotSystem.getPlugin().getConfig(); long inactivityIntervalDays = config.getLong(ConfigPaths.INACTIVITY_INTERVAL); + long rejectedInactivityIntervalDays = (config.getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) != -1) ? config.getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) : inactivityIntervalDays; for (Plot plot : plots) { LocalDate lastActivity = plot.getLastActivity(); - if (lastActivity == null) continue; - if (lastActivity.plusDays(inactivityIntervalDays).isAfter(LocalDate.now())) continue; + long interval = (plot.isRejected()) ? rejectedInactivityIntervalDays : inactivityIntervalDays; + if (lastActivity == null || lastActivity.plusDays(interval).isAfter(LocalDate.now())) continue; Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (Actions.abandonPlot(plot)) { @@ -575,7 +579,7 @@ public static void sendLinkMessages(AbstractPlot plot, Player player) { }); } - public static void sendGroupTipMessage(Plot plot, Player player) { + public static void sendGroupTipMessage(@NotNull Plot plot, Player player) { if (plot.getPlotMembers().isEmpty()) { Component tc = text("» ", DARK_GRAY) .append(text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_PLAY_WITH_FRIENDS), GRAY)) diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java index 0cf83800..cd8473a1 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.utils.io; public abstract class ConfigPaths { + private ConfigPaths() {throw new IllegalStateException("Utility class");} // General Behaviour public static final String SPAWN_WORLD = "spawn-world"; @@ -32,13 +33,9 @@ public abstract class ConfigPaths { public static final String ENABLE_SCORE_REQUIREMENT = "enable-score-requirement"; public static final String DEV_MODE = "dev-mode"; public static final String INACTIVITY_INTERVAL = "inactivity-interval"; + public static final String REJECTED_INACTIVITY_INTERVAL = "rejected-inactivity-interval"; public static final String ENABLE_GROUP_SUPPORT = "enable-group-support"; - private static final String SYNC_FTP_FILES = "sync-ftp-files."; - public static final String SYNC_FTP_FILES_ENABLE = SYNC_FTP_FILES + "sff-enable"; - public static final String SYNC_FTP_FILES_INTERVAL = SYNC_FTP_FILES + "sync-interval"; - - // Database private static final String DATABASE = "database."; public static final String DATABASE_URL = DATABASE + "url"; @@ -46,7 +43,6 @@ public abstract class ConfigPaths { public static final String DATABASE_USERNAME = DATABASE + "username"; public static final String DATABASE_PASSWORD = DATABASE + "password"; - // Leaderboards private static final String HOLOGRAMS = "holograms."; public static final String SCORE_LEADERBOARD = "score-leaderboard"; @@ -60,7 +56,6 @@ public abstract class ConfigPaths { public static final String PLOTS_LEADERBOARD_Y = HOLOGRAMS + PLOTS_LEADERBOARD + ".pl-y"; public static final String PLOTS_LEADERBOARD_Z = HOLOGRAMS + PLOTS_LEADERBOARD + ".pl-z"; - private static final String DISPLAY_OPTIONS = "display-options."; public static final String DISPLAY_OPTIONS_INTERVAL = DISPLAY_OPTIONS + "interval"; public static final String DISPLAY_OPTIONS_SHOW_DAILY = DISPLAY_OPTIONS + "show-daily"; @@ -71,26 +66,22 @@ public abstract class ConfigPaths { public static final String DISPLAY_OPTIONS_ACTION_BAR_ENABLE = DISPLAY_OPTIONS + "action-bar-enable"; public static final String DISPLAY_OPTIONS_ACTION_BAR_RADIUS = DISPLAY_OPTIONS + "action-bar-radius"; - // FORMATTING private static final String CHAT_FORMAT = "chat-format."; public static final String CHAT_FORMAT_INFO_PREFIX = CHAT_FORMAT + "info-prefix"; public static final String CHAT_FORMAT_ALERT_PREFIX = CHAT_FORMAT + "alert-prefix"; - // COMMANDS public static final String EDITPLOT_ENABLED = "editplot-enabled"; public static final String BLOCKED_COMMANDS_BUILDERS = "blocked-commands-builders"; public static final String ALLOWED_COMMANDS_NON_BUILDERS = "allowed-commands-non-builders"; - // SHORTLINKS private static final String SHORTLINK = "shortlink."; public static final String SHORTLINK_ENABLE = SHORTLINK + "enable"; public static final String SHORTLINK_APIKEY = SHORTLINK + "apikey"; public static final String SHORTLINK_HOST = SHORTLINK + "host"; - // TUTORIALS private static final String TUTORIALS = "tutorials."; public static final String TUTORIAL_ENABLE = TUTORIALS + "tutorial-enable"; diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 69f4eeb9..bb305856 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -27,9 +27,13 @@ sync-ftp-files: sff-enable: false sync-interval: 3600 -# How many days of inactivity it will take before a claimed plot is automatically abandoned +# How many days of inactivity it will take before a claimed plot is automatically abandoned, 0 disables it inactivity-interval: 14 +# How many days of inactivity it will take before a rejected plots are automatically abandoned +# Use -1 to use the normal inactivity-interval, 0 disables it +rejected-inactivity-interval: -1 + # Enable or disable the Group System, that allows users to invite other Builders as members of their plot, # allowing them to build together. # NOTE: Score will be split by all participating members From e407f8774167822889590d0ef6f2dca411e75133 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sat, 15 Feb 2025 00:16:41 +0100 Subject: [PATCH 034/175] Make the owner head in /p members clickable There is a new translation, so the people know its clickable. Also, I fixed a bug with disabled tutorial config, where it would never be possible to add someone to a plot. I added a correct message for that. Improves #66. Resolves #133. --- .../plotsystem/commands/CMD_Companion.java | 9 +-- .../commands/review/CMD_EditFeedback.java | 5 +- .../plotsystem/core/EventListener.java | 58 +++++++++---------- .../plotsystem/core/menus/PlotMemberMenu.java | 17 +++++- .../core/menus/companion/CompanionMenu.java | 25 ++++---- .../core/system/plot/TutorialPlot.java | 14 ++++- .../core/system/plot/utils/PlotUtils.java | 5 +- .../plotsystem/utils/io/LangPaths.java | 4 +- .../alpsbte/plotsystem/utils/io/LangUtil.java | 12 ++-- src/main/resources/config.yml | 4 +- src/main/resources/lang/de_DE.yml | 4 +- src/main/resources/lang/en_GB.yml | 4 +- src/main/resources/lang/fr_FR.yml | 2 + src/main/resources/lang/ko_KR.yml | 4 +- src/main/resources/lang/pt_PT.yml | 4 +- src/main/resources/lang/ru_RU.yml | 4 +- src/main/resources/lang/zh_CN.yml | 4 +- src/main/resources/lang/zh_TW.yml | 2 + 18 files changed, 105 insertions(+), 76 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java index 9a3ef0a6..c892c437 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.commands; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; import com.alpsbte.plotsystem.core.menus.tutorial.TutorialStagesMenu; import com.alpsbte.plotsystem.core.menus.tutorial.TutorialsMenu; @@ -33,12 +32,10 @@ import com.alpsbte.plotsystem.core.system.tutorial.Tutorial; import com.alpsbte.plotsystem.core.system.tutorial.TutorialCategory; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -53,12 +50,10 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Player player = getPlayer(sender); if (player == null) return true; - FileConfiguration config = PlotSystem.getPlugin().getConfig(); Tutorial tutorial = AbstractTutorial.getActiveTutorial(player.getUniqueId()); if (tutorial != null) { new TutorialStagesMenu(player, tutorial.getId()); - } else if (config.getBoolean(ConfigPaths.TUTORIAL_ENABLE) && config.getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && - TutorialPlot.isInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId()) && player.hasPermission("plotsystem.tutorial")) { + } else if (TutorialPlot.isRequiredAndInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId()) && player.hasPermission("plotsystem.tutorial")) { new TutorialsMenu(player); } else CompanionMenu.open((Player) sender); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index f4184acb..5066d524 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -33,7 +33,6 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -52,7 +51,7 @@ public class CMD_EditFeedback extends BaseCommand { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { Player player = getPlayer(sender); if (player == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); + Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", RED)); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 029ad321..4dc0694f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,9 +26,13 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.menus.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; +import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; +import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.tutorial.AbstractPlotTutorial; @@ -36,18 +40,14 @@ import com.alpsbte.plotsystem.core.system.tutorial.Tutorial; import com.alpsbte.plotsystem.core.system.tutorial.TutorialCategory; import com.alpsbte.plotsystem.utils.PlotMemberInvitation; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.chat.ChatInput; -import com.alpsbte.plotsystem.utils.chat.PlayerInviteeChatInput; import com.alpsbte.plotsystem.utils.chat.PlayerFeedbackChatInput; +import com.alpsbte.plotsystem.utils.chat.PlayerInviteeChatInput; +import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.alpsbte.plotsystem.core.menus.ReviewMenu; -import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Status; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.flags.Flags; @@ -73,6 +73,7 @@ import org.bukkit.event.player.*; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; import java.sql.SQLException; import java.time.Duration; @@ -113,7 +114,7 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { } @EventHandler - public void onPlayerInteractEvent(PlayerInteractEvent event) { + public void onPlayerInteractEvent(@NotNull PlayerInteractEvent event) { if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.RIGHT_CLICK_AIR)) { if (event.getItem() != null && event.getItem().equals(CompanionMenu.getMenuItem(event.getPlayer()))) { event.getPlayer().performCommand("companion"); @@ -127,14 +128,14 @@ public void onPlayerInteractEvent(PlayerInteractEvent event) { } @EventHandler - public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { + public void onPlayerInteractAtEntity(@NotNull PlayerInteractAtEntityEvent event) { if (event.getRightClicked().getType().equals(EntityType.PLAYER) && event.getHand() == EquipmentSlot.HAND) { event.getPlayer().performCommand("plots " + Builder.byUUID(event.getRightClicked().getUniqueId()).getName()); } } @EventHandler - public void onPlayerQuitEvent(PlayerQuitEvent event) { + public void onPlayerQuitEvent(@NotNull PlayerQuitEvent event) { final World w = event.getPlayer().getWorld(); DefaultPlotGenerator.playerPlotGenerationHistory.remove(event.getPlayer().getUniqueId()); @@ -157,7 +158,7 @@ public void onPlayerQuitEvent(PlayerQuitEvent event) { } @EventHandler - public void onPlayerChangedWorldEvent(PlayerChangedWorldEvent event) { + public void onPlayerChangedWorldEvent(@NotNull PlayerChangedWorldEvent event) { Bukkit.getScheduler().scheduleSyncDelayedTask(PlotSystem.getPlugin(), () -> { PlotWorld plotWorld = PlotWorld.getPlotWorldByName(event.getFrom().getName()); if (plotWorld != null) plotWorld.unloadWorld(false); @@ -167,24 +168,21 @@ public void onPlayerChangedWorldEvent(PlayerChangedWorldEvent event) { } @EventHandler - public void onInventoryClickEvent(InventoryClickEvent event) { - if (event.getCurrentItem() != null && event.getCurrentItem().equals(CompanionMenu.getMenuItem((Player) event.getWhoClicked()))) { - event.setCancelled(true); - } else if (event.getCurrentItem() != null && event.getCurrentItem().equals(ReviewMenu.getMenuItem(((Player) event.getWhoClicked()).getPlayer()))) { + public void onInventoryClickEvent(@NotNull InventoryClickEvent event) { + if (event.getCurrentItem() != null && (event.getCurrentItem().equals(CompanionMenu.getMenuItem((Player) event.getWhoClicked())) || event.getCurrentItem().equals(ReviewMenu.getMenuItem(((Player) event.getWhoClicked()))))) { event.setCancelled(true); } - if (event.getWhoClicked().getGameMode() == GameMode.CREATIVE) { - if (event.getCursor().isSimilar(CompanionMenu.getMenuItem((Player) event.getWhoClicked())) || - event.getCursor().isSimilar(ReviewMenu.getMenuItem((Player) event.getWhoClicked()))) { + if (event.getWhoClicked().getGameMode() == GameMode.CREATIVE && (event.getCursor().isSimilar(CompanionMenu.getMenuItem((Player) event.getWhoClicked())) || + event.getCursor().isSimilar(ReviewMenu.getMenuItem((Player) event.getWhoClicked())))) { event.getView().setCursor(ItemStack.empty()); event.setCancelled(true); } - } + } @EventHandler - public void onlPlayerItemDropEvent(PlayerDropItemEvent event) { + public void onlPlayerItemDropEvent(@NotNull PlayerDropItemEvent event) { if (event.getItemDrop().getItemStack().equals(CompanionMenu.getMenuItem(event.getPlayer())) || event.getItemDrop().getItemStack().equals(ReviewMenu.getMenuItem(event.getPlayer()))) { event.setCancelled(true); @@ -192,7 +190,7 @@ public void onlPlayerItemDropEvent(PlayerDropItemEvent event) { } @EventHandler - public void onPlayerSwapHandItemsEvent(PlayerSwapHandItemsEvent event) { + public void onPlayerSwapHandItemsEvent(@NotNull PlayerSwapHandItemsEvent event) { if (event.getMainHandItem().equals(CompanionMenu.getMenuItem(event.getPlayer())) || event.getMainHandItem().equals(ReviewMenu.getMenuItem(event.getPlayer()))) event.setCancelled(true); if (event.getOffHandItem().equals(CompanionMenu.getMenuItem(event.getPlayer())) || @@ -200,7 +198,7 @@ public void onPlayerSwapHandItemsEvent(PlayerSwapHandItemsEvent event) { } @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerChatEvent(AsyncChatEvent event) throws SQLException { + public void onPlayerChatEvent(@NotNull AsyncChatEvent event) throws SQLException { UUID playerUUID = event.getPlayer().getUniqueId(); if (ChatInput.awaitChatInput.containsKey(playerUUID)) { event.setCancelled(true); @@ -218,7 +216,7 @@ public void onPlayerChatEvent(AsyncChatEvent event) throws SQLException { if (player == null) { event.getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance() .get(event.getPlayer(), LangPaths.Message.Error.PLAYER_NOT_FOUND))); - } else if (!player.isOnline() || TutorialPlot.isInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { + } else if (!player.isOnline()) { event.getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance() .get(event.getPlayer(), LangPaths.Message.Error.PLAYER_IS_NOT_ONLINE))); } else if (inviteeInput.getPlot().getPlotMembers().contains(Builder.byUUID(player.getUniqueId()))) { @@ -227,6 +225,9 @@ public void onPlayerChatEvent(AsyncChatEvent event) throws SQLException { } else if (inviteeInput.getPlot().getPlotOwner().getUUID().toString().equals(player.getUniqueId().toString())) { event.getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance() .get(event.getPlayer(), LangPaths.Message.Error.PLAYER_IS_PLOT_OWNER))); + } else if (TutorialPlot.isRequiredAndInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { + event.getPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance() + .get(event.getPlayer(), LangPaths.Message.Error.PLAYER_MISSING_TUTORIAL))); } else { new PlotMemberInvitation(Bukkit.getPlayer(messageComp.content()), inviteeInput.getPlot()); ChatInput.awaitChatInput.remove(playerUUID); @@ -239,11 +240,11 @@ public void onPlayerChatEvent(AsyncChatEvent event) throws SQLException { } @EventHandler - public void onLanguageChange(LanguageChangeEvent event) { + public void onLanguageChange(@NotNull LanguageChangeEvent event) { Utils.updatePlayerInventorySlots(event.getPlayer()); } - private void handleIronTrapdoorClick(PlayerInteractEvent event) { + private void handleIronTrapdoorClick(@NotNull PlayerInteractEvent event) { if (!event.getAction().equals(Action.RIGHT_CLICK_AIR) && !event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return; if (event.getHand() == EquipmentSlot.OFF_HAND) return; if (event.getPlayer().isSneaking()) return; @@ -266,7 +267,7 @@ private void handleIronTrapdoorClick(PlayerInteractEvent event) { state.update(); } - private void sendNotices(Player player, Builder builder) { + private void sendNotices(@NotNull Player player, Builder builder) { // Inform player about update if (player.hasPermission("plotsystem.admin") && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.CHECK_FOR_UPDATES) && PlotSystem.UpdateChecker.updateAvailable()) { player.sendMessage(Utils.ChatUtils.getInfoFormat("There is a new update for the Plot-System available. Check your console for more information!")); @@ -321,8 +322,7 @@ private void sendNotices(Player player, Builder builder) { // Start or notify the player if he has not completed the beginner tutorial yet (only if required) - if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && - TutorialPlot.isInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { + if (TutorialPlot.isRequiredAndInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { if (!player.hasPlayedBefore()) { Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> player.performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index 48cc4c02..bc1911f4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -40,9 +40,11 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; +import org.jetbrains.annotations.NotNull; import java.util.List; @@ -57,7 +59,7 @@ public class PlotMemberMenu extends AbstractMenu { private final ItemStack emptyMemberSlotItem = new ItemBuilder(Material.GREEN_STAINED_GLASS_PANE, 1).setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.GroupSystem.EMPTY_MEMBER_SLOTS), DARK_GREEN).decoration(BOLD, true)).build(); private List builders; - public PlotMemberMenu(Plot plot, Player menuPlayer) { + public PlotMemberMenu(@NotNull Plot plot, Player menuPlayer) { super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.MenuTitle.MANAGE_MEMBERS) + " | " + LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), menuPlayer); this.plot = plot; } @@ -102,7 +104,10 @@ protected void setMenuItemsAsync() { .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(plot.getPlotOwner().getUUID())) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER), GOLD, BOLD)) .setLore(new LoreBuilder() - .addLine(plot.getPlotOwner().getName()).build()) + .addLines(text(plot.getPlotOwner().getName()), + empty(), + text(Utils.ItemUtils.getActionFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.Action.CLICK_TO_OPEN_PLOTS_MENUE)))) + .build()) .build()); // Set plot member items @@ -125,6 +130,12 @@ protected void setMenuItemsAsync() { @Override protected void setItemClickEventsAsync() { + // Set click event for owner slot + getMenu().getSlot(10).setClickHandler((clickPlayer, clickInformation) -> { + clickPlayer.closeInventory(InventoryCloseEvent.Reason.OPEN_NEW); + new PlayerPlotsMenu(clickPlayer, plot.getPlotOwner()); + }); + // Set click event for member slots for (int i = 12; i < 15; i++) { int itemSlot = i; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 16458e42..7ce6d854 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -47,17 +47,14 @@ import com.alpsbte.plotsystem.utils.items.CustomHeads; import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.Menu; +import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Optional; +import java.util.*; import java.util.function.Consumer; import static net.kyori.adventure.text.Component.empty; @@ -66,6 +63,8 @@ import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class CompanionMenu { + private CompanionMenu() {throw new IllegalStateException("Utility class");} + public static boolean hasContinentView() { // TODO: make this run async return Arrays.stream(Continent.values()).map(continent -> DataProvider.COUNTRY.getCountriesByContinent(continent).size()).filter(count -> count > 0).count() > 1; @@ -100,7 +99,7 @@ public static void open(Player player) { * @param returnToMenu a lambda to call when needing to return to current menu * @return FooterItems indexed by slot number */ - public static HashMap getFooterItems(int startingSlot, Player player, Consumer returnToMenu) { + public static @NotNull Map getFooterItems(int startingSlot, Player player, Consumer returnToMenu) { HashMap items = new HashMap<>(); // Set builder utilities menu item items.put(startingSlot + 5, new FooterItem(BuilderUtilitiesMenu.getMenuItem(player), (clickPlayer, clickInformation) -> new BuilderUtilitiesMenu(clickPlayer))); @@ -218,8 +217,8 @@ public static class FooterItem { public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) { String nameText = LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); - TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true); - TextComponent slotDescriptionComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), NamedTextColor.GRAY); + TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), GOLD).decoration(TextDecoration.BOLD, true); + TextComponent slotDescriptionComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), GRAY); Material itemMaterial = Material.MAP; ArrayList lore = new LoreBuilder() @@ -234,16 +233,16 @@ public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPla String plotCityText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.CITY); String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); lore = new LoreBuilder() - .addLines(text(plotIdText + ": ", NamedTextColor.GRAY).append(text(plot.getID(), NamedTextColor.WHITE)), - text(plotCityText + ": ", NamedTextColor.GRAY).append(text(plot.getCity().getName(langPlayer), NamedTextColor.WHITE)), - text(plotDifficultyText + ": ", NamedTextColor.GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), NamedTextColor.WHITE)), + .addLines(text(plotIdText + ": ", GRAY).append(text(plot.getID(), WHITE)), + text(plotCityText + ": ", GRAY).append(text(plot.getCity().getName(langPlayer), WHITE)), + text(plotDifficultyText + ": ", GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), WHITE)), empty(), - statusComp.append(text(": Unassigned", NamedTextColor.GRAY)).decoration(TextDecoration.BOLD, true)) + statusComp.append(text(": Unassigned", GRAY)).decoration(TextDecoration.BOLD, true)) .build(); } return new ItemBuilder(itemMaterial, 1 + slotIndex) - .setName(text(nameText, NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) + .setName(text(nameText, GOLD).decoration(TextDecoration.BOLD, true)) .setLore(lore) .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index 959f42e3..14be51a7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -33,6 +33,7 @@ import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.TutorialPaths; import com.sk89q.worldedit.math.BlockVector2; @@ -40,11 +41,14 @@ import org.bukkit.configuration.file.FileConfiguration; import org.jetbrains.annotations.NotNull; -import java.io.*; +import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDate; -import java.util.*; +import java.util.List; +import java.util.Objects; +import java.util.UUID; import static net.kyori.adventure.text.Component.text; @@ -179,8 +183,12 @@ public void setTutorialSchematic(int schematicId) { currentSchematicId = schematicId; } - public static boolean isInProgress(int tutorialId, UUID playerUUID) { + public static boolean isInProgress(int tutorialId, @NotNull UUID playerUUID) { TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID.toString()); return plot == null || !plot.isComplete(); } + + public static boolean isRequiredAndInProgress(int tutorialId, UUID playerUUID) { + return PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE) && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) && isInProgress(tutorialId, playerUUID); + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 6f81b9cf..69be99dd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -173,7 +173,7 @@ public static boolean isPlotWorld(World world) { return PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().isMVWorld(world) && (PlotWorld.isOnePlotWorld(world.getName()) || PlotWorld.isCityPlotWorld(world.getName())); } - public static byte[] getOutlinesSchematicBytes(AbstractPlot plot, World world) throws IOException { + public static byte @Nullable [] getOutlinesSchematicBytes(@NotNull AbstractPlot plot, World world) throws IOException { Clipboard clipboard; ByteArrayInputStream inputStream = new ByteArrayInputStream(plot.getInitialSchematicBytes()); try (ClipboardReader reader = AbstractPlot.CLIPBOARD_FORMAT.getReader(inputStream)) { @@ -286,10 +286,11 @@ public static void checkPlotsForLastActivity() { FileConfiguration config = PlotSystem.getPlugin().getConfig(); long inactivityIntervalDays = config.getLong(ConfigPaths.INACTIVITY_INTERVAL); long rejectedInactivityIntervalDays = (config.getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) != -1) ? config.getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) : inactivityIntervalDays; + if (inactivityIntervalDays == -2 && rejectedInactivityIntervalDays == -2) return; for (Plot plot : plots) { LocalDate lastActivity = plot.getLastActivity(); long interval = (plot.isRejected()) ? rejectedInactivityIntervalDays : inactivityIntervalDays; - if (lastActivity == null || lastActivity.plusDays(interval).isAfter(LocalDate.now())) continue; + if (interval == -2 || lastActivity == null || lastActivity.plusDays(interval).isAfter(LocalDate.now())) continue; Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (Actions.abandonPlot(plot)) { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 080b8035..7c6afe26 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -216,7 +216,6 @@ private Note() {} public static final class Action { private Action() {} - private static final String ACTION_PREFIX = NOTES + "action."; public static final String READ = ACTION_PREFIX + "read"; public static final String READ_MORE = ACTION_PREFIX + "read-more"; @@ -239,6 +238,7 @@ private Action() {} public static final String CLICK_TO_SHOW_PLOTS = ACTION_PREFIX + "click-to-show-plots"; public static final String CLICK_TO_PLAY_WITH_FRIENDS = ACTION_PREFIX + "click-to-play-with-friends"; public static final String TUTORIAL_SHOW_STAGES = ACTION_PREFIX + "tutorial-show-stages"; + public static final String CLICK_TO_OPEN_PLOTS_MENUE = ACTION_PREFIX + "click-to-open-plots-menu"; } } @@ -288,7 +288,6 @@ private Info() {} public static final class Error { private Error() {} - private static final String ERROR_PREFIX = MESSAGE_PREFIX + "error."; public static final String PLOT_DOES_NOT_EXIST = ERROR_PREFIX + "plot-does-not-exist"; public static final String PLOT_EITHER_UNCLAIMED_OR_UNREVIEWED = ERROR_PREFIX + "plot-either-unclaimed-or-unreviewed"; @@ -316,6 +315,7 @@ private Error() {} public static final String PLAYER_INVITE_TO_REJECTED = ERROR_PREFIX + "player-invite-to-rejected"; public static final String PLAYER_NEEDS_TO_BE_ON_PLOT = ERROR_PREFIX + "player-needs-to-be-on-plot"; public static final String PLAYER_NEEDS_HIGHER_SCORE = ERROR_PREFIX + "player-needs-higher-score"; + public static final String PLAYER_MISSING_TUTORIAL = MESSAGE_PREFIX + "player-missing-tutorial"; public static final String ERROR_OCCURRED = ERROR_PREFIX + "error-occurred"; public static final String COMMAND_DISABLED = ERROR_PREFIX + "command-disabled"; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java index 35457a63..5f923cf2 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java @@ -39,13 +39,13 @@ public class LangUtil extends LanguageUtil { public static void init() { if (langUtilInstance != null) return; LangLibAPI.register(PlotSystem.getPlugin(), new LanguageFile[]{ - new LanguageFile(Language.en_GB, 2.2), - new LanguageFile(Language.de_DE, 2.2, "de_AT", "de_CH"), + new LanguageFile(Language.en_GB, 2.3), + new LanguageFile(Language.de_DE, 2.3, "de_AT", "de_CH"), new LanguageFile(Language.fr_FR, 2.3, "fr_CA"), - new LanguageFile(Language.pt_PT, 2.2, "pt_BR"), - new LanguageFile(Language.ko_KR, 2.2), - new LanguageFile(Language.ru_RU, 2.2, "ba_RU", "tt_RU"), - new LanguageFile(Language.zh_CN, 2.2), + new LanguageFile(Language.pt_PT, 2.3, "pt_BR"), + new LanguageFile(Language.ko_KR, 2.3), + new LanguageFile(Language.ru_RU, 2.3, "ba_RU", "tt_RU"), + new LanguageFile(Language.zh_CN, 2.3), new LanguageFile(Language.zh_TW, 2.3, "zh_HK"), }); langUtilInstance = new LangUtil(); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index bb305856..7372760a 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -27,11 +27,11 @@ sync-ftp-files: sff-enable: false sync-interval: 3600 -# How many days of inactivity it will take before a claimed plot is automatically abandoned, 0 disables it +# How many days of inactivity it will take before a claimed plot is automatically abandoned, -2 disables it inactivity-interval: 14 # How many days of inactivity it will take before a rejected plots are automatically abandoned -# Use -1 to use the normal inactivity-interval, 0 disables it +# Use -1 to use the normal inactivity-interval, -2 disables it rejected-inactivity-interval: -1 # Enable or disable the Group System, that allows users to invite other Builders as members of their plot, diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index 76d857ff..b147a293 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6Klicke hier, §aum deine Plots anzuzeigen..." click-to-play-with-friends: "§7Willst du mit deinen Freunden spielen? §6Klicke hier..." tutorial-show-stages: 'Stages Anzeigen' + click-to-open-plots-menu: 'Klicke hier, um das Plot Menü zu öffnen...' #----------------------------------------------------- #| Messages #----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0} hat deine Einladung abgelehnt.' player-needs-to-be-on-plot: "Um dies zu nutzen musst du auf einem Plot sein!" player-needs-higher-score: "Du benötigst einen höheren Punktestand, um in diesem Schwierigkeitsgrad zu bauen." + player-missing-tutorial: "Der Spieler muss zuerst das Tutorial abschließen, um hinzugefügt zu werden!" error-occurred: "Ein Fehler ist aufgetreten! Bitte versuche es erneut!" command-disabled: "Dieser Befehl ist deaktiviert!" no-plots-left: "Für diese Stadt gibt es keine freien Plots mehr. Bitte wähle einen anderen Ort." @@ -389,4 +391,4 @@ tutorials: stage-10-tasks: - 'Lies alle Tipps auf dem Plot und markiere sie als gelesen.' #NOTE: Do not change -config-version: 2.2 +config-version: 2.3 diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index bd6325db..ef40e926 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6Click Here §ato show your plots..." click-to-play-with-friends: "§7Want to play with your friends? §6Click Here..." tutorial-show-stages: 'Show Stages' + click-to-open-plots-menu: 'Click to open the plots menu...' # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0} has rejected your invitation.' player-needs-to-be-on-plot: "You need to be on a plot in order to use this!" player-needs-higher-score: "You need a higher score to build in this difficulty level." + player-missing-tutorial: "The player must first complete the tutorial to be added to the plot!" error-occurred: "An error occurred! Please try again!" command-disabled: "This command is disabled!" no-plots-left: "This city project does not have any more plots left. Please select another project." @@ -389,4 +391,4 @@ tutorials: stage-10-tasks: - 'Read all tips on the plot and mark them as read.' # NOTE: Do not change -config-version: 2.2 +config-version: 2.3 diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index d50ea3ca..8a534a00 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6Cliquez ici §apour afficher vos tracés..." click-to-play-with-friends: "§7Vous voulez jouer avec vos amis? §6Cliquez ici..." tutorial-show-stages: 'Montrer les étapes' + click-to-open-plots-menu: 'Cliquez pour ouvrir le menu des parcelles...' #----------------------------------------------------- #| Messages #----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0} a rejeté votre invitation.' player-needs-to-be-on-plot: "Vous devez être sur un terrain pour pouvoir l'utiliser!" player-needs-higher-score: "Vous avez besoin d'un score plus élevé pour intégrer ce niveau de difficulté." + player-missing-tutorial: "Le joueur doit d'abord terminer le tutoriel pour être intégré à l'intrigue!" error-occurred: "Une erreur s'est produite! Veuillez réessayer!" command-disabled: "Cette commande est désactivée!" no-plots-left: "Ce projet de ville n'a plus de parcelles restantes. Veuillez sélectionner un autre projet." diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index 4b72f2b0..f5e11ed8 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6여기§a를 클릭해 자신의 플롯들을 확인하세요!" click-to-play-with-friends: "§7친구와 플레이하시려면 §6여기§7를 클릭하세요!" tutorial-show-stages: 'Show Stages' + click-to-open-plots-menu: "클릭하여 플롯 메뉴 열기..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0} has rejected your invitation.' player-needs-to-be-on-plot: "플롯에서만 사용할 수 있습니다!" player-needs-higher-score: "해당 난이도에서 건축하시려면 더 높은 점수가 필요합니다." + player-missing-tutorial: "플레이어는 먼저 튜토리얼을 완료해야 플롯에 추가할 수 있습니다!" error-occurred: "에러 발생! 다시 시도해주세요!" command-disabled: "비활성화된 커맨드입니다!" no-plots-left: "이 도시 프로젝트에 남아있는 플롯이 없습니다. 다른 프로젝트를 선택해주세요." @@ -389,4 +391,4 @@ tutorials: stage-10-tasks: - 'Read all tips on the plot and mark them as read.' # NOTE: Do not change -config-version: 2.2 +config-version: 2.3 diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index 2d16775c..edb66b6c 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6Clique aqui §apara mostrar seus terrenos..." click-to-play-with-friends: "§7Quer jogar com seus amigos? §6Clique aqui..." tutorial-show-stages: 'Show Stages' + click-to-open-plots-menu: 'Clique para abrir o menu de parcelas...' # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0} has rejected your invitation.' player-needs-to-be-on-plot: "Você precisa estar em um terreno para usar isso!" player-needs-higher-score: "Você precisa de uma pontuação mais alta para construir neste nível de dificuldade." + player-missing-tutorial: "O jogador tem de completar o tutorial primeiro, para ser adicionado ao enredo!" error-occurred: "Um erro ocorreu! Por favor, tente novamente!" command-disabled: "Este comando está desabilitado!" no-plots-left: "Este projeto da cidade não tem mais terrenos. Por favor, Selecione outro projeto." @@ -389,4 +391,4 @@ tutorials: stage-10-tasks: - 'Read all tips on the plot and mark them as read.' # NOTE: Do not change -config-version: 2.2 +config-version: 2.3 diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index f6ee3075..640a78cf 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6Нажмите,чтобы показать ваши участки..." click-to-play-with-friends: "§7Хотите играть с друзьями? §6Нажмите здесь..." tutorial-show-stages: 'Show Stages' + click-to-open-plots-menu: "Нажмите, чтобы открыть меню участков..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0} has rejected your invitation.' player-needs-to-be-on-plot: "Вам нужно быть на участке чтобы использовать это!" player-needs-higher-score: "Вам нужна более высокая оценка чтобы строить на этом уровне сложности." + player-missing-tutorial: "Чтобы стать участником сюжета, игрок должен сначала пройти обучение!" error-occurred: "Произошла ошибка! Пожалуйста, попробуйте снова!" command-disabled: "Эта команда отключена!!" no-plots-left: "У этого градостроительного проекта больше не осталось участков. Пожалуйста, выберите другой проект." @@ -389,4 +391,4 @@ tutorials: stage-10-tasks: - 'Read all tips on the plot and mark them as read.' # NOTE: Do not change -config-version: 2.2 +config-version: 2.3 diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 4428f0c9..03a20d2c 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -198,6 +198,7 @@ note: click-to-show-plots: "§6点击此区 §a显示你的建地..." click-to-play-with-friends: "§7想和你的朋友一起玩吗? §6点击此区..." tutorial-show-stages: 'Show Stages' + click-to-open-plots-menu: "点击此区 显示你的建地..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -261,6 +262,7 @@ message: player-invite-to-rejected: '{0} has rejected your invitation.' player-needs-to-be-on-plot: "你需要在一个建地上才能使用它! " player-needs-higher-score: "你需要更高的积分来才能在这个难度度建设。" + player-missing-tutorial: "玩家必須先完成教學才能加入劇情!" error-occurred: "发生错误!请再次尝试!" command-disabled: "此命令已禁用!" no-plots-left: "此城市计画区没有剩余更多建地了。请选择其他计画区。" @@ -390,4 +392,4 @@ tutorials: stage-10-tasks: - 'Read all tips on the plot and mark them as read.' # NOTE: Do not change -config-version: 2.2 +config-version: 2.3 diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index fc0b4681..5c6dc3c7 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -197,6 +197,7 @@ note: click-to-show-plots: "§6點擊此處§a顯示你的建地..." click-to-play-with-friends: "§7想和你的朋友一起玩嗎?§6點擊此處..." tutorial-show-stages: '顯示階段' + click-to-open-plots-menu: '點擊以開啟建地選單...' # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -260,6 +261,7 @@ message: player-invite-to-rejected: '{0}否決了你的邀請。' player-needs-to-be-on-plot: "你需要在一個建地上才能使用它!" player-needs-higher-score: "你需要更高的積分來才能在這個難度下建設。" + player-missing-tutorial: "玩家必须先完成教程,才能加入剧情!" error-occurred: "發生錯誤!請再次嘗試!" command-disabled: "此指令已被禁用!" no-plots-left: "此城市計畫區沒有剩餘更多建地了。請選擇其他計畫區。" From 0c1870eb471ae0b44617aa0f3eda8e820860c13c Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 15 Feb 2025 22:27:52 +0100 Subject: [PATCH 035/175] add database related values to language files --- pom.xml | 7 ------ .../core/menus/companion/CompanionMenu.java | 2 +- .../plotsystem/core/system/CityProject.java | 17 +++++++------ .../plotsystem/core/system/Country.java | 9 +++---- .../plotsystem/core/system/Difficulty.java | 7 ++++++ .../com/alpsbte/plotsystem/utils/Utils.java | 8 +++---- .../plotsystem/utils/io/LangPaths.java | 10 ++++++++ .../alpsbte/plotsystem/utils/io/LangUtil.java | 16 ++++++------- src/main/resources/lang/de_DE.yml | 24 ++++++++++++++++++- src/main/resources/lang/en_GB.yml | 24 ++++++++++++++++++- src/main/resources/lang/fr_FR.yml | 24 ++++++++++++++++++- src/main/resources/lang/ko_KR.yml | 24 ++++++++++++++++++- src/main/resources/lang/pt_PT.yml | 24 ++++++++++++++++++- src/main/resources/lang/ru_RU.yml | 24 ++++++++++++++++++- src/main/resources/lang/zh_CN.yml | 24 ++++++++++++++++++- src/main/resources/lang/zh_TW.yml | 24 ++++++++++++++++++- 16 files changed, 225 insertions(+), 43 deletions(-) diff --git a/pom.xml b/pom.xml index f94c04d9..784d72b0 100644 --- a/pom.xml +++ b/pom.xml @@ -164,13 +164,6 @@ 4.0.3 compile - - - org.apache.commons - commons-vfs2 - 2.4 - compile - commons-net diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 7ce6d854..381931aa 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -153,7 +153,7 @@ public static ItemStack getDifficultyItem(Player player, PlotDifficulty selected .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.PLOT_DIFFICULTY), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() .emptyLine() - .addLines(selectedPlotDifficulty != null ? Utils.ItemUtils.getFormattedDifficulty(selectedPlotDifficulty) : text(LangUtil.getInstance().get(player, LangPaths.Difficulty.AUTOMATIC), WHITE).decoration(BOLD, true), + .addLines(selectedPlotDifficulty != null ? Utils.ItemUtils.getFormattedDifficulty(selectedPlotDifficulty, player) : text(LangUtil.getInstance().get(player, LangPaths.Difficulty.AUTOMATIC), WHITE).decoration(BOLD, true), selectedPlotDifficulty != null ? text(LangUtil.getInstance().get(player, LangPaths.Difficulty.SCORE_MULTIPLIER) + ": ", GRAY).append(text("x" + DataProvider.DIFFICULTY.getMultiplier(selectedPlotDifficulty), WHITE)) : empty()) .emptyLine() .addLine(text(LangUtil.getInstance().get(player, LangPaths.MenuDescription.PLOT_DIFFICULTY), GRAY)) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index af4f071f..c1e5f4c1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -35,12 +35,13 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.sql.SQLException; import java.util.ArrayList; +import java.util.List; import java.util.concurrent.ExecutionException; import static net.kyori.adventure.text.Component.text; @@ -94,17 +95,15 @@ public boolean setVisible(boolean isVisible) { } public String getName(Player player) { - // TODO: implement (get from language file) - return "CityProject WIP"; + return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + ID + ".name"); } public String getDescription(Player player) { - // TODO: implement (get from language file) - return "Description WIP"; + return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + ID + ".description"); } - public ArrayList getDescriptionComponents(Player player) { - ArrayList descriptionLines = new ArrayList<>(); + public List getDescriptionComponents(Player player) { + ArrayList descriptionLines = new ArrayList<>(); for (String line : getDescription(player).split("%newline%")) descriptionLines.add(text(line)); return descriptionLines; } @@ -128,7 +127,7 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { return new ItemBuilder(cpItem) .setName(text(getName(player), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() - .addLines(true, getDescription(player)) + .addLines(getDescriptionComponents(player)) .emptyLine() .addLine(text(plotsOpen, GOLD) .append(text(" " + LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_OPEN) + " ", GRAY)) @@ -141,7 +140,7 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { .append(text(" " + LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_COMPLETED), GRAY))) .emptyLine() .addLine(plotsUnclaimed != 0 - ? Utils.ItemUtils.getFormattedDifficulty(plotDifficulty) + ? Utils.ItemUtils.getFormattedDifficulty(plotDifficulty, player) : text(LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_NO_PLOTS_AVAILABLE), WHITE).decoration(BOLD, true)) .build()) .build(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index e73ba5a2..5c051b96 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -27,6 +27,8 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Nullable; @@ -51,10 +53,6 @@ public Country(String code, Continent continent, String material, String customM public String getCode() {return code;} - public String getMaterial() {return material;} - - public String getCustomModelData() {return customModelData;} - public Continent getContinent() {return continent;} public List getCityProjects() { @@ -62,8 +60,7 @@ public List getCityProjects() { } public String getName(Player player) { - // TODO: get name from new language file - return code; + return LangUtil.getInstance().get(player, LangPaths.Database.COUNTRY + "." + code + ".name"); } public boolean setMaterialAndModelData(String material, @Nullable String customModelData) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java b/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java index 714a6938..b347d1a2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java @@ -26,6 +26,9 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import org.bukkit.entity.Player; public class Difficulty { private final String ID; @@ -45,6 +48,10 @@ public String getID() { return ID; } + public String getName(Player player) { + return LangUtil.getInstance().get(player, LangPaths.Database.DIFFICULTY + "." + ID + ".name"); + } + public PlotDifficulty getDifficulty() { return difficulty; } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index eb8226f0..34f083aa 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -202,11 +202,11 @@ private ItemUtils() {} }; } - public static @NotNull TextComponent getFormattedDifficulty(@NotNull PlotDifficulty plotDifficulty) { + public static @NotNull TextComponent getFormattedDifficulty(@NotNull PlotDifficulty plotDifficulty, Player player) { return switch (plotDifficulty) { - case EASY -> text("Easy", GREEN).decoration(BOLD, true); - case MEDIUM -> text("Medium", GOLD).decoration(BOLD, true); - case HARD -> text("Hard", RED).decoration(BOLD, true); + case EASY -> text(LangUtil.getInstance().get(player, LangPaths.Database.DIFFICULTY + ".easy.name"), GREEN).decoration(BOLD, true); + case MEDIUM -> text(LangUtil.getInstance().get(player, LangPaths.Database.DIFFICULTY + ".medium.name"), GOLD).decoration(BOLD, true); + case HARD -> text(LangUtil.getInstance().get(player, LangPaths.Database.DIFFICULTY + ".hard.name"), RED).decoration(BOLD, true); }; } } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 7c6afe26..699f613f 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -409,5 +409,15 @@ private Beginner() {} public static final String STAGE10_MESSAGES = STAGE10 + "stage-10-messages"; public static final String STAGE10_TASKS = STAGE10 + "stage-10-tasks"; } + + } + + public static final class Database { + private Database() {} + + private static final String DATABASE_PREFIX = "database."; + public static final String CITY_PROJECT = DATABASE_PREFIX + "city-project"; + public static final String COUNTRY = DATABASE_PREFIX + "country"; + public static final String DIFFICULTY = DATABASE_PREFIX + "difficulty"; } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java index 5f923cf2..a8ca94d2 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java @@ -39,14 +39,14 @@ public class LangUtil extends LanguageUtil { public static void init() { if (langUtilInstance != null) return; LangLibAPI.register(PlotSystem.getPlugin(), new LanguageFile[]{ - new LanguageFile(Language.en_GB, 2.3), - new LanguageFile(Language.de_DE, 2.3, "de_AT", "de_CH"), - new LanguageFile(Language.fr_FR, 2.3, "fr_CA"), - new LanguageFile(Language.pt_PT, 2.3, "pt_BR"), - new LanguageFile(Language.ko_KR, 2.3), - new LanguageFile(Language.ru_RU, 2.3, "ba_RU", "tt_RU"), - new LanguageFile(Language.zh_CN, 2.3), - new LanguageFile(Language.zh_TW, 2.3, "zh_HK"), + new LanguageFile(Language.en_GB, 2.4), + new LanguageFile(Language.de_DE, 2.4, "de_AT", "de_CH"), + new LanguageFile(Language.fr_FR, 2.4, "fr_CA"), + new LanguageFile(Language.pt_PT, 2.4, "pt_BR"), + new LanguageFile(Language.ko_KR, 2.4), + new LanguageFile(Language.ru_RU, 2.4, "ba_RU", "tt_RU"), + new LanguageFile(Language.zh_CN, 2.4), + new LanguageFile(Language.zh_TW, 2.4, "zh_HK"), }); langUtilInstance = new LangUtil(); } diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index b147a293..ad9497b9 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -390,5 +390,27 @@ tutorials: - 'Frohes Bauen! ☺' stage-10-tasks: - 'Lies alle Tipps auf dem Plot und markiere sie als gelesen.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Beispiel Stadt' + description: 'Eine Beschreibung' + country: + AT: + name: 'Österreich' + CH: + name: 'Schweiz' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' #NOTE: Do not change -config-version: 2.3 +config-version: 2.4 diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index ef40e926..25c569d0 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -390,5 +390,27 @@ tutorials: - 'Happy building! ☺' stage-10-tasks: - 'Read all tips on the plot and mark them as read.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' # NOTE: Do not change -config-version: 2.3 +config-version: 2.4 diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index 8a534a00..9b1b3a06 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -390,5 +390,27 @@ tutorials: - 'Bonne construction ! ☺' stage-10-tasks: - 'Lisez tous les conseils sur les parcelles et marquez-les comme lus.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' #NOTE: Do not change -config-version: 2.3 \ No newline at end of file +config-version: 2.4 \ No newline at end of file diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index f5e11ed8..c33c6716 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -390,5 +390,27 @@ tutorials: - 'Happy building! ☺' stage-10-tasks: - 'Read all tips on the plot and mark them as read.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' # NOTE: Do not change -config-version: 2.3 +config-version: 2.4 diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index edb66b6c..2df30762 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -390,5 +390,27 @@ tutorials: - 'Happy building! ☺' stage-10-tasks: - 'Read all tips on the plot and mark them as read.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' # NOTE: Do not change -config-version: 2.3 +config-version: 2.4 diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index 640a78cf..bc5ae528 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -390,5 +390,27 @@ tutorials: - 'Happy building! ☺' stage-10-tasks: - 'Read all tips on the plot and mark them as read.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' # NOTE: Do not change -config-version: 2.3 +config-version: 2.4 diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 03a20d2c..56cf984a 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -391,5 +391,27 @@ tutorials: - 'Happy building! ☺' stage-10-tasks: - 'Read all tips on the plot and mark them as read.' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' # NOTE: Do not change -config-version: 2.3 +config-version: 2.4 diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index 5c6dc3c7..3043f779 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -390,5 +390,27 @@ tutorials: - '建築愉快!☺' stage-10-tasks: - '閱讀建地上全部的提示並將其標記為已讀。' +# ----------------------------------------------------- +# | Database +# ----------------------------------------------------- +database: + city-project: + example-city: + name: 'Example City' + description: 'Some description' + country: + AT: + name: 'Austria' + CH: + name: 'Switzerland' + LI: + name: 'Liechtenstein' + difficulty: + easy: + name: 'Easy' + medium: + name: 'Medium' + hard: + name: 'Hard' # NOTE: Do not change -config-version: 2.3 +config-version: 2.4 From 108b83edd699db153d4372765ab305ed0cceab09 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 16 Feb 2025 00:52:43 +0100 Subject: [PATCH 036/175] implement country provider logic --- .../admin/setup/CMD_Setup_BuildTeam.java | 19 +++--- .../commands/admin/setup/CMD_Setup_City.java | 7 +- .../admin/setup/CMD_Setup_Country.java | 9 +-- .../database/providers/CountryProvider.java | 68 +++++++++++++++---- .../core/menus/companion/CompanionMenu.java | 7 +- .../plotsystem/core/system/Builder.java | 6 +- .../plotsystem/core/system/CityProject.java | 3 +- .../plotsystem/core/system/Country.java | 2 +- 8 files changed, 82 insertions(+), 39 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 1d082944..a8df8d44 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -35,6 +35,7 @@ import org.bukkit.command.CommandSender; import java.util.List; +import java.util.Optional; import java.util.StringJoiner; import static net.kyori.adventure.text.Component.text; @@ -278,22 +279,20 @@ public void onCommand(CommandSender sender, String[] args) { return; } - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); - + Optional country = DataProvider.COUNTRY.getCountryByCode(args[2]); // Check if build team and country exists if (buildTeam == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } - if (country == null) { + if (country.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is already added to the build team!")); return; } - boolean successful = buildTeam.addCountry(country); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.getCode() + "' to build team with ID " + args[1] + "!")); + boolean successful = buildTeam.addCountry(country.get()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.get().getCode() + "' to build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -331,20 +330,20 @@ public void onCommand(CommandSender sender, String[] args) { } BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - Country country = DataProvider.COUNTRY.getCountryByCode(args[2]); + Optional country = DataProvider.COUNTRY.getCountryByCode(args[2]); // Check if build team and country exists if (buildTeam == null) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } - if (country == null) { + if (country.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is not added to the build team!")); return; } - boolean successful = buildTeam.removeCountry(country.getCode()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.getCode() + "' from build team with ID " + args[1] + "!")); + boolean successful = buildTeam.removeCountry(country.get().getCode()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.get().getCode() + "' from build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index accedfde..e4538099 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -33,6 +33,7 @@ import org.bukkit.command.CommandSender; import java.util.List; +import java.util.Optional; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; @@ -135,8 +136,8 @@ public void onCommand(CommandSender sender, String[] args) { String cityProjectId = args[1]; String countryCode = args[2]; - Country country = DataProvider.COUNTRY.getCountryByCode(countryCode); - if (country == null) { + Optional country = DataProvider.COUNTRY.getCountryByCode(countryCode); + if (country.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with code " + countryCode + "!")); sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all countries!")); return; @@ -153,7 +154,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, country.getCode(), serverName); + boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, country.get().getCode(), serverName); if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 696208f5..519b9f94 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -35,6 +35,7 @@ import java.util.Arrays; import java.util.List; +import java.util.Optional; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; @@ -184,7 +185,7 @@ public void onCommand(CommandSender sender, String[] args) { String code = args[1]; // Check if country exists - if (DataProvider.COUNTRY.getCountryByCode(code) == null) { + if (DataProvider.COUNTRY.getCountryByCode(code).isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with code " + code + "!")); sendInfo(sender); return; @@ -232,14 +233,14 @@ public void onCommand(CommandSender sender, String[] args) { String customModelData = args.length > 3 ? args[3] : null; // Check if country exists - Country country = DataProvider.COUNTRY.getCountryByCode(code); - if (country == null) { + Optional country = DataProvider.COUNTRY.getCountryByCode(code); + if (country.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with name " + args[1] + "!")); sendInfo(sender); return; } - boolean successful = country.setMaterialAndModelData(material, customModelData); + boolean successful = country.get().setMaterialAndModelData(material, customModelData); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully updated country with code " + country + "! Material: " + material + " CustomModelData: " + (customModelData == null ? "NULL" : customModelData))); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index dba53dcb..2ded58c2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -1,41 +1,83 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; import org.jetbrains.annotations.Nullable; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; +import java.util.Optional; public class CountryProvider { + private static final List cachedCountries = new ArrayList<>(); + + public CountryProvider() { + // cache all countries + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT country_code, continent, material, custom_model_data FROM country;")) { + try (ResultSet rs = stmt.executeQuery()) { + Continent continent = Continent.fromDatabase(rs.getString(2)); + Country country = new Country(rs.getString(1), continent, rs.getString(3), rs.getString(4)); + cachedCountries.add(country); + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + } + public List getCountries() { - // TODO: implement - return List.of(); + return cachedCountries; } public List getCountriesByContinent(Continent continent) { - // TODO: implement - return List.of(); + return cachedCountries.stream().filter(c -> c.getContinent() == continent).toList(); } - public Country getCountryByCode(String code) { - // TODO: implement - //Continent continent = Continent.fromDatabase() - - return null; + public Optional getCountryByCode(String code) { + return cachedCountries.stream().filter(c -> c.getCode().equals(code)).findFirst(); } - public boolean setMaterialAndCustomModelData(String material, @Nullable String customModelData) { - // TODO: implement + public boolean setMaterialAndCustomModelData(String code, String material, @Nullable String customModelData) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;")) { + stmt.setString(1, material); + stmt.setString(2, customModelData); + stmt.setString(3, code); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean addCountry(String code, Continent continent, String material, @Nullable String customModelData) { - // TODO: implement + if (getCountryByCode(code).isPresent()) return true; + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO country (country_code, continent, material, custom_model_data) " + + "VALUES (?, ?, ?, ?);")) { + stmt.setString(1, code); + stmt.setString(2, continent.databaseEnum); + stmt.setString(3, material); + stmt.setString(4, customModelData); + boolean result = stmt.executeUpdate() > 0; + if (result) cachedCountries.add(new Country(code, continent, material, customModelData)); + return result; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean removeCountry(String code) { - // TODO: implement + Optional cachedCountry = getCountryByCode(code); + if (cachedCountry.isEmpty()) return false; + + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("DELETE FROM country WHERE country_code = ?;")) { + stmt.setString(1, code); + boolean result = stmt.executeUpdate() > 0; + if (result) cachedCountries.remove(cachedCountry.get()); + return result; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 381931aa..3da1ad94 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -47,7 +47,6 @@ import com.alpsbte.plotsystem.utils.items.CustomHeads; import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -217,7 +216,7 @@ public static class FooterItem { public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) { String nameText = LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); - TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), GOLD).decoration(TextDecoration.BOLD, true); + TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), GOLD).decoration(BOLD, true); TextComponent slotDescriptionComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), GRAY); Material itemMaterial = Material.MAP; @@ -237,12 +236,12 @@ public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPla text(plotCityText + ": ", GRAY).append(text(plot.getCity().getName(langPlayer), WHITE)), text(plotDifficultyText + ": ", GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), WHITE)), empty(), - statusComp.append(text(": Unassigned", GRAY)).decoration(TextDecoration.BOLD, true)) + statusComp.append(text(": Unassigned", GRAY)).decoration(BOLD, true)) .build(); } return new ItemBuilder(itemMaterial, 1 + slotIndex) - .setName(text(nameText, GOLD).decoration(TextDecoration.BOLD, true)) + .setName(text(nameText, GOLD).decoration(BOLD, true)) .setLore(lore) .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 4cc83d4e..72a261e1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -94,9 +94,9 @@ public Plot getSlot(Slot slot) { public boolean setSlot(Slot slot, int plotId) { if (DataProvider.BUILDER.setSlot(this.uuid, plotId, slot)) { switch (slot) { - case FIRST: firstSlot = plotId; break; - case SECOND: secondSlot = plotId; break; - case THIRD: thirdSlot = plotId; break; + case FIRST -> firstSlot = plotId; + case SECOND -> secondSlot = plotId; + case THIRD -> thirdSlot = plotId; } return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index c1e5f4c1..772ed19e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -67,7 +67,8 @@ public String getID() { } public Country getCountry() { - return DataProvider.COUNTRY.getCountryByCode(countryCode); + // city project objects will never be created with an id of a country that does not exist as this would throw a sql exception first + return DataProvider.COUNTRY.getCountryByCode(countryCode).orElseThrow(); } public String getServerName() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index 5c051b96..f9edbc70 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -64,7 +64,7 @@ public String getName(Player player) { } public boolean setMaterialAndModelData(String material, @Nullable String customModelData) { - if (DataProvider.COUNTRY.setMaterialAndCustomModelData(material, customModelData)) { + if (DataProvider.COUNTRY.setMaterialAndCustomModelData(code, material, customModelData)) { this.material = material; this.customModelData = customModelData; return true; From 844b40ef8cb12097d8d21ac0977ecd12382cd10b Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 16 Feb 2025 01:21:49 +0100 Subject: [PATCH 037/175] implement server provider logic --- .../admin/setup/CMD_Setup_Server.java | 16 +++++-- .../database/providers/CountryProvider.java | 8 ++-- .../database/providers/ServerProvider.java | 48 +++++++++++++++---- 3 files changed, 57 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index 27f86cc9..dcbfa135 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.commands.admin.setup; +import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -124,14 +125,21 @@ public CMD_Setup_Server_Add(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1) {sendInfo(sender); return;} - if (args[1].length() > 255) { + if (args.length <= 2 || AlpsUtils.tryParseInt(args[2]) == null) {sendInfo(sender); return;} + + String serverName = args[1]; + if (serverName.length() > 255) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Server name cannot be longer than 255 characters!")); sendInfo(sender); return; } - boolean successful = DataProvider.SERVER.addServer(args[1]); + int buildTeamId = AlpsUtils.tryParseInt(args[2]); + if (DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId) == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team with id " + buildTeamId + " could not be found!")); + } + + boolean successful = DataProvider.SERVER.addServer(serverName, buildTeamId); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added server!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -148,7 +156,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"Name"}; + return new String[]{"Name", "BuildTeamId"}; } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index 2ded58c2..c1acf7c3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -21,9 +21,11 @@ public CountryProvider() { try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("SELECT country_code, continent, material, custom_model_data FROM country;")) { try (ResultSet rs = stmt.executeQuery()) { - Continent continent = Continent.fromDatabase(rs.getString(2)); - Country country = new Country(rs.getString(1), continent, rs.getString(3), rs.getString(4)); - cachedCountries.add(country); + while (rs.next()) { + Continent continent = Continent.fromDatabase(rs.getString(2)); + Country country = new Country(rs.getString(1), continent, rs.getString(3), rs.getString(4)); + cachedCountries.add(country); + } } } catch (SQLException ex) {Utils.logSqlException(ex);} } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java index 031b1aff..4c644b81 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java @@ -1,26 +1,58 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.utils.Utils; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; public class ServerProvider { - @SuppressWarnings("BooleanMethodIsAlwaysInverted") + private static final List cachedServers = new ArrayList<>(); + + public ServerProvider() { + // cache all servers + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT server_name FROM server;")) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) cachedServers.add(rs.getString(1)); + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + } + public boolean serverExists(String serverName) { - // TODO: implement - return false; + return cachedServers.stream().anyMatch(s -> s.equals(serverName)); } public List getServers() { - // TODO: implement - return null; + return cachedServers; } - public boolean addServer(String name) { - // TODO: implement + public boolean addServer(String name, int buildTeamId) { + if (serverExists(name)) return true; + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO server (server_name, build_team_id) " + + "VALUES (?, ?);")) { + stmt.setString(1, name); + stmt.setInt(2, buildTeamId); + boolean result = stmt.executeUpdate() > 0; + if (result) cachedServers.add(name); + return result; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean removeServer(String name) { - // TODO: implement + if (!serverExists(name)) return false; + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("DELETE FROM server WHERE server_name = ?;")) { + stmt.setString(1, name); + boolean result = stmt.executeUpdate() > 0; + if (result) cachedServers.remove(name); + return result; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } } From 0ebe768ffae42d7fecbb7b105fd0c10e083e50bc Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 16 Feb 2025 02:46:36 +0100 Subject: [PATCH 038/175] implement difficulty provider logic --- .../admin/setup/CMD_Setup_Difficulty.java | 13 ++-- .../providers/DifficultyProvider.java | 70 ++++++++++++++----- .../core/menus/companion/CompanionMenu.java | 9 ++- 3 files changed, 69 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java index 512b7d6c..b74f466e 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java @@ -33,6 +33,7 @@ import org.bukkit.command.CommandSender; import java.util.List; +import java.util.Optional; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; @@ -128,10 +129,10 @@ public void onCommand(CommandSender sender, String[] args) { } // Check if difficulty exists - Difficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(args[1]); - if (difficulty == null) return; + Optional difficulty = DataProvider.DIFFICULTY.getDifficultyById(args[1]); + if (difficulty.isEmpty()) return; - boolean successful = difficulty.setMultiplier(Double.parseDouble(args[2])); + boolean successful = difficulty.get().setMultiplier(Double.parseDouble(args[2])); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set multiplier of Difficulty with ID " + args[1] + " to " + args[2] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -170,10 +171,10 @@ public void onCommand(CommandSender sender, String[] args) { } // Check if difficulty exists - Difficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(args[1]); - if (difficulty == null) return; + Optional difficulty = DataProvider.DIFFICULTY.getDifficultyById(args[1]); + if (difficulty.isEmpty()) return; - boolean successful = difficulty.setScoreRequirement(Integer.parseInt(args[2])); + boolean successful = difficulty.get().setScoreRequirement(Integer.parseInt(args[2])); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set score requirement of Difficulty with ID " + args[1] + " to " + args[2] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index e4cfdf03..aeacaca2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -1,45 +1,83 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Difficulty; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; import java.util.List; +import java.util.Optional; + +import static net.kyori.adventure.text.Component.text; public class DifficultyProvider { + private static final List cachedDifficulties = new ArrayList<>(); + + public DifficultyProvider() { + // cache all difficulties + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT difficulty_id, multiplier, score_requirement FROM difficulty;")) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + String id = rs.getString(1); + double multiplier = rs.getDouble(2); + int scoreRequirement = rs.getInt(3); + PlotDifficulty plotDifficulty = PlotDifficulty.valueOf(id); + + Difficulty difficulty = new Difficulty(plotDifficulty, id, multiplier, scoreRequirement); + cachedDifficulties.add(difficulty); + } + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + } + public List getDifficulties() { - // TODO: implement - return List.of(); + return cachedDifficulties; } - public Difficulty getDifficultyById(String id) { - // TODO: implement - return null; + public Optional getDifficultyById(String id) { + return cachedDifficulties.stream().filter(d -> d.getID().equals(id)).findAny(); } - public double getMultiplier(PlotDifficulty difficulty) { - // TODO: implement (get from cached list) - return 0; + public Optional getDifficultyByEnum(PlotDifficulty difficulty) { + return cachedDifficulties.stream().filter(d -> d.getID().equals(difficulty.name())).findFirst(); } public boolean setMultiplier(String id, double multiplier) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE difficulty SET multiplier = ? WHERE difficulty_id = ?;")) { + stmt.setDouble(1, multiplier); + stmt.setString(2, id); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } - public int getScoreRequirement(PlotDifficulty difficulty) { - // TODO: implement (get from cached list) - return 0; - } - public boolean setScoreRequirement(String id, int scoreRequirement) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE difficulty SET score_requirement = ? WHERE difficulty_id = ?;")) { + stmt.setInt(1, scoreRequirement); + stmt.setString(2, id); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean builderMeetsRequirements(Builder builder, PlotDifficulty plotDifficulty) { + Optional cachedDifficulty = getDifficultyByEnum(plotDifficulty); + if (cachedDifficulty.isEmpty()) { + PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " + plotDifficulty.name() + " was found!")); + return false; + } + int playerScore = builder.getScore(); - int scoreRequirement = getScoreRequirement(plotDifficulty); + int scoreRequirement = cachedDifficulty.get().getScoreRequirement(); return playerScore >= scoreRequirement; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 3da1ad94..0f90c987 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -35,6 +35,7 @@ import com.alpsbte.plotsystem.core.menus.SettingsMenu; import com.alpsbte.plotsystem.core.menus.tutorial.TutorialsMenu; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.Difficulty; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; @@ -148,12 +149,18 @@ public static ItemStack getDifficultyItem(Player player, PlotDifficulty selected } } else item = AlpsHeadUtils.getCustomHead(CustomHeads.WHITE_CONCRETE.getId()); + Optional difficulty = DataProvider.DIFFICULTY.getDifficultyByEnum(selectedPlotDifficulty); + if (difficulty.isEmpty()) { + PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " + selectedPlotDifficulty + " was found!")); + } + double scoreMultiplier = difficulty.map(Difficulty::getMultiplier).orElse(0.0); + return new ItemBuilder(item) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.PLOT_DIFFICULTY), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() .emptyLine() .addLines(selectedPlotDifficulty != null ? Utils.ItemUtils.getFormattedDifficulty(selectedPlotDifficulty, player) : text(LangUtil.getInstance().get(player, LangPaths.Difficulty.AUTOMATIC), WHITE).decoration(BOLD, true), - selectedPlotDifficulty != null ? text(LangUtil.getInstance().get(player, LangPaths.Difficulty.SCORE_MULTIPLIER) + ": ", GRAY).append(text("x" + DataProvider.DIFFICULTY.getMultiplier(selectedPlotDifficulty), WHITE)) : empty()) + selectedPlotDifficulty != null ? text(LangUtil.getInstance().get(player, LangPaths.Difficulty.SCORE_MULTIPLIER) + ": ", GRAY).append(text("x" + scoreMultiplier, WHITE)) : empty()) .emptyLine() .addLine(text(LangUtil.getInstance().get(player, LangPaths.MenuDescription.PLOT_DIFFICULTY), GRAY)) .build()) From ef704cd2777079cd42c53c48a3d9b8ecc1bec08b Mon Sep 17 00:00:00 2001 From: Zoriot Date: Tue, 18 Feb 2025 23:19:05 +0100 Subject: [PATCH 039/175] Check only first numbers for tutorial height It's better than specifying all units. Diskussion on Discord. Resolves #137. --- .../stage/tasks/events/ChatEventTask.java | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java index 7a9f6e00..d02176a7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events; -import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.AbstractTask; import io.papermc.paper.event.player.AsyncChatEvent; @@ -32,6 +31,7 @@ import net.kyori.adventure.text.TextComponent; import org.bukkit.entity.Player; import org.bukkit.event.Event; +import org.jetbrains.annotations.NotNull; public class ChatEventTask extends AbstractTask implements EventTask { private final int expectedValue; @@ -59,10 +59,10 @@ public void performEvent(Event event) { if (event instanceof AsyncChatEvent chatEvent) { chatEvent.setCancelled(true); - TextComponent message = (TextComponent) chatEvent.message(); - if (AlpsUtils.tryParseInt(message.content()) != null) { - int value = Integer.parseInt(message.content()); - if (value >= expectedValue - offset && value <= expectedValue + offset) { + int inputNum = getStartDigits(((TextComponent) chatEvent.message()).content()); + + if (inputNum != -1) { + if (inputNum >= expectedValue - offset && inputNum <= expectedValue + offset) { onChatAction.performAction(true, attemptsLeft); attemptsLeft = 0; } else { @@ -77,4 +77,20 @@ public void performEvent(Event event) { } } } + + private int getStartDigits(@NotNull String message) { + int i = 0; + StringBuilder digits = new StringBuilder("0"); + while (i < message.length()) { + if (Character.isDigit(message.charAt(i))) { + digits.append(message.charAt(i)); + } else if (i == 0) { + return -1; + } else { + break; + } + i++; + } + return Integer.parseInt(digits.toString()); + } } From 8b09ff37cbe773e9c1a6b68b47a4381103924095 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 20 Feb 2025 17:39:57 +0100 Subject: [PATCH 040/175] implement remaining methods of builder provider --- .../database/providers/BuilderProvider.java | 102 +++++++++++------- 1 file changed, 66 insertions(+), 36 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index b1549388..69249232 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -24,8 +24,10 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; +import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; import com.alpsbte.plotsystem.utils.Utils; @@ -54,7 +56,7 @@ public Builder getBuilderByUUID(UUID uuid) { rs.getInt(4), rs.getInt(5), rs.getInt(6)); } } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } @@ -67,15 +69,28 @@ public Builder getBuilderByName(String name) { String uuid = rs.getString(1); if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } public boolean addBuilderIfNotExists(UUID uuid, String name) { - // TODO: implement // check if builder already exists, if so return TRUE!! - // if successfully added -> TRUE - // else -> FALSE + if (builders.containsKey(uuid)) return true; + try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("SELECT name FROM builder WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) return true; + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + + // add builder to database + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO builder (uuid, name) " + + "VALUES (?, ?);")) { + stmt.setString(1, uuid.toString()); + stmt.setString(2, name); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -87,7 +102,7 @@ public boolean setName(UUID uuid, String name) { stmt.executeUpdate(); if (builders.containsKey(uuid)) builders.get(uuid).setName(name); return true; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -100,7 +115,7 @@ public boolean addScore(UUID uuid, int score) { stmt.executeUpdate(); return true; } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -123,29 +138,29 @@ public boolean setSlot(UUID uuid, int plotID, Slot slot) { } } return true; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean setPlotType(UUID uuid, int plotTypeId) { - try { - if (plotTypeId > 0) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET plot_type = ? WHERE uuid = ?;")) { - stmt.setInt(1, plotTypeId); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - } - } else { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET plot_type = DEFAULT(plot_type) WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); - stmt.executeUpdate(); - } - } - return true; - } catch (SQLException ex) { Utils.logSqlException(ex); } - return false; + try { + if (plotTypeId > 0) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET plot_type = ? WHERE uuid = ?;")) { + stmt.setInt(1, plotTypeId); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + } + } else { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE builder b SET plot_type = DEFAULT(plot_type) WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + stmt.executeUpdate(); + } + } + return true; + } catch (SQLException ex) {Utils.logSqlException(ex);} + return false; } public int getCompletedBuildsCount(UUID uuid) { @@ -157,7 +172,7 @@ public int getCompletedBuildsCount(UUID uuid) { try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) return rs.getInt(1); } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return 0; } @@ -171,19 +186,34 @@ public Slot getFreeSlot(UUID uuid) { if (rs.getString(i) == null) return Slot.values()[i - 1]; } } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean canReviewPlot(Builder builder, Plot plot) { - // TODO: implement (check for build team) - // no need to check for plot owner / plot members as this is handled separately + // TODO: cache + try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;")) { + stmt.setString(1, builder.getUUID().toString()); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + BuildTeam team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); + if (team.getReviewers().stream().anyMatch(b -> b.getUUID() == builder.getUUID())) + return true; + } + } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean isAnyReviewer(UUID uuid) { - // TODO: implement (check if builder is a reviewer of any build team) + // TODO: cache + try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("SELECT uuid FROM build_team_has_reviewer WHERE uuid = ?;")) { + stmt.setString(1, uuid.toString()); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) return true; + } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -191,7 +221,7 @@ public boolean isAnyReviewer(UUID uuid) { * Retrieves the leaderboard entry for a specific player based on their UUID and the specified timeframe. * The leaderboard entry includes the player's score, rank, and total number of players. * - * @param uuid the unique identifier of the player. + * @param uuid the unique identifier of the player. * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). * @return provides the leaderboard entry for the player, or null if not found. */ @@ -205,7 +235,7 @@ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimefram } } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } @@ -225,7 +255,7 @@ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { return playerEntries; } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } @@ -238,8 +268,8 @@ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { * If no UUID is provided, the query will return the top leaderboard entries ordered by score * within the specified timeframe.

* - * @param uuid the unique identifier of the builder for which to calculate the leaderboard position. - * If {@code null}, the query retrieves the top entries instead of a specific position. + * @param uuid the unique identifier of the builder for which to calculate the leaderboard position. + * If {@code null}, the query retrieves the top entries instead of a specific position. * @param sortBy the timeframe used to filter entries. Determines the minimum date for reviews * (e.g., daily, weekly, monthly, yearly). * @return the constructed SQL query as a {@code String}. From 8ceb4ea705c7d6030db27ff94bc5190990e067b3 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 20 Feb 2025 20:47:29 +0100 Subject: [PATCH 041/175] Send a repeated message for unfinished plots Resolves #118. Also remove unnecessary config options and use cache to get the plots. The interval is configurable. --- .../plotsystem/core/EventListener.java | 12 ++--------- .../core/system/plot/utils/PlotUtils.java | 20 ++++++++++++++++++- .../plotsystem/utils/io/ConfigPaths.java | 7 +------ src/main/resources/config.yml | 10 ++++------ 4 files changed, 26 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 4dc0694f..63809be5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -299,16 +299,8 @@ private void sendNotices(@NotNull Player player, Builder builder) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his plot feedback!"), ex); } - // Informing player about unfinished plots - try { - List plots = DataProvider.PLOT.getPlots(builder, Status.unfinished); - if (!plots.isEmpty()) { - PlotUtils.ChatFormatting.sendUnfinishedPlotReminderMessage(plots, player); - player.sendMessage(""); - } - } catch (Exception ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his unfinished plots!"), ex); - } + PlotUtils.informPlayerAboutUnfinishedPlots(player, builder); + PlotUtils.startUnfinishedPlotReminderTimer(player); // Informing reviewer about new reviews if (player.hasPermission("plotsystem.admin") || DataProvider.BUILDER.isAnyReviewer(builder.getUUID())) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 69be99dd..92cd2d4a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -303,6 +303,23 @@ public static void checkPlotsForLastActivity() { }, 0L, 20 * 60 * 60L); // Check every hour } + public static void informPlayerAboutUnfinishedPlots(@NotNull Player player, Builder builder) { + try { + List plots = Cache.getCachedInProgressPlots(builder); + if (!plots.isEmpty()) { + PlotUtils.ChatFormatting.sendUnfinishedPlotReminderMessage(plots, player); + } + } catch (Exception ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his unfinished plots!"), ex); + } + } + + public static void startUnfinishedPlotReminderTimer(Player player) { + int interval = PlotSystem.getPlugin().getConfig().getInt(ConfigPaths.UNFINISHED_REMINDER_INTERVAL); + if (interval == -1) return; + Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> informPlayerAboutUnfinishedPlots(player, Builder.byUUID(player.getUniqueId())), 0L, 20L * 60 * interval); + } + public static final class Actions { private Actions() {} @@ -626,7 +643,8 @@ public static void sendUnreviewedPlotsReminderMessage(@NotNull List plots, Component tc = text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_SHOW_OPEN_REVIEWS), GOLD) .clickEvent(ClickEvent.runCommand("/review")) - .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.SHOW_PLOTS))); + .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.SHOW_PLOTS))) + .appendNewline(); player.sendMessage(tc); } } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java index cd8473a1..f7a14fd9 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java @@ -35,6 +35,7 @@ public abstract class ConfigPaths { public static final String INACTIVITY_INTERVAL = "inactivity-interval"; public static final String REJECTED_INACTIVITY_INTERVAL = "rejected-inactivity-interval"; public static final String ENABLE_GROUP_SUPPORT = "enable-group-support"; + public static final String UNFINISHED_REMINDER_INTERVAL = "unfinished-reminder-interval"; // Database private static final String DATABASE = "database."; @@ -50,11 +51,6 @@ public abstract class ConfigPaths { public static final String SCORE_LEADERBOARD_X = HOLOGRAMS + SCORE_LEADERBOARD + ".sl-x"; public static final String SCORE_LEADERBOARD_Y = HOLOGRAMS + SCORE_LEADERBOARD + ".sl-y"; public static final String SCORE_LEADERBOARD_Z = HOLOGRAMS + SCORE_LEADERBOARD + ".sl-z"; - public static final String PLOTS_LEADERBOARD = "plots-leaderboard"; - public static final String PLOTS_LEADERBOARD_ENABLE = HOLOGRAMS + PLOTS_LEADERBOARD + ".pl-enable"; - public static final String PLOTS_LEADERBOARD_X = HOLOGRAMS + PLOTS_LEADERBOARD + ".pl-x"; - public static final String PLOTS_LEADERBOARD_Y = HOLOGRAMS + PLOTS_LEADERBOARD + ".pl-y"; - public static final String PLOTS_LEADERBOARD_Z = HOLOGRAMS + PLOTS_LEADERBOARD + ".pl-z"; private static final String DISPLAY_OPTIONS = "display-options."; public static final String DISPLAY_OPTIONS_INTERVAL = DISPLAY_OPTIONS + "interval"; @@ -74,7 +70,6 @@ public abstract class ConfigPaths { // COMMANDS public static final String EDITPLOT_ENABLED = "editplot-enabled"; public static final String BLOCKED_COMMANDS_BUILDERS = "blocked-commands-builders"; - public static final String ALLOWED_COMMANDS_NON_BUILDERS = "allowed-commands-non-builders"; // SHORTLINKS private static final String SHORTLINK = "shortlink."; diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 7372760a..4ead134c 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -39,6 +39,10 @@ rejected-inactivity-interval: -1 # NOTE: Score will be split by all participating members enable-group-support: true +# After how many minutes a player receives a reminder to finish his plot. +# Will be repeated every x minutes; It uses the unfinished-plots string, set it to -1 to disable +unfinished-reminder-interval: 20 + # ----------------------------------------------------- # | Supported databases: MariaDB & MySQL # ----------------------------------------------------- @@ -60,12 +64,6 @@ holograms: sl-x: 0 sl-y: 0 sl-z: 0 - # Displays the top 10 players with the most completed plots - plots-leaderboard: - pl-enable: false - pl-x: 0 - pl-y: 0 - pl-z: 0 # Switch score-leaderboard between different time stamps # [interval] -> default: 15 seconds From 8353b7a1dfe1e07f6b971d7f80e67aa3fcda63fa Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 27 Feb 2025 05:26:09 +0100 Subject: [PATCH 042/175] implement most methods of build team provider --- .../admin/setup/CMD_Setup_BuildTeam.java | 42 +++--- .../core/database/DataProvider.java | 2 +- .../database/providers/BuildTeamProvider.java | 123 +++++++++++++----- .../database/providers/BuilderProvider.java | 20 ++- .../database/providers/CountryProvider.java | 15 +++ 5 files changed, 149 insertions(+), 53 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index a8df8d44..228b864a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -183,16 +183,16 @@ public CMD_Setup_BuildTeam_Remove(BaseCommand baseCommand, SubCommand subCommand public void onCommand(CommandSender sender, String[] args) { if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); // Check if build team exists - if (buildTeam == null) { + if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any build team with ID " + args[1] + "!")); sendInfo(sender); return; } - boolean successful = DataProvider.BUILD_TEAM.removeBuildTeam(buildTeam.getID()); + boolean successful = DataProvider.BUILD_TEAM.removeBuildTeam(buildTeam.get().getID()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -227,10 +227,10 @@ public CMD_Setup_BuildTeam_SetName(BaseCommand baseCommand, SubCommand subComman public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); // Check if build team exits - if (buildTeam == null) { + if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; } @@ -241,7 +241,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean successful = buildTeam.setName(name); + boolean successful = buildTeam.get().setName(name); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed name of build team with ID " + args[1] + " to '" + name + "'!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -279,11 +279,11 @@ public void onCommand(CommandSender sender, String[] args) { return; } - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); Optional country = DataProvider.COUNTRY.getCountryByCode(args[2]); // Check if build team and country exists - if (buildTeam == null) { + if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } @@ -291,7 +291,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is already added to the build team!")); return; } - boolean successful = buildTeam.addCountry(country.get()); + boolean successful = buildTeam.get().addCountry(country.get()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.get().getCode() + "' to build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -329,11 +329,11 @@ public void onCommand(CommandSender sender, String[] args) { return; } - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); Optional country = DataProvider.COUNTRY.getCountryByCode(args[2]); // Check if build team and country exists - if (buildTeam == null) { + if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } @@ -342,7 +342,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean successful = buildTeam.removeCountry(country.get().getCode()); + boolean successful = buildTeam.get().removeCountry(country.get().getCode()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.get().getCode() + "' from build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -381,19 +381,19 @@ public void onCommand(CommandSender sender, String[] args) { } // Check if build team exits - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - if (buildTeam == null) { + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; } Builder builder = Builder.byName(args[2]); - if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == buildTeam.getID())) { + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == buildTeam.get().getID())) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is already reviewer for this build team!")); return; } - boolean successful = buildTeam.addReviewer(builder); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added '" + builder.getName() + "' as reviewer to build team with ID " + buildTeam.getName() + "!")); + boolean successful = buildTeam.get().addReviewer(builder); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added '" + builder.getName() + "' as reviewer to build team with ID " + buildTeam.get().getName() + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -428,20 +428,20 @@ public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} // Check if build team exits - BuildTeam buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - if (buildTeam == null) { + if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; } Builder builder = Builder.byName(args[2]); - if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == buildTeam.getID())) { + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == buildTeam.get().getID())) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is not a reviewer for this build team!")); return; } - boolean successful = buildTeam.removeReviewer(builder.getUUID().toString()); + boolean successful = buildTeam.get().removeReviewer(builder.getUUID().toString()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed '" + builder.getName() + "' as reviewer from build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 79106efd..18c4b1a2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -28,11 +28,11 @@ public class DataProvider { public static final BuilderProvider BUILDER = new BuilderProvider(); - public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(); public static final PlotProvider PLOT = new PlotProvider(); public static final DifficultyProvider DIFFICULTY = new DifficultyProvider(); public static final CityProjectProvider CITY_PROJECT = new CityProjectProvider(); public static final CountryProvider COUNTRY = new CountryProvider(); public static final ServerProvider SERVER = new ServerProvider(); public static final TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); + public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(BUILDER, COUNTRY); // has to be initialized after builder and country providers } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 1d36de90..240c2f3c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -1,6 +1,7 @@ package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; @@ -20,71 +21,135 @@ public class BuildTeamProvider { public static final List BUILD_TEAMS = new ArrayList<>(); - public BuildTeam getBuildTeam(int id) { - Optional buildTeam = BUILD_TEAMS.stream().filter(b -> b.getID() == id).findFirst(); - if (buildTeam.isPresent()) return buildTeam.get(); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT bt.name, bthc.country_code, bthcp.city_project_id, bthr.uuid FROM build_team bt " + - "INNER JOIN build_team_has_country bthc ON bthc.build_team_id = bt.build_team_id " + - "INNER JOIN build_team_has_city_project bthcp ON bthcp.build_team_id = bt.build_team_id " + - "INNER JOIN build_team_has_reviewer bthr ON bthr.build_team_id = bt.build_team_id " + - "WHERE bt.build_team_id = ?")) { + public BuildTeamProvider(BuilderProvider builderProvider, CountryProvider countryProvider) { + // cache all build teams + try (ResultSet rs = DatabaseConnection.createStatement("SELECT build_team_id, name FROM build_team").executeQuery()) { + while (rs.next()) { + int buildTeamId = rs.getInt(1); - } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; + List countries = countryProvider.getCountriesByBuildTeam(buildTeamId); + List reviewers = builderProvider.getReviewersByBuildTeam(buildTeamId); + BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), countries, reviewers)); + } + DatabaseConnection.closeResultSet(rs); + } catch (SQLException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + } } - public List getBuildTeamsByReviewer(UUID reviewerUUID) { - // TODO: implement - return List.of(); + public Optional getBuildTeam(int id) { + return BUILD_TEAMS.stream().filter(b -> b.getID() == id).findFirst(); } - public List getBuildTeams() { + public List getBuildTeamsByReviewer(UUID reviewerUUID) { List buildTeams = new ArrayList<>(); - List countries = new ArrayList<>(); - List reviewers = new ArrayList<>(); - // TODO: also get countries and reviewers (currently empty lists) - try (ResultSet rs = DatabaseConnection.createStatement("SELECT build_team_id, name FROM build_team").executeQuery()) { - while (rs.next()) buildTeams.add(new BuildTeam(rs.getInt(1), rs.getString(2), countries, reviewers)); - DatabaseConnection.closeResultSet(rs); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?")) { + stmt.setString(1, reviewerUUID.toString()); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + Optional buildTeam = getBuildTeam(rs.getInt(1)); + if (buildTeam.isEmpty()) continue; + buildTeams.add(buildTeam.get()); + } + DatabaseConnection.closeResultSet(rs); + } } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } return buildTeams; } + public List getBuildTeams() { + return BUILD_TEAMS; + } + public boolean addBuildTeam(String name) { - // TODO: implement - return false; + boolean result = false; + if (BUILD_TEAMS.stream().anyMatch(b -> b.getName().equals(name))) return false; + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO build_team (name) VALUES (?);")) { + stmt.setString(1, name); + result = stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} + + if (result) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT build_team_id FROM build_team WHERE name = ?;")) { + stmt.setString(1, name); + try (ResultSet rs = stmt.executeQuery()) { + BUILD_TEAMS.add(new BuildTeam(rs.getInt(1), name, List.of(), List.of())); + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + } + return result; } public boolean removeBuildTeam(int id) { - // TODO: implement + Optional cachedBuildTeam = getBuildTeam(id); + if (cachedBuildTeam.isEmpty()) return false; + + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("DELETE FROM build_team WHERE build_team_id = ?;")) { + stmt.setInt(1, id); + boolean result = stmt.executeUpdate() > 0; + if (result) BUILD_TEAMS.remove(cachedBuildTeam.get()); + return result; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean setBuildTeamName(int id, String newName) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE build_team SET name = ? WHERE build_team_id = ?;")) { + stmt.setString(1, newName); + stmt.setInt(2, id); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { Utils.logSqlException(ex); } return false; } public boolean addCountry(int id, String countryCode) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO build_team_has_country (build_team_id, country_code) " + + "VALUES (?, ?);")) { + stmt.setInt(1, id); + stmt.setString(2, countryCode); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean removeCountry(int id, String countryCode) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("DELETE FROM build_team_has_country " + + "WHERE build_team_id = ? AND country_code = ?;")) { + stmt.setInt(1, id); + stmt.setString(2, countryCode); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean addReviewer(int id, String reviewerUUID) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("INSERT INTO build_team_has_reviewer (build_team_id, uuid) " + + "VALUES (?, ?);")) { + stmt.setInt(1, id); + stmt.setString(2, reviewerUUID); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean removeReviewer(int id, String reviewerUUID) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("DELETE FROM build_team_has_reviewer " + + "WHERE build_team_id = ? AND uuid = ?;")) { + stmt.setInt(1, id); + stmt.setString(2, reviewerUUID); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 69249232..80ab519f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -197,8 +197,9 @@ public boolean canReviewPlot(Builder builder, Plot plot) { stmt.setString(1, builder.getUUID().toString()); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { - BuildTeam team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); - if (team.getReviewers().stream().anyMatch(b -> b.getUUID() == builder.getUUID())) + Optional team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); + if (team.isEmpty()) continue; + if (team.get().getCountries().stream().anyMatch(c -> Objects.equals(c.getCode(), plot.getCity().getCountry().getCode()))) return true; } } @@ -217,6 +218,21 @@ public boolean isAnyReviewer(UUID uuid) { return false; } + public List getReviewersByBuildTeam(int buildTeamId) { + List builders = new ArrayList<>(); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT uuid FROM build_team_has_reviewer WHERE build_team_id = ?;")) { + try (ResultSet rs = stmt.executeQuery()) { + stmt.setInt(1, buildTeamId); + while (rs.next()) { + Builder builder = getBuilderByUUID(UUID.fromString(rs.getString(1))); + if (builder != null) builders.add(builder); + } + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + return builders; + } + /** * Retrieves the leaderboard entry for a specific player based on their UUID and the specified timeframe. * The leaderboard entry includes the player's score, rank, and total number of players. diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index c1acf7c3..2bdd4e24 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -42,6 +42,21 @@ public Optional getCountryByCode(String code) { return cachedCountries.stream().filter(c -> c.getCode().equals(code)).findFirst(); } + public List getCountriesByBuildTeam(int id) { + List countries = new ArrayList<>(); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT country_code FROM build_team_has_country WHERE build_team_id = ?;")) { + try (ResultSet rs = stmt.executeQuery()) { + stmt.setInt(1, id); + while (rs.next()) { + Optional country = getCountryByCode(rs.getString(1)); + country.ifPresent(countries::add); + } + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + return countries; + } + public boolean setMaterialAndCustomModelData(String code, String material, @Nullable String customModelData) { try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;")) { From 9bc0d8b6756b9df630c2719d0d7501af9d6a219f Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 27 Feb 2025 06:12:07 +0100 Subject: [PATCH 043/175] change build team behaviour to have city projects assigned to build teams instead of countries --- .../admin/setup/CMD_Setup_BuildTeam.java | 57 +++++++++---------- .../core/database/DataProvider.java | 2 +- .../database/providers/BuildTeamProvider.java | 22 +++---- .../database/providers/BuilderProvider.java | 2 +- .../providers/CityProjectProvider.java | 15 +++++ .../database/providers/CountryProvider.java | 15 ----- .../plotsystem/core/system/BuildTeam.java | 26 ++++----- 7 files changed, 69 insertions(+), 70 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 228b864a..28e3a7c3 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -30,7 +30,7 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.command.CommandSender; @@ -52,8 +52,8 @@ private void register() { registerSubCommand(new CMD_Setup_BuildTeam_Add(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_Remove(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_SetName(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_BuildTeam_AddCountry(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_BuildTeam_RemoveCountry(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_BuildTeam_AddCityProject(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_BuildTeam_RemoveCityProject(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_AddReviewer(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_RemoveReviewer(getBaseCommand(), this)); } @@ -100,13 +100,13 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + buildTeams.size() + " build teams registered in the database:")); sender.sendMessage(text("--------------------------", DARK_GRAY)); for (BuildTeam b : buildTeams) { - StringJoiner countriesAsString = new StringJoiner(", "); + StringJoiner citiesAsString = new StringJoiner(", "); StringJoiner reviewersAsString = new StringJoiner(", "); - b.getCountries().forEach(c -> countriesAsString.add(c.getCode())); + b.getCityProjects().forEach(c -> citiesAsString.add(c.getID())); b.getReviewers().forEach(r -> reviewersAsString.add(r.getName())); sender.sendMessage(text(" » ", DARK_GRAY) .append(text(b.getID() + " (" + b.getName() + ") ", AQUA)) - .append(text("- Country Codes: " + (countriesAsString.length() == 0 ? "No Countries" : countriesAsString) + .append(text("- City Project IDs: " + (citiesAsString.length() == 0 ? "No City Projects" : citiesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString), WHITE))); } sender.sendMessage(text("--------------------------", DARK_GRAY)); @@ -267,38 +267,38 @@ public String getPermission() { } } - public static class CMD_Setup_BuildTeam_AddCountry extends SubCommand { - public CMD_Setup_BuildTeam_AddCountry(BaseCommand baseCommand, SubCommand subCommand) { + public static class CMD_Setup_BuildTeam_AddCityProject extends SubCommand { + public CMD_Setup_BuildTeam_AddCityProject(BaseCommand baseCommand, SubCommand subCommand) { super(baseCommand, subCommand); } @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null || AlpsUtils.tryParseInt(args[2]) == null) { + if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) { sendInfo(sender); return; } Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - Optional country = DataProvider.COUNTRY.getCountryByCode(args[2]); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[2]); - // Check if build team and country exists if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } - if (country.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is already added to the build team!")); + if (cityProject == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("City Project could not be found!")); return; } - boolean successful = buildTeam.get().addCountry(country.get()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country '" + country.get().getCode() + "' to build team with ID " + args[1] + "!")); + + boolean successful = buildTeam.get().addCityProject(cityProject); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added city project '" + cityProject.getID() + "' to build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override public String[] getNames() { - return new String[]{"addcountry"}; + return new String[]{"addcityproject"}; } @Override @@ -308,17 +308,17 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"BuildTeam-ID", "Country-Code"}; + return new String[]{"BuildTeam-ID", "CityProject-ID"}; } @Override public String getPermission() { - return "plotsystem.admin.pss.buildteam.addcountry"; + return "plotsystem.admin.pss.buildteam.addcityproject"; } } - public static class CMD_Setup_BuildTeam_RemoveCountry extends SubCommand { - public CMD_Setup_BuildTeam_RemoveCountry(BaseCommand baseCommand, SubCommand subCommand) { + public static class CMD_Setup_BuildTeam_RemoveCityProject extends SubCommand { + public CMD_Setup_BuildTeam_RemoveCityProject(BaseCommand baseCommand, SubCommand subCommand) { super(baseCommand, subCommand); } @@ -330,26 +330,25 @@ public void onCommand(CommandSender sender, String[] args) { } Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - Optional country = DataProvider.COUNTRY.getCountryByCode(args[2]); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[2]); - // Check if build team and country exists if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } - if (country.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Country could not be found or is not added to the build team!")); + if (cityProject == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("City project could not be found!")); return; } - boolean successful = buildTeam.get().removeCountry(country.get().getCode()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country '" + country.get().getCode() + "' from build team with ID " + args[1] + "!")); + boolean successful = buildTeam.get().removeCityProject(cityProject.getID()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed city project '" + cityProject.getID() + "' from build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @Override public String[] getNames() { - return new String[]{"removecountry"}; + return new String[]{"removecityproject"}; } @Override @@ -359,12 +358,12 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"BuildTeam-ID", "Country-Code"}; + return new String[]{"BuildTeam-ID", "CityProject-ID"}; } @Override public String getPermission() { - return "plotsystem.admin.pss.buildteam.removecountry"; + return "plotsystem.admin.pss.buildteam.removecityproject"; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index 18c4b1a2..e5eb0705 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -34,5 +34,5 @@ public class DataProvider { public static final CountryProvider COUNTRY = new CountryProvider(); public static final ServerProvider SERVER = new ServerProvider(); public static final TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); - public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(BUILDER, COUNTRY); // has to be initialized after builder and country providers + public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(BUILDER, CITY_PROJECT); // has to be initialized after builder and city project providers } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 240c2f3c..0c1bc0d1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -1,10 +1,10 @@ package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; @@ -21,15 +21,15 @@ public class BuildTeamProvider { public static final List BUILD_TEAMS = new ArrayList<>(); - public BuildTeamProvider(BuilderProvider builderProvider, CountryProvider countryProvider) { + public BuildTeamProvider(BuilderProvider builderProvider, CityProjectProvider cityProjectProvider) { // cache all build teams try (ResultSet rs = DatabaseConnection.createStatement("SELECT build_team_id, name FROM build_team").executeQuery()) { while (rs.next()) { int buildTeamId = rs.getInt(1); - List countries = countryProvider.getCountriesByBuildTeam(buildTeamId); + List cityProjects = cityProjectProvider.getCityProjectsByBuildTeam(buildTeamId); List reviewers = builderProvider.getReviewersByBuildTeam(buildTeamId); - BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), countries, reviewers)); + BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), cityProjects, reviewers)); } DatabaseConnection.closeResultSet(rs); } catch (SQLException ex) { @@ -109,23 +109,23 @@ public boolean setBuildTeamName(int id, String newName) { return false; } - public boolean addCountry(int id, String countryCode) { + public boolean addCityProject(int id, String cityId) { try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO build_team_has_country (build_team_id, country_code) " + + .prepareStatement("INSERT INTO build_team_has_city_project (build_team_id, city_project_id) " + "VALUES (?, ?);")) { stmt.setInt(1, id); - stmt.setString(2, countryCode); + stmt.setString(2, cityId); return stmt.executeUpdate() > 0; } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } - public boolean removeCountry(int id, String countryCode) { + public boolean removeCityProject(int id, String cityId) { try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM build_team_has_country " + - "WHERE build_team_id = ? AND country_code = ?;")) { + .prepareStatement("DELETE FROM build_team_has_city_project " + + "WHERE build_team_id = ? AND city_project_id = ?;")) { stmt.setInt(1, id); - stmt.setString(2, countryCode); + stmt.setString(2, cityId); return stmt.executeUpdate() > 0; } catch (SQLException ex) {Utils.logSqlException(ex);} return false; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 80ab519f..5e78a528 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -199,7 +199,7 @@ public boolean canReviewPlot(Builder builder, Plot plot) { while (rs.next()) { Optional team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); if (team.isEmpty()) continue; - if (team.get().getCountries().stream().anyMatch(c -> Objects.equals(c.getCode(), plot.getCity().getCountry().getCode()))) + if (team.get().getCityProjects().stream().anyMatch(c -> Objects.equals(c.getID(), plot.getCity().getID()))) return true; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index d7510838..fd1917e6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -86,6 +86,21 @@ public List get(boolean onlyVisible) { return null; } + public List getCityProjectsByBuildTeam(int id) { + List cityProjects = new ArrayList<>(); + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT city_project_id FROM build_team_has_city_project WHERE build_team_id = ?;")) { + try (ResultSet rs = stmt.executeQuery()) { + stmt.setInt(1, id); + while (rs.next()) { + CityProject city = getById(rs.getString(1)); + if(city != null) cityProjects.add(city); + } + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + return cityProjects; + } + public boolean add(String id, String countryCode, String serverName) { if (getById(id) != null) return true; try (PreparedStatement stmt = DatabaseConnection.getConnection() diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index 2bdd4e24..c1acf7c3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -42,21 +42,6 @@ public Optional getCountryByCode(String code) { return cachedCountries.stream().filter(c -> c.getCode().equals(code)).findFirst(); } - public List getCountriesByBuildTeam(int id) { - List countries = new ArrayList<>(); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT country_code FROM build_team_has_country WHERE build_team_id = ?;")) { - try (ResultSet rs = stmt.executeQuery()) { - stmt.setInt(1, id); - while (rs.next()) { - Optional country = getCountryByCode(rs.getString(1)); - country.ifPresent(countries::add); - } - } - } catch (SQLException ex) {Utils.logSqlException(ex);} - return countries; - } - public boolean setMaterialAndCustomModelData(String code, String material, @Nullable String customModelData) { try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;")) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 3965cf51..333a32aa 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -32,13 +32,13 @@ public class BuildTeam { private final int ID; private String name; - private final List countries; + private final List cityProjects; private final List reviewers; - public BuildTeam(int ID, String name, List countries, List reviewers) { + public BuildTeam(int ID, String name, List cities, List reviewers) { this.ID = ID; this.name = name; - this.countries = countries; + this.cityProjects = cities; this.reviewers = reviewers; } @@ -50,8 +50,8 @@ public String getName() { return name; } - public List getCountries() { - return countries; + public List getCityProjects() { + return cityProjects; } public List getReviewers() { @@ -66,19 +66,19 @@ public boolean setName(String newName) { return false; } - public boolean addCountry(Country country) { - if (DataProvider.BUILD_TEAM.addCountry(ID, country.getCode())) { - this.countries.add(country); + public boolean addCityProject(CityProject city) { + if (DataProvider.BUILD_TEAM.addCityProject(ID, city.getID())) { + this.cityProjects.add(city); return true; } return false; } - public boolean removeCountry(String countryCode) { - Optional removeCountry = countries.stream().filter(c -> c.getCode().equalsIgnoreCase(countryCode)).findFirst(); - if (removeCountry.isEmpty()) return false; - if (DataProvider.BUILD_TEAM.removeCountry(ID, countryCode)) { - this.countries.remove(removeCountry.get()); + public boolean removeCityProject(String cityId) { + Optional removeCity = cityProjects.stream().filter(c -> c.getID().equalsIgnoreCase(cityId)).findFirst(); + if (removeCity.isEmpty()) return false; + if (DataProvider.BUILD_TEAM.removeCityProject(ID, cityId)) { + this.cityProjects.remove(removeCity.get()); return true; } return false; From 5252fe0e2baeaa26c3c251cafae6dfe4971c7aec Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 27 Feb 2025 16:38:12 +0100 Subject: [PATCH 044/175] change CityProjectProvider.java to be consistent with the other providers --- .../admin/setup/CMD_Setup_BuildTeam.java | 16 ++-- .../commands/admin/setup/CMD_Setup_City.java | 16 ++-- .../providers/CityProjectProvider.java | 73 +++++++------------ .../plotsystem/core/system/CityProject.java | 2 - .../core/system/plot/utils/PlotUtils.java | 5 +- 5 files changed, 45 insertions(+), 67 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 28e3a7c3..73ce204e 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -280,19 +280,19 @@ public void onCommand(CommandSender sender, String[] args) { } Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[2]); + Optional cityProject = DataProvider.CITY_PROJECT.getById(args[2]); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } - if (cityProject == null) { + if (cityProject.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("City Project could not be found!")); return; } - boolean successful = buildTeam.get().addCityProject(cityProject); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added city project '" + cityProject.getID() + "' to build team with ID " + args[1] + "!")); + boolean successful = buildTeam.get().addCityProject(cityProject.get()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added city project '" + cityProject.get().getID() + "' to build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -330,19 +330,19 @@ public void onCommand(CommandSender sender, String[] args) { } Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[2]); + Optional cityProject = DataProvider.CITY_PROJECT.getById(args[2]); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); return; } - if (cityProject == null) { + if (cityProject.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("City project could not be found!")); return; } - boolean successful = buildTeam.get().removeCityProject(cityProject.getID()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed city project '" + cityProject.getID() + "' from build team with ID " + args[1] + "!")); + boolean successful = buildTeam.get().removeCityProject(cityProject.get().getID()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed city project '" + cityProject.get().getID() + "' from build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index e4538099..ca25e5f8 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -191,8 +191,8 @@ public void onCommand(CommandSender sender, String[] args) { String cityProjectId = args[1]; // Check if City Project exists - CityProject cityProject = DataProvider.CITY_PROJECT.getById(cityProjectId); - if (cityProject == null) { + Optional cityProject = DataProvider.CITY_PROJECT.getById(cityProjectId); + if (cityProject.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any City Project with ID " + cityProjectId + "!")); sender.sendMessage(Utils.ChatUtils.getAlertFormat("Type to see all City Projects!")); return; @@ -234,8 +234,8 @@ public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2) {sendInfo(sender); return;} // Check if City Project exits - CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[1]); - if (cityProject == null) return; + Optional cityProject = DataProvider.CITY_PROJECT.getById(args[1]); + if (cityProject.isEmpty()) return; String serverName = args[2]; if (serverName.length() > 255) { @@ -249,7 +249,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean successful = cityProject.setServer(serverName); + boolean successful = cityProject.get().setServer(serverName); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed server of City Project with ID " + args[1] + " to '" + serverName + "'!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project server!")); } @@ -285,12 +285,12 @@ public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2) {sendInfo(sender); return;} // Check if City Project exits - CityProject cityProject = DataProvider.CITY_PROJECT.getById(args[1]); - if (cityProject == null) return; + Optional cityProject = DataProvider.CITY_PROJECT.getById(args[1]); + if (cityProject.isEmpty()) return; if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) return; boolean isVisible = args[2].equalsIgnoreCase("true"); - boolean successful = cityProject.setVisible(isVisible); + boolean successful = cityProject.get().setVisible(isVisible); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set visibility of City Project with ID " + args[1] + " to " + args[2].toUpperCase() + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project visibility!")); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index fd1917e6..3c35f365 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -33,57 +33,36 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; +import java.util.Optional; public class CityProjectProvider { - public static final List cityProjects = new ArrayList<>(); + public static final List cachedCityProjects = new ArrayList<>(); - public CityProject getById(String id) { - return cityProjects.stream().filter(c -> c.getID().equals(id)).findFirst() - .orElseGet(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT country_code, server_name, is_visible FROM city_project " + - "WHERE city_project_id = ?;")) { - stmt.setString(1, id); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new CityProject(id, rs.getString(1), rs.getString(2), - rs.getBoolean(3)); - } - } - } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; - }); - } - - public List getByCountryCode(String countryCode, boolean onlyVisible) { + public CityProjectProvider() { + // cache all city projects try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT city_project_id FROM city_project WHERE country_code = ? " + - "AND is_visible = ?;")) { - stmt.setString(1, countryCode); - stmt.setBoolean(2, onlyVisible); - + .prepareStatement("SELECT city_project_id, country_code, server_name, is_visible FROM city_project;")) { try (ResultSet rs = stmt.executeQuery()) { - List cityProjects = new ArrayList<>(); - while (rs.next()) cityProjects.add(getById(rs.getString(1))); - return cityProjects; + while (rs.next()) cachedCityProjects.add(new CityProject( + rs.getString(1), + rs.getString(2), + rs.getString(3), + rs.getBoolean(4) + )); } } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; } - public List get(boolean onlyVisible) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT city_project_id FROM city_project WHERE is_visible = ?;")) { - stmt.setBoolean(1, onlyVisible); + public Optional getById(String id) { + return cachedCityProjects.stream().filter(c -> c.getID().equals(id)).findFirst(); + } - try (ResultSet rs = stmt.executeQuery()) { - List cityProjects = new ArrayList<>(); - while (rs.next()) cityProjects.add(getById(rs.getString(1))); - return cityProjects; - } - } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; + public List getByCountryCode(String countryCode, boolean onlyVisible) { + return cachedCityProjects.stream().filter(c -> (!onlyVisible || c.isVisible()) && c.getCountry().getCode().equals(countryCode)).toList(); + } + + public List get(boolean onlyVisible) { + return cachedCityProjects.stream().filter(c -> !onlyVisible || c.isVisible()).toList(); } public List getCityProjectsByBuildTeam(int id) { @@ -93,8 +72,8 @@ public List getCityProjectsByBuildTeam(int id) { try (ResultSet rs = stmt.executeQuery()) { stmt.setInt(1, id); while (rs.next()) { - CityProject city = getById(rs.getString(1)); - if(city != null) cityProjects.add(city); + Optional city = getById(rs.getString(1)); + city.ifPresent(cityProjects::add); } } } catch (SQLException ex) {Utils.logSqlException(ex);} @@ -102,7 +81,7 @@ public List getCityProjectsByBuildTeam(int id) { } public boolean add(String id, String countryCode, String serverName) { - if (getById(id) != null) return true; + if (getById(id).isPresent()) return true; try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("INSERT INTO city_project (city_project_id, country_code, server_name) " + "VALUES (?, ?, ?);")) { @@ -115,14 +94,14 @@ public boolean add(String id, String countryCode, String serverName) { } public boolean remove(String id) { - CityProject cityProject = getById(id); - if (cityProject == null) return false; + Optional cityProject = getById(id); + if (cityProject.isEmpty()) return false; try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("DELETE FROM city_project WHERE city_project_id = ?;")) { stmt.setString(1, id); boolean result = stmt.executeUpdate() > 0; - if (result) cityProjects.remove(cityProject); + if (result) cachedCityProjects.remove(cityProject.get()); return result; } catch (SQLException ex) { Utils.logSqlException(ex); } return false; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index 772ed19e..2b5c8cc9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -27,7 +27,6 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.providers.CityProjectProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; @@ -59,7 +58,6 @@ public CityProject(String id, String countryCode, String serverName, boolean isV this.countryCode = countryCode; this.serverName = serverName; this.isVisible = isVisible; - CityProjectProvider.cityProjects.add(this); } public String getID() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 92cd2d4a..6fd3c4ef 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -119,9 +119,10 @@ public static AbstractPlot getCurrentPlot(@NotNull Builder builder, Status... st return null; } else if (PlotWorld.isCityPlotWorld(worldName)) { String cityID = worldName.substring(2); - CityProject city = DataProvider.CITY_PROJECT.getById(cityID); - List plots = DataProvider.PLOT.getPlots(city, statuses); + Optional city = DataProvider.CITY_PROJECT.getById(cityID); + if (city.isEmpty()) return null; + List plots = DataProvider.PLOT.getPlots(city.get(), statuses); if (plots.isEmpty()) return null; if (plots.size() == 1) return plots.getFirst(); From 14b37e93dd06ce7476f3ced6f9f882568b4e86d0 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 27 Feb 2025 16:55:24 +0100 Subject: [PATCH 045/175] implement last remaining method "getReviewerCities" in BuildTeamProvider --- .../plotsystem/core/EventListener.java | 5 +-- .../database/providers/BuildTeamProvider.java | 17 ++++++--- .../plotsystem/core/menus/ReviewMenu.java | 36 +++++++++---------- 3 files changed, 34 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 63809be5..fa0f323f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.core.menus.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; @@ -304,8 +305,8 @@ private void sendNotices(@NotNull Player player, Builder builder) { // Informing reviewer about new reviews if (player.hasPermission("plotsystem.admin") || DataProvider.BUILDER.isAnyReviewer(builder.getUUID())) { - List reviewerCountries = DataProvider.BUILD_TEAM.getReviewerCountries(builder); - List unreviewedPlots = DataProvider.PLOT.getPlots(reviewerCountries, Status.unreviewed); + List reviewerCityProjects = DataProvider.BUILD_TEAM.getReviewerCities(builder); + List unreviewedPlots = DataProvider.PLOT.getPlots(reviewerCityProjects, Status.unreviewed); if (!unreviewedPlots.isEmpty()) { PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, player); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 0c1bc0d1..0e1261d6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -5,7 +5,6 @@ import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; import java.sql.PreparedStatement; @@ -20,8 +19,11 @@ public class BuildTeamProvider { public static final List BUILD_TEAMS = new ArrayList<>(); + private final CityProjectProvider cityProjectProvider; public BuildTeamProvider(BuilderProvider builderProvider, CityProjectProvider cityProjectProvider) { + this.cityProjectProvider = cityProjectProvider; + // cache all build teams try (ResultSet rs = DatabaseConnection.createStatement("SELECT build_team_id, name FROM build_team").executeQuery()) { while (rs.next()) { @@ -153,8 +155,15 @@ public boolean removeReviewer(int id, String reviewerUUID) { return false; } - public List getReviewerCountries(Builder builder) { - // TODO: implement - return List.of(); + public List getReviewerCities(Builder builder) { + List buildTeams = BUILD_TEAMS.stream().filter(b + -> b.getReviewers().stream().anyMatch(r -> r.getUUID() == builder.getUUID())).toList(); + List cities = new ArrayList<>(); + + for (BuildTeam buildTeam : buildTeams) { + cities.addAll(cityProjectProvider.getCityProjectsByBuildTeam(buildTeam.getID())); + } + + return cities; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 59e36f3e..18adea34 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -28,7 +28,7 @@ import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Country; +import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; @@ -48,8 +48,8 @@ import java.util.stream.Collectors; public class ReviewMenu extends AbstractPaginatedMenu { - private List countries = new ArrayList<>(); - private Country filteredCountry = null; + private List cityProjects = new ArrayList<>(); + private CityProject filteredCityProject = null; public ReviewMenu(Player player) { super(6, 4, LangUtil.getInstance().get(player, LangPaths.Review.MANAGE_AND_REVIEW_PLOTS), player); @@ -58,9 +58,9 @@ public ReviewMenu(Player player) { @Override protected List getSource() { List plots = new ArrayList<>(); - countries = DataProvider.BUILD_TEAM.getReviewerCountries(Builder.byUUID(getMenuPlayer().getUniqueId())); - plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unreviewed)); - plots.addAll(DataProvider.PLOT.getPlots(countries, Status.unfinished)); + cityProjects = DataProvider.BUILD_TEAM.getReviewerCities(Builder.byUUID(getMenuPlayer().getUniqueId())); + plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unreviewed)); + plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unfinished)); return plots; } @@ -130,13 +130,13 @@ protected void setItemClickEventsAsync() { // Set click event for filter item getMenu().getSlot(7).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - if (countries.isEmpty()) return; + if (cityProjects.isEmpty()) return; - if (filteredCountry == null) { - filteredCountry = countries.getFirst(); + if (filteredCityProject == null) { + filteredCityProject = cityProjects.getFirst(); } else { - int index = countries.indexOf(filteredCountry); - filteredCountry = index + 1 >= countries.size() ? null : countries.get(index + 1); + int index = cityProjects.indexOf(filteredCityProject); + filteredCityProject = index + 1 >= cityProjects.size() ? null : cityProjects.get(index + 1); } reloadMenuAsync(false); @@ -177,25 +177,25 @@ protected Mask getMask() { private List getFilteredPlots(List plots) { List filteredPlots = plots.stream().map(p -> (Plot) p).collect(Collectors.toList()); - if (filteredCountry != null) - filteredPlots = filteredPlots.stream().filter(p -> p.getCity().getCountry().getCode().equals(filteredCountry.getCode())).collect(Collectors.toList()); + if (filteredCityProject != null) + filteredPlots = filteredPlots.stream().filter(p -> p.getCity().getID().equals(filteredCityProject.getID())).collect(Collectors.toList()); return filteredPlots; } private ItemStack getFilterItem(Player langPlayer) { LegacyLoreBuilder LegacyLoreBuilder = new LegacyLoreBuilder(); - LegacyLoreBuilder.addLine((filteredCountry == null ? "§b§l> §f§l" : "§7") + LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.FILTER)); + LegacyLoreBuilder.addLine((filteredCityProject == null ? "§b§l> §f§l" : "§7") + LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.FILTER)); LegacyLoreBuilder.emptyLine(); - countries.forEach(c -> { - if (filteredCountry != null && filteredCountry.getCode().equals(c.getCode())) { - LegacyLoreBuilder.addLine("§b§l> §f§l" + filteredCountry.getName(langPlayer)); + cityProjects.forEach(c -> { + if (filteredCityProject != null && filteredCityProject.getID().equals(c.getID())) { + LegacyLoreBuilder.addLine("§b§l> §f§l" + filteredCityProject.getName(langPlayer)); } else LegacyLoreBuilder.addLine("§7" + c.getName(langPlayer)); }); return new ItemBuilder(MenuItems.filterItem(getMenuPlayer())) .setLore(LegacyLoreBuilder.build()) - .setEnchanted(filteredCountry != null) + .setEnchanted(filteredCityProject != null) .build(); } From 9fb0e0cde8171804e710413002561d29e1dc81ec Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 27 Feb 2025 17:59:56 +0100 Subject: [PATCH 046/175] implement method to get tutorial plot by plot id --- .../providers/TutorialPlotProvider.java | 61 ++++++++++--------- .../menus/tutorial/TutorialStagesMenu.java | 2 +- .../core/menus/tutorial/TutorialsMenu.java | 2 +- .../core/system/plot/TutorialPlot.java | 4 +- .../core/system/plot/world/PlotWorld.java | 2 +- .../system/tutorial/AbstractPlotTutorial.java | 9 +-- 6 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index ec5fa93d..c9626665 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -32,49 +32,50 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; +import java.util.*; public class TutorialPlotProvider { - public static final List tutorialPlots = new ArrayList<>(); + public static final HashMap tutorialPlots = new HashMap<>(); public static final LinkedList freeTutorialPlotIds = new LinkedList<>(); - public TutorialPlot getById(int id) { - // TODO: implement - return null; + public Optional getById(int id) { + return tutorialPlots.keySet().stream().filter(t -> tutorialPlots.get(t) == id).findFirst(); } - public TutorialPlot getByTutorialId(int tutorialId, String playerUUID) { - return tutorialPlots.stream().filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString() - .equals(playerUUID)).findFirst() - .orElseGet(() -> { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT stage_id, is_complete, last_stage_complete_date FROM " + - "tutorial WHERE tutorial_id = ? AND uuid = ?;")) { - stmt.setInt(1, tutorialId); - stmt.setString(2, playerUUID); + public Optional getByTutorialId(int tutorialId, String playerUUID) { + Optional tutorialPlot = tutorialPlots.keySet().stream() + .filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString().equals(playerUUID)).findFirst(); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - int plotId = freeTutorialPlotIds.isEmpty() ? 0 : freeTutorialPlotIds.poll(); - return new TutorialPlot(plotId, tutorialId, playerUUID, rs.getInt(1), - rs.getBoolean(2), rs.getDate(3).toLocalDate()); - } - } - } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; - }); + if (tutorialPlot.isEmpty()) { + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT stage_id, is_complete, last_stage_complete_date FROM " + + "tutorial WHERE tutorial_id = ? AND uuid = ?;")) { + stmt.setInt(1, tutorialId); + stmt.setString(2, playerUUID); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int plotId = freeTutorialPlotIds.isEmpty() ? 0 : freeTutorialPlotIds.poll(); + TutorialPlot newTutorialPlot = new TutorialPlot(plotId, tutorialId, playerUUID, rs.getInt(1), + rs.getBoolean(2), rs.getDate(3).toLocalDate()); + tutorialPlots.put(newTutorialPlot, plotId); + + return Optional.of(newTutorialPlot); + } + } + } catch (SQLException ex) {Utils.logSqlException(ex);} + } + return tutorialPlot; } public boolean add(int tutorialId, String playerUUID) { - if (getByTutorialId(tutorialId, playerUUID) != null) return false; + if (getByTutorialId(tutorialId, playerUUID).isPresent()) return false; try (PreparedStatement stmt = DatabaseConnection.getConnection() .prepareStatement("INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);")) { stmt.setInt(1, tutorialId); stmt.setString(2, playerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -87,7 +88,7 @@ public boolean setStageId(int tutorialId, String playerUUID, int stageId) { stmt.setInt(3, tutorialId); stmt.setString(4, playerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -100,7 +101,7 @@ public boolean setComplete(int tutorialId, String playerUUID) { stmt.setInt(3, tutorialId); stmt.setString(4, playerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java index 7350bb48..19f59cd4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java @@ -124,7 +124,7 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { - plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, getMenuPlayer().getUniqueId().toString()); + plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, getMenuPlayer().getUniqueId().toString()).orElse(null); if (plot != null) { playerHighestStage = plot.getStageID(); isTutorialCompleted = plot.isComplete(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index 7c003fae..8ab2dff4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -90,7 +90,7 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Set tutorial items - plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()); + plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(TutorialCategory.BEGINNER.getId(), getMenuPlayer().getUniqueId().toString()).orElse(null); if (plot != null) isBeginnerTutorialCompleted = plot.isComplete(); // Set beginner tutorial item diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index 14be51a7..5ad7b375 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -26,7 +26,6 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.providers.TutorialPlotProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; @@ -71,7 +70,6 @@ public TutorialPlot(int plotId, int tutorialId, String uuid, int stageId, boolea this.lastStageActivity = lastStageActivity; tutorialConfig = ConfigUtil.getTutorialInstance().configs[tutorialId]; - TutorialPlotProvider.tutorialPlots.add(plotId, this); } public int getTutorialID() { @@ -184,7 +182,7 @@ public void setTutorialSchematic(int schematicId) { } public static boolean isInProgress(int tutorialId, @NotNull UUID playerUUID) { - TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID.toString()); + TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID.toString()).orElse(null); return plot == null || !plot.isComplete(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index c9959878..63645302 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -249,7 +249,7 @@ public static boolean isCityPlotWorld(String worldName) { public static T getPlotWorldByName(String worldName) { if (isOnePlotWorld(worldName) || isCityPlotWorld(worldName)) { int id = Integer.parseInt(worldName.substring(2)); - AbstractPlot plot = worldName.toLowerCase().startsWith("t-") ? DataProvider.TUTORIAL_PLOT.getById(id) : DataProvider.PLOT.getPlotById(id); + AbstractPlot plot = worldName.toLowerCase().startsWith("t-") ? DataProvider.TUTORIAL_PLOT.getById(id).orElse(null) : DataProvider.PLOT.getPlotById(id); return plot == null ? null : plot.getWorld(); } return null; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index 98b2dd7c..fade50fe 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -49,6 +49,7 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -67,9 +68,9 @@ protected AbstractPlotTutorial(Player player, int tutorialId, int stageId) { CompletableFuture.runAsync(() -> { String playerUUID = player.getUniqueId().toString(); - TutorialPlot plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID); - if (plot == null && DataProvider.TUTORIAL_PLOT.add(tutorialId, playerUUID)) - tutorialPlot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID); + Optional plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID); + if (plot.isEmpty() && DataProvider.TUTORIAL_PLOT.add(tutorialId, playerUUID)) + tutorialPlot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID).orElse(null); // Check if tutorial plot is null if (tutorialPlot == null) { @@ -181,7 +182,7 @@ public void onTutorialStop(UUID playerUUID) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; super.onTutorialStop(playerUUID); if (tutorialPlot != null) tutorialPlot.getWorld().deleteWorld(); - int index = TutorialPlotProvider.tutorialPlots.indexOf(tutorialPlot); + int index = TutorialPlotProvider.tutorialPlots.get(tutorialPlot); TutorialPlotProvider.tutorialPlots.remove(tutorialPlot); TutorialPlotProvider.freeTutorialPlotIds.add(index); } From 253200a63c603e282f22f917763adef20ab8fa66 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 28 Feb 2025 22:59:30 +0100 Subject: [PATCH 047/175] implement basic updates in PlotProvider.java --- .../core/database/providers/PlotProvider.java | 98 +++++++++++++++---- .../plotsystem/core/system/plot/Plot.java | 2 + 2 files changed, 83 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 8334bc22..8942296f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -1,21 +1,18 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Country; -import com.alpsbte.plotsystem.core.system.Review; +import com.alpsbte.plotsystem.core.system.*; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import com.ibm.icu.impl.Pair; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -53,6 +50,33 @@ public Plot getPlotById(int plotId) { } } } catch (SQLException ex) { Utils.logSqlException(ex); } + + + + + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT status, city_project_id, difficulty_id, created_by, create_date, plot_version, outline_bounds, last_activity_date, plot_type " + + "FROM plot WHERE plot_id = ?;")) { + stmt.setInt(1, plotId); + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return null; + Status status = Status.valueOf(rs.getString(1)); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString(2)).orElseThrow(); + PlotDifficulty plotDifficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString(3)).orElseThrow().getDifficulty(); + Builder plotCreator = DataProvider.BUILDER.getBuilderByUUID(UUID.fromString(rs.getString(4))); + java.util.Date createdDate = rs.getDate(5); + double plotVersion = rs.getDouble(6); + String outline = rs.getString(7); + LocalDate lastActivity = rs.getDate(8).toLocalDate(); + PlotType plotType = PlotType.valueOf(rs.getString(9)); + + Builder owner = getPlotOwner(plotId); + List members = getPlotMembers(plotId); + + Plot plot = new Plot(plotId, status, cityProject, plotDifficulty, plotCreator, createdDate, plotVersion, outline, lastActivity, owner, members, plotType); + return plot; + } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } @@ -92,6 +116,11 @@ public List getPlots(Builder builder, Status... statuses) { return List.of(); } + public Builder getPlotOwner(int plotId) { + // TODO: implement + return null; + } + public List getPlotMembers(int plotId) { // TODO: implement return null; @@ -103,18 +132,36 @@ public Review getReview(int plotId) { } public byte[] getInitialSchematic(int plotId) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT initial_schematic FROM plot WHERE plot_id = ?;")) { + stmt.setInt(1, plotId); + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return null; + return rs.getBytes(1); + } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } public byte[] getCompletedSchematic(int plotId) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("SELECT complete_schematic FROM plot WHERE plot_id = ?;")) { + stmt.setInt(1, plotId); + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return null; + return rs.getBytes(1); + } + } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } public boolean setCompletedSchematic(int plotId, byte[] completedSchematic) { - // TODO: implement - // set to default if completedSchematic is null (for undoing review) + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE plot SET complete_schematic = ? WHERE plot_id = ?;")) { + stmt.setBytes(1, completedSchematic); + stmt.setInt(2, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -125,13 +172,22 @@ public boolean setPlotOwner(int plotId, UUID ownerUUID) { } public boolean setLastActivity(int plotId, LocalDate activityDate) { - // TODO: implement - // set last_activity to null if activityDate is null + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE plot SET last_activity_date = ? WHERE plot_id = ?;")) { + stmt.setDate(1, activityDate == null ? null : Date.valueOf(activityDate)); + stmt.setInt(2, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean setStatus(int plotId, Status status) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE plot SET status = ? WHERE plot_id = ?;")) { + stmt.setString(1, status.name()); + stmt.setInt(2, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -141,12 +197,20 @@ public boolean setPlotMembers(int plotId, List members) { } public boolean setPlotType(int plotId, PlotType type) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection() + .prepareStatement("UPDATE plot SET plot_type = ? WHERE plot_id = ?;")) { + stmt.setInt(1, type.getId()); + stmt.setInt(2, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } public boolean deletePlot(int plotId) { - // TODO: implement + try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("DELETE FROM plot WHERE plot_id = ?;")) { + stmt.setInt(1, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 17ddd46e..fd1fc477 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -79,6 +79,7 @@ public Plot( double plotVersion, String outline, LocalDate lastActivity, + Builder owner, List members, PlotType type ) { @@ -91,6 +92,7 @@ public Plot( this.plotVersion = plotVersion; this.outlineString = outline; this.lastActivity = lastActivity; + this.plotOwner = owner; this.plotMembers = members; this.plotType = type; } From 426d061f69daecaa1011661db7738634e323deec Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 1 Mar 2025 18:41:45 +0100 Subject: [PATCH 048/175] remove redundant provider method --- .../core/database/providers/PlotProvider.java | 14 -------------- .../core/system/plot/utils/PlotUtils.java | 2 +- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 8942296f..8a17833d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -5,12 +5,9 @@ import com.alpsbte.plotsystem.core.system.*; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.enums.Status; -import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; -import com.ibm.icu.impl.Pair; import java.sql.*; import java.time.LocalDate; @@ -100,12 +97,6 @@ public List getPlots(List cities, Status... statuses) { return List.of(); } - public List getPlots(List countries, Status status) { - List cities = new ArrayList<>(); - countries.forEach(c -> cities.addAll(c.getCityProjects())); - return getPlots(cities, status); - } - public List getPlots(Builder builder) { // TODO: get plots where builder is either owner or member return List.of(); @@ -213,9 +204,4 @@ public boolean deletePlot(int plotId) { } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } - - public TutorialPlot getTutorialPlotById(int tutorialPlotId) { - // TODO: implement - return null; - } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 6fd3c4ef..9060ca38 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -113,7 +113,7 @@ public static AbstractPlot getCurrentPlot(@NotNull Builder builder, Status... st int id = Integer.parseInt(worldName.substring(2)); AbstractPlot plot = worldName.toLowerCase(Locale.ROOT).startsWith("p-") ? DataProvider.PLOT.getPlotById(id) - : DataProvider.PLOT.getTutorialPlotById(id); + : DataProvider.TUTORIAL_PLOT.getById(id).orElseThrow(); if (statuses == null) return plot; for (Status status : statuses) if (status == plot.getStatus()) return plot; return null; From 965214222405f77c9118a1030be04835713cb897 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 1 Mar 2025 22:50:11 +0100 Subject: [PATCH 049/175] continue work on PlotProvider --- .../database/providers/BuilderProvider.java | 2 +- .../core/database/providers/PlotProvider.java | 229 ++++++++++++------ .../core/menus/PlayerPlotsMenu.java | 2 +- .../plotsystem/core/menus/ReviewMenu.java | 6 +- .../plotsystem/core/menus/ReviewPlotMenu.java | 4 +- .../core/menus/companion/CompanionMenu.java | 2 +- .../core/system/plot/AbstractPlot.java | 20 +- .../plotsystem/core/system/plot/Plot.java | 222 ++++++++--------- .../core/system/plot/TutorialPlot.java | 2 +- .../core/system/plot/world/CityPlotWorld.java | 2 +- 10 files changed, 282 insertions(+), 209 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 5e78a528..8f849207 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -199,7 +199,7 @@ public boolean canReviewPlot(Builder builder, Plot plot) { while (rs.next()) { Optional team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); if (team.isEmpty()) continue; - if (team.get().getCityProjects().stream().anyMatch(c -> Objects.equals(c.getID(), plot.getCity().getID()))) + if (team.get().getCityProjects().stream().anyMatch(c -> Objects.equals(c.getID(), plot.getCityProject().getID()))) return true; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 8a17833d..df748b11 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -16,100 +16,160 @@ import java.util.UUID; public class PlotProvider { - public Plot getPlotById(int plotId) { - try (Connection con = DatabaseConnection.getConnection()) { - try (PreparedStatement stmt = con.prepareStatement("SELECT city_project_id, difficulty_id, status," + - " score, outline_bounds, last_activity_date, plot_version FROM plot WHERE plot_id = ?")) { - stmt.setInt(1, plotId); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - Status status = Status.valueOf(rs.getString(3)); - if (status != Status.unclaimed) { - try (PreparedStatement stmt2 = con.prepareStatement("SELECT uuid, 'owner' AS role FROM " + - "builder_is_plot_owner WHERE plot_id = ? UNION SELECT uuid, 'member' AS role FROM " + - "builder_is_plot_member WHERE plot_id = ?;")) { - stmt2.setInt(1, plotId); - stmt2.setInt(2, plotId); - UUID plotOwner; - List memberUUIDs = new ArrayList<>(); - try (ResultSet rs2 = stmt2.executeQuery()) { - while (rs2.next()) { - UUID uuid = UUID.fromString(rs2.getString(1)); - String role = rs2.getString(2); - if (role.equals("owner")) plotOwner = uuid; - else memberUUIDs.add(uuid); - } - } - } - } - } - } - } - } catch (SQLException ex) { Utils.logSqlException(ex); } - - - + private static final String PLOT_SQL_COLUMNS = "plot.plot_id, plot.city_project_id, plot.difficulty_id, " + + "plot.owner_uuid, plot.status, plot.score, plot.outline_bounds, plot.last_activity_date, " + + "plot.plot_version, plot.plot_type"; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT status, city_project_id, difficulty_id, created_by, create_date, plot_version, outline_bounds, last_activity_date, plot_type " - + "FROM plot WHERE plot_id = ?;")) { + public Plot getPlotById(int plotId) { + String query = "SELECT city_project_id, difficulty_id, owner_uuid, status, score, " + + "outline_bounds, last_activity_date, plot_version, plot_type FROM plot WHERE plot_id = ?;"; + try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(query)) { stmt.setInt(1, plotId); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) return null; - Status status = Status.valueOf(rs.getString(1)); - CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString(2)).orElseThrow(); - PlotDifficulty plotDifficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString(3)).orElseThrow().getDifficulty(); - Builder plotCreator = DataProvider.BUILDER.getBuilderByUUID(UUID.fromString(rs.getString(4))); - java.util.Date createdDate = rs.getDate(5); - double plotVersion = rs.getDouble(6); - String outline = rs.getString(7); - LocalDate lastActivity = rs.getDate(8).toLocalDate(); - PlotType plotType = PlotType.valueOf(rs.getString(9)); - - Builder owner = getPlotOwner(plotId); - List members = getPlotMembers(plotId); - - Plot plot = new Plot(plotId, status, cityProject, plotDifficulty, plotCreator, createdDate, plotVersion, outline, lastActivity, owner, members, plotType); - return plot; + CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString(1)).orElseThrow(); + PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString(2)).orElseThrow().getDifficulty(); + UUID ownerUUID = UUID.fromString(rs.getString(3)); + Status status = Status.valueOf(rs.getString(4)); + int score = rs.getInt(5); + String outlineBounds = rs.getString(6); + LocalDate lastActivity = rs.getDate(7).toLocalDate(); + double version = rs.getDouble(8); + PlotType type = PlotType.byId(rs.getInt(9)); + + return new Plot(plotId, cityProject, difficulty, ownerUUID, status, score, outlineBounds, + lastActivity, version, type, getPlotMembers(plotId)); } } catch (SQLException ex) {Utils.logSqlException(ex);} return null; } public List getPlots(Status status) { - // TODO: implement + String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE status = ?;"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + + stmt.setString(1, status.name()); + + try (ResultSet rs = stmt.executeQuery()) { + List plots = new ArrayList<>(); + while (rs.next()) { + plots.add(extractPlot(rs)); + } + return plots; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return List.of(); } public List getPlots(CityProject city, Status... statuses) { - // TODO: implement + String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ?"; + query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + + stmt.setString(1, city.getID()); + for (int i = 0; i < statuses.length; i++) stmt.setString(i + 2, statuses[i].name()); + + try (ResultSet rs = stmt.executeQuery()) { + List plots = new ArrayList<>(); + while (rs.next()) plots.add(extractPlot(rs)); + return plots; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return List.of(); } public List getPlots(CityProject city, PlotDifficulty plotDifficulty, Status status) { - // TODO: implement + String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ? AND difficulty_id = ? " + + "AND status = ?;"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + + stmt.setString(1, city.getID()); + stmt.setString(2, plotDifficulty.name()); + stmt.setString(3, status.name()); + + try (ResultSet rs = stmt.executeQuery()) { + List plots = new ArrayList<>(); + while (rs.next()) plots.add(extractPlot(rs)); + return plots; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return List.of(); } public List getPlots(List cities, Status... statuses) { - // TODO: implement - return List.of(); - } + if (cities.isEmpty()) return List.of(); + + String cityPlaceholders = "?,".repeat(cities.size() - 1) + "?"; + String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id IN (" + cityPlaceholders + ")"; + query += statuses.length > 0 ? " AND status IN (?,".repeat(statuses.length - 1) + "?);" : ";"; - public List getPlots(Builder builder) { - // TODO: get plots where builder is either owner or member + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + + int index = 1; + for (CityProject city : cities) stmt.setString(index++, city.getID()); + for (Status status : statuses) stmt.setString(index++, status.name()); + + try (ResultSet rs = stmt.executeQuery()) { + List plots = new ArrayList<>(); + while (rs.next()) plots.add(extractPlot(rs)); + return plots; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return List.of(); } public List getPlots(Builder builder, Status... statuses) { - // TODO: get plots where builder is either owner or member and filter by status + String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot LEFT JOIN builder_is_plot_member pm ON " + + "plot.plot_id = pm.plot_id WHERE (plot.owner_uuid = ? OR pm.uuid = ?)"; + query += statuses.length > 0 ? "AND plot.status IN (?,".repeat(statuses.length - 1) + "?);" : ";"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + + String builderUUID = builder.getUUID().toString(); + stmt.setString(1, builderUUID); + stmt.setString(2, builderUUID); + for (int i = 0; i < statuses.length; i++) stmt.setString(i + 3, statuses[i].name()); + + try (ResultSet rs = stmt.executeQuery()) { + List plots = new ArrayList<>(); + while (rs.next()) plots.add(extractPlot(rs)); + return plots; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return List.of(); } - public Builder getPlotOwner(int plotId) { - // TODO: implement - return null; + private Plot extractPlot(ResultSet rs) throws SQLException { + int plotId = rs.getInt("plot_id"); + CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString("city_project_id")).orElseThrow(); + PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString("difficulty_id")).orElseThrow().getDifficulty(); + UUID ownerUUID = UUID.fromString(rs.getString("owner_uuid")); + Status status = Status.valueOf(rs.getString("status")); + int score = rs.getInt("score"); + String outlineBounds = rs.getString("outline_bounds"); + LocalDate lastActivity = rs.getDate("last_activity_date").toLocalDate(); + double version = rs.getDouble("plot_version"); + PlotType type = PlotType.byId(rs.getInt("plot_type")); + + return new Plot(plotId, cityProject, difficulty, ownerUUID, status, score, outlineBounds, lastActivity, version, type, getPlotMembers(plotId)); } public List getPlotMembers(int plotId) { @@ -123,8 +183,9 @@ public Review getReview(int plotId) { } public byte[] getInitialSchematic(int plotId) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT initial_schematic FROM plot WHERE plot_id = ?;")) { + String query = "SELECT initial_schematic FROM plot WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) return null; @@ -135,8 +196,9 @@ public byte[] getInitialSchematic(int plotId) { } public byte[] getCompletedSchematic(int plotId) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT complete_schematic FROM plot WHERE plot_id = ?;")) { + String query = "SELECT complete_schematic FROM plot WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) return null; @@ -147,8 +209,9 @@ public byte[] getCompletedSchematic(int plotId) { } public boolean setCompletedSchematic(int plotId, byte[] completedSchematic) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE plot SET complete_schematic = ? WHERE plot_id = ?;")) { + String query = "UPDATE plot SET complete_schematic = ? WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setBytes(1, completedSchematic); stmt.setInt(2, plotId); return stmt.executeUpdate() > 0; @@ -157,8 +220,18 @@ public boolean setCompletedSchematic(int plotId, byte[] completedSchematic) { } public boolean setPlotOwner(int plotId, UUID ownerUUID) { - // TODO: implement - // (should also be able to be set to null in case a plot gets abandoned) + String query = "UPDATE plot SET owner_uuid = ? WHERE plot_id = ?;"; + String query2 = "UPDATE plot SET owner_uuid = DEFAULT(owner_uuid) WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(ownerUUID == null ? query2 : query)) { + if (ownerUUID == null) { + stmt.setInt(1, plotId); + } else { + stmt.setString(1, ownerUUID.toString()); + stmt.setInt(2, plotId); + } + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} return false; } @@ -197,6 +270,18 @@ public boolean setPlotType(int plotId, PlotType type) { return false; } + public boolean setPasted(int plotId, boolean pasted) { + String query = "UPDATE plot SET is_pasted = ? WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + + stmt.setBoolean(1, pasted); + stmt.setInt(2, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) {Utils.logSqlException(ex);} + return false; + } + public boolean deletePlot(int plotId) { try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("DELETE FROM plot WHERE plot_id = ?;")) { stmt.setInt(1, plotId); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 309ae219..f40a4e43 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -102,7 +102,7 @@ protected void setMenuItemsAsync() { getMenu().getSlot(9 + i) .setItem(new ItemBuilder(item) - .setName(text(plot.getCity().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) + .setName(text(plot.getCityProject().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) .setLore(getLore(plot, getMenuPlayer()).build()) .build()); } catch (SQLException ex) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java index 18adea34..30ef55bb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java @@ -88,8 +88,8 @@ protected void setPaginatedMenuItemsAsync(List source) { if (!plot.getPlotMembers().isEmpty()) { lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.MEMBERS) + ": §f" + plot.getPlotMembers().stream().map(Builder::getName).collect(Collectors.joining(", "))); } - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCity().getName(getMenuPlayer())); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": §f" + plot.getCity().getCountry().getName(getMenuPlayer())); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCityProject().getName(getMenuPlayer())); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": §f" + plot.getCityProject().getCountry().getName(getMenuPlayer())); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": §f" + plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase()); getMenu().getSlot(i + 9).setItem(new ItemBuilder(plot.getStatus() == Status.unfinished ? Material.MAP : Material.FILLED_MAP, 1) @@ -178,7 +178,7 @@ protected Mask getMask() { private List getFilteredPlots(List plots) { List filteredPlots = plots.stream().map(p -> (Plot) p).collect(Collectors.toList()); if (filteredCityProject != null) - filteredPlots = filteredPlots.stream().filter(p -> p.getCity().getID().equals(filteredCityProject.getID())).collect(Collectors.toList()); + filteredPlots = filteredPlots.stream().filter(p -> p.getCityProject().getID().equals(filteredCityProject.getID())).collect(Collectors.toList()); return filteredPlots; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java index 390cf6ba..4eb5a2b7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java @@ -354,8 +354,8 @@ private ItemStack getPlotInfoItem() { Player plotOwnerPlayer; plotOwner = plot.getPlotOwner().getName(); - city = plot.getCity().getName(getMenuPlayer()); - country = plot.getCity().getCountry().getName(getMenuPlayer()); + city = plot.getCityProject().getName(getMenuPlayer()); + country = plot.getCityProject().getCountry().getName(getMenuPlayer()); difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); plotOwnerPlayer = plot.getPlotOwner().getPlayer(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 0f90c987..764059b9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -240,7 +240,7 @@ public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPla String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); lore = new LoreBuilder() .addLines(text(plotIdText + ": ", GRAY).append(text(plot.getID(), WHITE)), - text(plotCityText + ": ", GRAY).append(text(plot.getCity().getName(langPlayer), WHITE)), + text(plotCityText + ": ", GRAY).append(text(plot.getCityProject().getName(langPlayer), WHITE)), text(plotDifficultyText + ": ", GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), WHITE)), empty(), statusComp.append(text(": Unassigned", GRAY)).decoration(BOLD, true)) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 4a708f5f..78f6703e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core.system.plot; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.utils.PlotPermissions; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; @@ -42,12 +43,14 @@ import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.Vector3; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; +import java.util.UUID; import static net.kyori.adventure.text.Component.text; @@ -55,7 +58,8 @@ public abstract class AbstractPlot { public static final double PLOT_VERSION = 3; public static final ClipboardFormat CLIPBOARD_FORMAT = BuiltInClipboardFormat.FAST_V2; - protected final int ID; + private final int ID; + protected Builder plotOwner; protected OnePlotWorld onePlotWorld; protected PlotPermissions plotPermissions; @@ -65,8 +69,9 @@ public abstract class AbstractPlot { protected List outline; protected List blockOutline; - public AbstractPlot(int id) { + public AbstractPlot(int id, UUID plotOwnerUUID) { this.ID = id; + this.plotOwner = plotOwnerUUID != null ? DataProvider.BUILDER.getBuilderByUUID(plotOwnerUUID) : null; } /** @@ -79,7 +84,16 @@ public int getID() { /** * @return builder who has claimed the plot */ - public abstract Builder getPlotOwner(); + public Builder getPlotOwner() { + return plotOwner; + } + + /** + * sets the plot owner of the current plot + * @param plotOwner uuid of player + * @return if true, the execution was successful + */ + public abstract boolean setPlotOwner(@Nullable Builder plotOwner); /** * @return plot world, can be one or city plot world diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index fd1fc477..13309731 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -44,102 +44,77 @@ import org.jetbrains.annotations.Nullable; import java.io.IOException; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; -import java.util.Date; +import java.util.ArrayList; import java.util.List; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; public class Plot extends AbstractPlot { - private final CityProject city; + private final CityProject cityProject; private final PlotDifficulty difficulty; - private final Builder plotCreator; - private final Date createdDate; - private final String outlineString; - - private CityPlotWorld cityPlotWorld; private Status status; + private final int score; + private String outlineBounds; private LocalDate lastActivity; - private List plotMembers; + private final List members; + + private CityPlotWorld cityPlotWorld; - // missing: - // outlineBounds - // initialSchem - // is_pasted public Plot( - int id, - Status status, - CityProject city, - PlotDifficulty difficulty, - Builder createdBy, - Date createdDate, - double plotVersion, - String outline, - LocalDate lastActivity, - Builder owner, - List members, - PlotType type - ) { - super(id); - this.status = status; - this.city = city; + int id, CityProject cityProject, PlotDifficulty difficulty, UUID ownerUUID, Status status, int score, + String outlineBounds, LocalDate lastActivity, double version, PlotType type, List members) { + super(id, ownerUUID); + this.cityProject = cityProject; this.difficulty = difficulty; - this.plotCreator = createdBy; - this.createdDate = createdDate; - this.plotVersion = plotVersion; - this.outlineString = outline; + this.status = status; + this.score = score; + this.outlineBounds = outlineBounds; this.lastActivity = lastActivity; - this.plotOwner = owner; - this.plotMembers = members; + this.plotVersion = version; this.plotType = type; - } - - public CityProject getCity() { - return city; - } - - public PlotDifficulty getDifficulty() { - return difficulty; + this.members = members; } @Override - public Builder getPlotOwner() { - return plotOwner; + public Status getStatus() { + return status; } - public boolean setPlotOwner(@Nullable Builder newPlotOwner) { - if (DataProvider.PLOT.setPlotOwner(ID, newPlotOwner == null ? null : newPlotOwner.getUUID())) { - plotOwner = newPlotOwner; + @Override + public boolean setStatus(@NotNull Status status) { + if (DataProvider.PLOT.setStatus(getID(), status)) { + this.status = status; return true; } return false; } - public List getPlotMembers() { - return plotMembers; + public CityProject getCityProject() { + return cityProject; + } + + public PlotDifficulty getDifficulty() { + return difficulty; } - public boolean setPlotMembers(@NotNull List plotMembers) { - if (DataProvider.PLOT.setPlotMembers(ID, plotMembers)) { - this.plotMembers = plotMembers; + @Override + public boolean setPlotOwner(@Nullable Builder plotOwner) { + if (DataProvider.PLOT.setPlotOwner(getID(), plotOwner == null ? null : plotOwner.getUUID())) { + this.plotOwner = plotOwner; return true; } return false; } - @SuppressWarnings("unchecked") @Override - public T getWorld() { - if (getVersion() <= 2 || getPlotType().hasOnePlotPerWorld()) { - if (onePlotWorld == null) onePlotWorld = new OnePlotWorld(this); - return (T) onePlotWorld; - } else { - if (cityPlotWorld == null) cityPlotWorld = new CityPlotWorld(this); - return (T) cityPlotWorld; - } + public double getVersion() { + return plotVersion; } @Override @@ -148,7 +123,7 @@ public List getOutline() { return this.outline; List pointVectors; - pointVectors = getOutlinePoints((outlineString.isEmpty() || getVersion() <= 2) ? null : outlineString); + pointVectors = getOutlinePoints((outlineBounds.isEmpty() || getVersion() <= 2) ? "" : outlineBounds); return pointVectors; } @@ -160,75 +135,71 @@ public LocalDate getLastActivity() { @Override public boolean setLastActivity(boolean setNull) { LocalDate activityDate = setNull ? null : LocalDate.now(); - if (DataProvider.PLOT.setLastActivity(ID, activityDate)) { + if (DataProvider.PLOT.setLastActivity(getID(), activityDate)) { this.lastActivity = activityDate; return true; } return false; } - @Override - public Status getStatus() { - return status; + public List getPlotMembers() { + return members; } @Override - public boolean setStatus(@NotNull Status status) { - if (DataProvider.PLOT.setStatus(ID, status)) { - this.status = status; + public PlotType getPlotType() { + return plotType; + } + + public boolean setPlotType(PlotType type) { + if (DataProvider.PLOT.setPlotType(getID(), type)) { + this.plotType = type; return true; } return false; } + @SuppressWarnings("unchecked") + @Override + public T getWorld() { + if (getVersion() <= 2 || getPlotType().hasOnePlotPerWorld()) { + if (onePlotWorld == null) onePlotWorld = new OnePlotWorld(this); + return (T) onePlotWorld; + } else { + if (cityPlotWorld == null) cityPlotWorld = new CityPlotWorld(this); + return (T) cityPlotWorld; + } + } + public int getTotalScore() { - // TODO: implement - return 0; + return score; } public void setTotalScore(int score) throws SQLException { if (score == -1) { DatabaseConnection.createStatement("UPDATE plotsystem_plots SET score = DEFAULT(score) WHERE id = ?") - .setValue(this.ID).executeUpdate(); + .setValue(getID()).executeUpdate(); } else { DatabaseConnection.createStatement("UPDATE plotsystem_plots SET score = ? WHERE id = ?") - .setValue(score).setValue(this.ID).executeUpdate(); + .setValue(score).setValue(getID()).executeUpdate(); } } public int getSharedScore() { int score = getTotalScore(); if (score != -1 && !getPlotMembers().isEmpty()) { - return (int) Math.floor(score / (getPlotMembers().size() + 1d)); + return (int) Math.floor(score / (members.size() + 1d)); } return score; } - @Override - public PlotType getPlotType() { - return plotType; - } - - public boolean setPlotType(PlotType type) { - if (DataProvider.PLOT.setPlotType(ID, type)) { - this.plotType = type; - return true; - } - return false; - } - - @Override - public double getVersion() { - return plotVersion; - } - @Override public byte[] getInitialSchematicBytes() { - return DataProvider.PLOT.getInitialSchematic(ID); + return DataProvider.PLOT.getInitialSchematic(getID()); } public byte[] getCompletedSchematic() { - return DataProvider.PLOT.getCompletedSchematic(ID); + return DataProvider.PLOT.getCompletedSchematic(getID()); } @Override @@ -243,59 +214,62 @@ public BlockVector3 getCenter() { return null; } - public Slot getSlot() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT first_slot, second_slot, third_slot FROM plotsystem_builders WHERE uuid = ?") - .setValue(this.getPlotOwner().getUUID().toString()).executeQuery()) { + public Slot getSlot() { + String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?"; + try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(query)) { - if (rs.next()) { - for (int i = 1; i <= 3; i++) { - int slot = rs.getInt(i); - if (!rs.wasNull() && slot == getID()) { - DatabaseConnection.closeResultSet(rs); - return Slot.values()[i - 1]; + stmt.setString(1, this.getPlotOwner().getUUID().toString()); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + for (int i = 1; i <= 3; i++) { + int slot = rs.getInt(i); + if (!rs.wasNull() && slot == getID()) { + return Slot.values()[i - 1]; + } } } } - - DatabaseConnection.closeResultSet(rs); - - return null; } + return null; } public Review getReview() { - return DataProvider.PLOT.getReview(ID); + return DataProvider.PLOT.getReview(getID()); } - public void setPasted(boolean pasted) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET pasted = ? WHERE id = ?") - .setValue(pasted).setValue(this.ID).executeUpdate(); + public boolean setPasted(boolean pasted) throws SQLException { + return DataProvider.PLOT.setPasted(getID(), pasted); } - public void addPlotMember(Builder member) { + public boolean addPlotMember(Builder member) { List members = getPlotMembers(); if (members.size() < 3 && members.stream().noneMatch(m -> m.getUUID().equals(member.getUUID()))) { Slot slot = member.getFreeSlot(); if (slot != null) { members.add(member); - setPlotMembers(members); - - member.setSlot(slot, ID); - getPermissions().addBuilderPerms(member.getUUID()); + if (DataProvider.PLOT.setPlotMembers(getID(), members)) { + member.setSlot(slot, getID()); + getPermissions().addBuilderPerms(member.getUUID()); + return true; + } } } + return false; } - public void removePlotMember(Builder member) { + public boolean removePlotMember(Builder member) { List members = getPlotMembers(); - if (!members.isEmpty() && members.stream().anyMatch(m -> m.getUUID().equals(member.getUUID()))) { - members.remove(members.stream().filter(m -> m.getUUID().equals(member.getUUID())).findFirst().orElse(null)); - setPlotMembers(members); - - Slot slot = member.getSlotByPlotId(ID); - if (slot != null) member.setSlot(slot, -1); - if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); + if (!members.isEmpty() && members.contains(member)) { + members.remove(member); + if (DataProvider.PLOT.setPlotMembers(getID(), members)) { + Slot slot = member.getSlotByPlotId(getID()); + if (slot != null) member.setSlot(slot, -1); + if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); + return true; + } } + return false; } public boolean isReviewed() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index 5ad7b375..a2aff1cc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -62,7 +62,7 @@ public class TutorialPlot extends AbstractPlot { private final FileConfiguration tutorialConfig; public TutorialPlot(int plotId, int tutorialId, String uuid, int stageId, boolean isComplete, LocalDate lastStageActivity) { - super(plotId); + super(plotId, UUID.fromString(uuid)); this.tutorialId = tutorialId; this.uuid = UUID.fromString(uuid); this.stageId = stageId; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index b1c201b6..9a005e9d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -43,7 +43,7 @@ public class CityPlotWorld extends PlotWorld { public CityPlotWorld(@NotNull Plot plot) { - super("C-" + plot.getCity().getID(), plot); + super("C-" + plot.getCityProject().getID(), plot); } @Override From 30c6fc63e7a195d6edd6cea80517e979203202ad Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 16 Mar 2025 00:41:50 +0100 Subject: [PATCH 050/175] add empty review provider --- .../com/alpsbte/plotsystem/core/database/DataProvider.java | 1 + .../plotsystem/core/database/providers/ReviewProvider.java | 7 +++++++ 2 files changed, 8 insertions(+) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index e5eb0705..b0323cbc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -34,5 +34,6 @@ public class DataProvider { public static final CountryProvider COUNTRY = new CountryProvider(); public static final ServerProvider SERVER = new ServerProvider(); public static final TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); + public static final ReviewProvider REVIEW = new ReviewProvider(); public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(BUILDER, CITY_PROJECT); // has to be initialized after builder and city project providers } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java new file mode 100644 index 00000000..c5df1892 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -0,0 +1,7 @@ +package com.alpsbte.plotsystem.core.database.providers; + +public class ReviewProvider { + public boolean undoReview() { + return false; + } +} From a994eb7a29b24b1501ee7a199d0c92257ad2948c Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Tue, 25 Mar 2025 20:44:33 +0100 Subject: [PATCH 051/175] fix & implement all data providers, update to current database schema --- .../commands/admin/setup/CMD_Setup_City.java | 3 +- .../database/providers/BuildTeamProvider.java | 137 +++++++----- .../database/providers/BuilderProvider.java | 199 ++++++++++-------- .../providers/CityProjectProvider.java | 85 +++++--- .../database/providers/CountryProvider.java | 69 ++++-- .../providers/DifficultyProvider.java | 55 ++++- .../core/database/providers/PlotProvider.java | 167 +++++++++++---- .../database/providers/ServerProvider.java | 58 +++-- .../providers/TutorialPlotProvider.java | 42 ++-- .../plotsystem/core/system/BuildTeam.java | 10 +- .../plotsystem/core/system/plot/Plot.java | 17 +- .../core/system/plot/TutorialPlot.java | 7 + 12 files changed, 552 insertions(+), 297 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index ca25e5f8..0fb91c52 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -154,7 +154,8 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, country.get().getCode(), serverName); + // TODO: Add build team id to parameter + boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, -1, country.get().getCode(), serverName); if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 0e1261d6..9b44dbf0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -1,12 +1,36 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -15,8 +39,6 @@ import java.util.Optional; import java.util.UUID; -import static net.kyori.adventure.text.Component.text; - public class BuildTeamProvider { public static final List BUILD_TEAMS = new ArrayList<>(); private final CityProjectProvider cityProjectProvider; @@ -25,17 +47,20 @@ public BuildTeamProvider(BuilderProvider builderProvider, CityProjectProvider ci this.cityProjectProvider = cityProjectProvider; // cache all build teams - try (ResultSet rs = DatabaseConnection.createStatement("SELECT build_team_id, name FROM build_team").executeQuery()) { - while (rs.next()) { - int buildTeamId = rs.getInt(1); + String query = "SELECT build_team_id, name FROM build_team;"; + try (Connection connection = DatabaseConnection.getConnection(); + PreparedStatement stmt = connection.prepareStatement(query)) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + int buildTeamId = rs.getInt(1); - List cityProjects = cityProjectProvider.getCityProjectsByBuildTeam(buildTeamId); - List reviewers = builderProvider.getReviewersByBuildTeam(buildTeamId); - BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), cityProjects, reviewers)); + List cityProjects = cityProjectProvider.getCityProjectsByBuildTeam(buildTeamId); + List reviewers = builderProvider.getReviewersByBuildTeam(buildTeamId); + BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), cityProjects, reviewers)); + } } - DatabaseConnection.closeResultSet(rs); } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + Utils.logSqlException(ex); } } @@ -45,19 +70,21 @@ public Optional getBuildTeam(int id) { public List getBuildTeamsByReviewer(UUID reviewerUUID) { List buildTeams = new ArrayList<>(); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?")) { + + String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, reviewerUUID.toString()); + try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Optional buildTeam = getBuildTeam(rs.getInt(1)); if (buildTeam.isEmpty()) continue; buildTeams.add(buildTeam.get()); } - DatabaseConnection.closeResultSet(rs); } } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + Utils.logSqlException(ex); } return buildTeams; } @@ -69,20 +96,27 @@ public List getBuildTeams() { public boolean addBuildTeam(String name) { boolean result = false; if (BUILD_TEAMS.stream().anyMatch(b -> b.getName().equals(name))) return false; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO build_team (name) VALUES (?);")) { + + String query = "INSERT INTO build_team (name) VALUES (?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, name); result = stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } if (result) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT build_team_id FROM build_team WHERE name = ?;")) { + String resultQuery = "SELECT build_team_id FROM build_team WHERE name = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(resultQuery)) { stmt.setString(1, name); try (ResultSet rs = stmt.executeQuery()) { BUILD_TEAMS.add(new BuildTeam(rs.getInt(1), name, List.of(), List.of())); } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } } return result; } @@ -91,67 +125,55 @@ public boolean removeBuildTeam(int id) { Optional cachedBuildTeam = getBuildTeam(id); if (cachedBuildTeam.isEmpty()) return false; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM build_team WHERE build_team_id = ?;")) { + String query = "DELETE FROM build_team WHERE build_team_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, id); boolean result = stmt.executeUpdate() > 0; if (result) BUILD_TEAMS.remove(cachedBuildTeam.get()); return result; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setBuildTeamName(int id, String newName) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE build_team SET name = ? WHERE build_team_id = ?;")) { + String query = "UPDATE build_team SET name = ? WHERE build_team_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, newName); stmt.setInt(2, id); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } - return false; - } - - public boolean addCityProject(int id, String cityId) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO build_team_has_city_project (build_team_id, city_project_id) " + - "VALUES (?, ?);")) { - stmt.setInt(1, id); - stmt.setString(2, cityId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} - return false; - } - - public boolean removeCityProject(int id, String cityId) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM build_team_has_city_project " + - "WHERE build_team_id = ? AND city_project_id = ?;")) { - stmt.setInt(1, id); - stmt.setString(2, cityId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean addReviewer(int id, String reviewerUUID) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO build_team_has_reviewer (build_team_id, uuid) " + - "VALUES (?, ?);")) { + String query = "INSERT INTO build_team_has_reviewer (build_team_id, uuid) VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, id); stmt.setString(2, reviewerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean removeReviewer(int id, String reviewerUUID) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM build_team_has_reviewer " + - "WHERE build_team_id = ? AND uuid = ?;")) { + String query = "DELETE FROM build_team_has_reviewer WHERE build_team_id = ? AND uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, id); stmt.setString(2, reviewerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } @@ -163,7 +185,6 @@ public List getReviewerCities(Builder builder) { for (BuildTeam buildTeam : buildTeams) { cities.addAll(cityProjectProvider.getCityProjectsByBuildTeam(buildTeam.getID())); } - return cities; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 8f849207..60cfb29c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -35,6 +35,7 @@ import com.alpsbte.plotsystem.utils.enums.Slot; import javax.annotation.Nullable; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -45,9 +46,10 @@ public class BuilderProvider { public Builder getBuilderByUUID(UUID uuid) { if (builders.containsKey(uuid)) return builders.get(uuid); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT name, score, first_slot, second_slot, third_slot, plot_type " + - "FROM builder WHERE uuid = ?;")) { + + String query = "SELECT name, score, first_slot, second_slot, third_slot, plot_type FROM builder WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { @@ -56,129 +58,132 @@ public Builder getBuilderByUUID(UUID uuid) { rs.getInt(4), rs.getInt(5), rs.getInt(6)); } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } public Builder getBuilderByName(String name) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT uuid FROM builder WHERE name = ?;")) { + String query = "SELECT uuid FROM builder WHERE name = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, name); try (ResultSet rs = stmt.executeQuery()) { String uuid = rs.getString(1); if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } public boolean addBuilderIfNotExists(UUID uuid, String name) { - // check if builder already exists, if so return TRUE!! if (builders.containsKey(uuid)) return true; - try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("SELECT name FROM builder WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); - try (ResultSet rs = stmt.executeQuery()) { + + String selectQuery = "SELECT 1 FROM builder WHERE uuid = ?;"; + String insertQuery = "INSERT INTO builder (uuid, name) VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement selectStmt = conn.prepareStatement(selectQuery)) { + selectStmt.setString(1, uuid.toString()); + try (ResultSet rs = selectStmt.executeQuery()) { if (rs.next()) return true; } - } catch (SQLException ex) {Utils.logSqlException(ex);} - // add builder to database - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO builder (uuid, name) " + - "VALUES (?, ?);")) { - stmt.setString(1, uuid.toString()); - stmt.setString(2, name); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) { + insertStmt.setString(1, uuid.toString()); + insertStmt.setString(2, name); + return insertStmt.executeUpdate() > 0; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setName(UUID uuid, String name) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder SET name = ? WHERE uuid = ?;")) { + String query = "UPDATE builder SET name = ? WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, name); stmt.setString(2, uuid.toString()); stmt.executeUpdate(); if (builders.containsKey(uuid)) builders.get(uuid).setName(name); return true; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean addScore(UUID uuid, int score) { - try { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;")) { - stmt.setInt(1, score); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - return true; - } - } catch (SQLException ex) {Utils.logSqlException(ex);} + String query = "UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, score); + stmt.setString(2, uuid.toString()); + stmt.executeUpdate(); + return true; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setSlot(UUID uuid, int plotID, Slot slot) { - try { - if (plotID > 0) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = ? " + - "WHERE uuid = ?;")) { - stmt.setInt(1, plotID); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - } - } else { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET " + slot.name().toLowerCase() + " = " + - "DEFAULT(first_slot) WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); - stmt.executeUpdate(); - } - } + String query = "UPDATE builder b SET " + slot.name().toLowerCase() + " = " + + (plotID > 0 ? "?" : "DEFAULT(first_slot)") + " WHERE uuid = ?;"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + if (plotID > 0) stmt.setInt(1, plotID); + stmt.setString(plotID > 0 ? 2 : 1, uuid.toString()); + stmt.executeUpdate(); return true; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setPlotType(UUID uuid, int plotTypeId) { - try { - if (plotTypeId > 0) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET plot_type = ? WHERE uuid = ?;")) { - stmt.setInt(1, plotTypeId); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - } - } else { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE builder b SET plot_type = DEFAULT(plot_type) WHERE uuid = ?;")) { - stmt.setString(1, uuid.toString()); - stmt.executeUpdate(); - } - } + String query = "UPDATE builder b SET plot_type = " + + (plotTypeId > 0 ? "?" : "DEFAULT(plot_type)") + " WHERE uuid = ?;"; + + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + if (plotTypeId > 0) stmt.setInt(1, plotTypeId); + stmt.setString(plotTypeId > 0 ? 2 : 1, uuid.toString()); + stmt.executeUpdate(); return true; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public int getCompletedBuildsCount(UUID uuid) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT COUNT(*) AS completed_plots FROM plot p INNER JOIN builder_has_plot " + - "bhp ON p.plot_id = bhp.plot_id WHERE p.status = 'completed' AND bhp.uuid = ?;")) { + String query = "SELECT COUNT(*) AS completed_plots FROM plot p INNER JOIN builder_is_plot_member " + + "bipm ON p.plot_id = bipm.plot_id WHERE p.status = 'completed' AND bhp.uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) return rs.getInt(1); } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return 0; } public Slot getFreeSlot(UUID uuid) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;")) { + String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { @@ -186,15 +191,20 @@ public Slot getFreeSlot(UUID uuid) { if (rs.getString(i) == null) return Slot.values()[i - 1]; } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean canReviewPlot(Builder builder, Plot plot) { // TODO: cache - try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;")) { + String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, builder.getUUID().toString()); + try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Optional team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); @@ -203,33 +213,44 @@ public boolean canReviewPlot(Builder builder, Plot plot) { return true; } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean isAnyReviewer(UUID uuid) { // TODO: cache - try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("SELECT uuid FROM build_team_has_reviewer WHERE uuid = ?;")) { + String query = "SELECT uuid FROM build_team_has_reviewer WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, uuid.toString()); + try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) return true; } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public List getReviewersByBuildTeam(int buildTeamId) { List builders = new ArrayList<>(); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT uuid FROM build_team_has_reviewer WHERE build_team_id = ?;")) { + String query = "SELECT uuid FROM build_team_has_reviewer WHERE build_team_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { stmt.setInt(1, buildTeamId); + while (rs.next()) { Builder builder = getBuilderByUUID(UUID.fromString(rs.getString(1))); if (builder != null) builders.add(builder); } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return builders; } @@ -242,16 +263,17 @@ public List getReviewersByBuildTeam(int buildTeamId) { * @return provides the leaderboard entry for the player, or null if not found. */ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimeframe sortBy) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement(getLeaderboardQuery(uuid, sortBy))) { + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(uuid, sortBy))) { try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return new LeaderboardEntry(rs.getInt(2), rs.getInt(3), rs.getInt(4)); } } - - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } @@ -262,16 +284,17 @@ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimefram * @return provides a map of player names and their scores, or null if no data is found. */ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement(getLeaderboardQuery(null, sortBy))) { + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(null, sortBy))) { try (ResultSet rs = stmt.executeQuery()) { Map playerEntries = new HashMap<>(); while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); return playerEntries; } - - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 3c35f365..26530fae 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -39,18 +40,18 @@ public class CityProjectProvider { public static final List cachedCityProjects = new ArrayList<>(); public CityProjectProvider() { - // cache all city projects - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT city_project_id, country_code, server_name, is_visible FROM city_project;")) { + String query = "SELECT city_project_id, country_code, server_name, is_visible FROM city_project;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) cachedCityProjects.add(new CityProject( - rs.getString(1), - rs.getString(2), - rs.getString(3), - rs.getBoolean(4) - )); + while (rs.next()) { + cachedCityProjects.add(new CityProject(rs.getString(1), // cache all city projects + rs.getString(2), rs.getString(3), rs.getBoolean(4))); + } } - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } } public Optional getById(String id) { @@ -58,38 +59,49 @@ public Optional getById(String id) { } public List getByCountryCode(String countryCode, boolean onlyVisible) { - return cachedCityProjects.stream().filter(c -> (!onlyVisible || c.isVisible()) && c.getCountry().getCode().equals(countryCode)).toList(); + return cachedCityProjects.stream().filter(c -> (!onlyVisible || c.isVisible()) && + c.getCountry().getCode().equals(countryCode)).toList(); } public List get(boolean onlyVisible) { return cachedCityProjects.stream().filter(c -> !onlyVisible || c.isVisible()).toList(); } - public List getCityProjectsByBuildTeam(int id) { + public List getCityProjectsByBuildTeam(int buildTeamId) { List cityProjects = new ArrayList<>(); - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT city_project_id FROM build_team_has_city_project WHERE build_team_id = ?;")) { + + String query = "SELECT city_project_id FROM city_project WHERE build_team_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, buildTeamId); + try (ResultSet rs = stmt.executeQuery()) { - stmt.setInt(1, id); while (rs.next()) { Optional city = getById(rs.getString(1)); city.ifPresent(cityProjects::add); } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return cityProjects; } - public boolean add(String id, String countryCode, String serverName) { + public boolean add(String id, int buildTeamId, String countryCode, String serverName) { if (getById(id).isPresent()) return true; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO city_project (city_project_id, country_code, server_name) " + - "VALUES (?, ?, ?);")) { + + String query = "INSERT INTO city_project (city_project_id, build_team_id, country_code, server_name) " + + "VALUES (?, ?, ?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, id); - stmt.setString(2, countryCode); - stmt.setString(3, serverName); + stmt.setInt(2, buildTeamId); + stmt.setString(3, countryCode); + stmt.setString(4, serverName); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } @@ -97,33 +109,42 @@ public boolean remove(String id) { Optional cityProject = getById(id); if (cityProject.isEmpty()) return false; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM city_project WHERE city_project_id = ?;")) { + String query = "DELETE FROM city_project WHERE city_project_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, id); boolean result = stmt.executeUpdate() > 0; if (result) cachedCityProjects.remove(cityProject.get()); return result; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setVisibility(String id, boolean isVisible) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE city_project SET is_visible = ? WHERE city_project_id = ?;")) { + String query = "UPDATE city_project SET is_visible = ? WHERE city_project_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setBoolean(1, isVisible); stmt.setString(2, id); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setServer(String id, String serverName) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE city_project SET server_name = ? WHERE city_project_id = ?;")) { + String query = "UPDATE city_project SET server_name = ? WHERE city_project_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, serverName); stmt.setString(2, id); return stmt.executeUpdate() > 0; - } catch (SQLException ex) { Utils.logSqlException(ex); } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index c1acf7c3..165ce50a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.database.DatabaseConnection; @@ -6,6 +30,7 @@ import com.alpsbte.plotsystem.utils.enums.Continent; import org.jetbrains.annotations.Nullable; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -17,17 +42,20 @@ public class CountryProvider { private static final List cachedCountries = new ArrayList<>(); public CountryProvider() { - // cache all countries - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT country_code, continent, material, custom_model_data FROM country;")) { + String query = "SELECT country_code, continent, material, custom_model_data FROM country;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { Continent continent = Continent.fromDatabase(rs.getString(2)); - Country country = new Country(rs.getString(1), continent, rs.getString(3), rs.getString(4)); - cachedCountries.add(country); + Country country = new Country(rs.getString(1), continent, rs.getString(3), + rs.getString(4)); + cachedCountries.add(country); // cache all countries } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } } public List getCountries() { @@ -43,21 +71,25 @@ public Optional getCountryByCode(String code) { } public boolean setMaterialAndCustomModelData(String code, String material, @Nullable String customModelData) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;")) { + String query = "UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, material); stmt.setString(2, customModelData); stmt.setString(3, code); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean addCountry(String code, Continent continent, String material, @Nullable String customModelData) { if (getCountryByCode(code).isPresent()) return true; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO country (country_code, continent, material, custom_model_data) " + - "VALUES (?, ?, ?, ?);")) { + + String query = "INSERT INTO country (country_code, continent, material, custom_model_data) VALUES (?, ?, ?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, code); stmt.setString(2, continent.databaseEnum); stmt.setString(3, material); @@ -65,7 +97,9 @@ public boolean addCountry(String code, Continent continent, String material, @Nu boolean result = stmt.executeUpdate() > 0; if (result) cachedCountries.add(new Country(code, continent, material, customModelData)); return result; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } @@ -73,13 +107,16 @@ public boolean removeCountry(String code) { Optional cachedCountry = getCountryByCode(code); if (cachedCountry.isEmpty()) return false; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM country WHERE country_code = ?;")) { + String query = "DELETE FROM country WHERE country_code = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, code); boolean result = stmt.executeUpdate() > 0; if (result) cachedCountries.remove(cachedCountry.get()); return result; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index aeacaca2..bc6d6211 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.PlotSystem; @@ -7,6 +31,7 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -21,8 +46,9 @@ public class DifficultyProvider { public DifficultyProvider() { // cache all difficulties - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT difficulty_id, multiplier, score_requirement FROM difficulty;")) { + String query = "SELECT difficulty_id, multiplier, score_requirement FROM plot_difficulty;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String id = rs.getString(1); @@ -34,7 +60,9 @@ public DifficultyProvider() { cachedDifficulties.add(difficulty); } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } } public List getDifficulties() { @@ -50,29 +78,36 @@ public Optional getDifficultyByEnum(PlotDifficulty difficulty) { } public boolean setMultiplier(String id, double multiplier) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE difficulty SET multiplier = ? WHERE difficulty_id = ?;")) { + String query = "UPDATE plot_difficulty SET multiplier = ? WHERE difficulty_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setDouble(1, multiplier); stmt.setString(2, id); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setScoreRequirement(String id, int scoreRequirement) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE difficulty SET score_requirement = ? WHERE difficulty_id = ?;")) { + String query = "UPDATE plot_difficulty SET score_requirement = ? WHERE difficulty_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, scoreRequirement); stmt.setString(2, id); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean builderMeetsRequirements(Builder builder, PlotDifficulty plotDifficulty) { Optional cachedDifficulty = getDifficultyByEnum(plotDifficulty); if (cachedDifficulty.isEmpty()) { - PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " + plotDifficulty.name() + " was found!")); + PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " + + plotDifficulty.name() + " was found!")); return false; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index df748b11..998c3077 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -23,7 +47,8 @@ public class PlotProvider { public Plot getPlotById(int plotId) { String query = "SELECT city_project_id, difficulty_id, owner_uuid, status, score, " + "outline_bounds, last_activity_date, plot_version, plot_type FROM plot WHERE plot_id = ?;"; - try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(query)) { + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) return null; @@ -40,16 +65,16 @@ public Plot getPlotById(int plotId) { return new Plot(plotId, cityProject, difficulty, ownerUUID, status, score, outlineBounds, lastActivity, version, type, getPlotMembers(plotId)); } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } public List getPlots(Status status) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE status = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, status.name()); try (ResultSet rs = stmt.executeQuery()) { @@ -68,10 +93,8 @@ public List getPlots(Status status) { public List getPlots(CityProject city, Status... statuses) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ?"; query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; - try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, city.getID()); for (int i = 0; i < statuses.length; i++) stmt.setString(i + 2, statuses[i].name()); @@ -89,7 +112,6 @@ public List getPlots(CityProject city, Status... statuses) { public List getPlots(CityProject city, PlotDifficulty plotDifficulty, Status status) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ? AND difficulty_id = ? " + "AND status = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -114,10 +136,8 @@ public List getPlots(List cities, Status... statuses) { String cityPlaceholders = "?,".repeat(cities.size() - 1) + "?"; String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id IN (" + cityPlaceholders + ")"; query += statuses.length > 0 ? " AND status IN (?,".repeat(statuses.length - 1) + "?);" : ";"; - try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - int index = 1; for (CityProject city : cities) stmt.setString(index++, city.getID()); for (Status status : statuses) stmt.setString(index++, status.name()); @@ -137,10 +157,8 @@ public List getPlots(Builder builder, Status... statuses) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot LEFT JOIN builder_is_plot_member pm ON " + "plot.plot_id = pm.plot_id WHERE (plot.owner_uuid = ? OR pm.uuid = ?)"; query += statuses.length > 0 ? "AND plot.status IN (?,".repeat(statuses.length - 1) + "?);" : ";"; - try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - String builderUUID = builder.getUUID().toString(); stmt.setString(1, builderUUID); stmt.setString(2, builderUUID); @@ -173,8 +191,21 @@ private Plot extractPlot(ResultSet rs) throws SQLException { } public List getPlotMembers(int plotId) { - // TODO: implement - return null; + String query = "SELECT uuid FROM builder_is_plot_member WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, plotId); + + List members = new ArrayList<>(); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) + members.add(Builder.byUUID(UUID.fromString(rs.getString(1)))); + } + return members; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return new ArrayList<>(); } public Review getReview(int plotId) { @@ -183,28 +214,26 @@ public Review getReview(int plotId) { } public byte[] getInitialSchematic(int plotId) { - String query = "SELECT initial_schematic FROM plot WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return null; - return rs.getBytes(1); - } - } catch (SQLException ex) {Utils.logSqlException(ex);} - return null; + return getSchematic(plotId, "initial_schematic"); } public byte[] getCompletedSchematic(int plotId) { - String query = "SELECT complete_schematic FROM plot WHERE plot_id = ?;"; + return getSchematic(plotId, "complete_schematic"); + } + + private byte[] getSchematic(int plotId, String name) { + String query = "SELECT ? FROM plot WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); + stmt.setString(1, name); + stmt.setInt(2, plotId); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) return null; return rs.getBytes(1); } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } @@ -215,15 +244,17 @@ public boolean setCompletedSchematic(int plotId, byte[] completedSchematic) { stmt.setBytes(1, completedSchematic); stmt.setInt(2, plotId); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setPlotOwner(int plotId, UUID ownerUUID) { - String query = "UPDATE plot SET owner_uuid = ? WHERE plot_id = ?;"; - String query2 = "UPDATE plot SET owner_uuid = DEFAULT(owner_uuid) WHERE plot_id = ?;"; + String updateQuery = "UPDATE plot SET owner_uuid = ? WHERE plot_id = ?;"; + String defaultUpdateQuery = "UPDATE plot SET owner_uuid = DEFAULT(owner_uuid) WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(ownerUUID == null ? query2 : query)) { + PreparedStatement stmt = conn.prepareStatement(ownerUUID == null ? defaultUpdateQuery : updateQuery)) { if (ownerUUID == null) { stmt.setInt(1, plotId); } else { @@ -231,42 +262,83 @@ public boolean setPlotOwner(int plotId, UUID ownerUUID) { stmt.setInt(2, plotId); } return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setLastActivity(int plotId, LocalDate activityDate) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE plot SET last_activity_date = ? WHERE plot_id = ?;")) { + String query = "UPDATE plot SET last_activity_date = ? WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setDate(1, activityDate == null ? null : Date.valueOf(activityDate)); stmt.setInt(2, plotId); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setStatus(int plotId, Status status) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE plot SET status = ? WHERE plot_id = ?;")) { + String query = "UPDATE plot SET status = ? WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, status.name()); stmt.setInt(2, plotId); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setPlotMembers(int plotId, List members) { - // TODO: implement + String deleteQuery = "DELETE FROM builder_is_plot_member WHERE plot_id = ?;"; + String insertQuery = "INSERT INTO builder_is_plot_member (plot_id, uuid) VALUES (?, ?);"; + + try (Connection conn = DatabaseConnection.getConnection()) { + conn.setAutoCommit(false); + try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery); + PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) { + + // Delete existing members + deleteStmt.setInt(1, plotId); + deleteStmt.executeUpdate(); + + // Insert new members if list is not empty + if (!members.isEmpty()) { + for (Builder member : members) { + insertStmt.setInt(1, plotId); + insertStmt.setString(2, member.getUUID().toString()); + insertStmt.addBatch(); + } + insertStmt.executeBatch(); + } + + conn.commit(); // Commit transaction + return true; + } catch (SQLException ex) { + conn.rollback(); // Rollback if anything fails + Utils.logSqlException(ex); + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setPlotType(int plotId, PlotType type) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE plot SET plot_type = ? WHERE plot_id = ?;")) { + String query = "UPDATE plot SET plot_type = ? WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, type.getId()); stmt.setInt(2, plotId); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } @@ -274,19 +346,24 @@ public boolean setPasted(int plotId, boolean pasted) { String query = "UPDATE plot SET is_pasted = ? WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setBoolean(1, pasted); stmt.setInt(2, plotId); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean deletePlot(int plotId) { - try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement("DELETE FROM plot WHERE plot_id = ?;")) { + String query = "DELETE FROM plot WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java index 4c644b81..bdc3b7d4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java @@ -1,8 +1,33 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.utils.Utils; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -13,13 +38,15 @@ public class ServerProvider { private static final List cachedServers = new ArrayList<>(); public ServerProvider() { - // cache all servers - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT server_name FROM server;")) { + String query = "SELECT server_name FROM server;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) cachedServers.add(rs.getString(1)); + while (rs.next()) cachedServers.add(rs.getString(1)); // cache all servers } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } } public boolean serverExists(String serverName) { @@ -32,27 +59,34 @@ public List getServers() { public boolean addServer(String name, int buildTeamId) { if (serverExists(name)) return true; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO server (server_name, build_team_id) " + - "VALUES (?, ?);")) { + + String query = "INSERT INTO server (server_name, build_team_id) VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, name); stmt.setInt(2, buildTeamId); boolean result = stmt.executeUpdate() > 0; if (result) cachedServers.add(name); return result; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean removeServer(String name) { if (!serverExists(name)) return false; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("DELETE FROM server WHERE server_name = ?;")) { + + String query = "DELETE FROM server WHERE server_name = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, name); boolean result = stmt.executeUpdate() > 0; if (result) cachedServers.remove(name); return result; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index c9626665..0a752b5b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.utils.Utils; +import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -47,9 +48,10 @@ public Optional getByTutorialId(int tutorialId, String playerUUID) .filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString().equals(playerUUID)).findFirst(); if (tutorialPlot.isEmpty()) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("SELECT stage_id, is_complete, last_stage_complete_date FROM " + - "tutorial WHERE tutorial_id = ? AND uuid = ?;")) { + String query = "SELECT stage_id, is_complete, last_stage_complete_date FROM " + + "tutorial WHERE tutorial_id = ? AND uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, tutorialId); stmt.setString(2, playerUUID); @@ -63,45 +65,55 @@ public Optional getByTutorialId(int tutorialId, String playerUUID) return Optional.of(newTutorialPlot); } } - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } } return tutorialPlot; } public boolean add(int tutorialId, String playerUUID) { if (getByTutorialId(tutorialId, playerUUID).isPresent()) return false; - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);")) { + + String query = "INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, tutorialId); stmt.setString(2, playerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setStageId(int tutorialId, String playerUUID, int stageId) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE tutorial SET stage_id = ?, last_stage_complete_date = ? WHERE " + - "tutorial_id = ? AND uuid = ?;")) { + String query = "UPDATE tutorial SET stage_id = ?, last_stage_complete_date = ? WHERE tutorial_id = ? AND uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, stageId); stmt.setObject(2, LocalDate.now()); stmt.setInt(3, tutorialId); stmt.setString(4, playerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } public boolean setComplete(int tutorialId, String playerUUID) { - try (PreparedStatement stmt = DatabaseConnection.getConnection() - .prepareStatement("UPDATE tutorial SET is_complete = ?, last_stage_complete_date = ? WHERE " + - "tutorial_id = ? AND uuid = ?;")) { + String query = "UPDATE tutorial SET is_complete = ?, last_stage_complete_date = ? WHERE tutorial_id = ? AND uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setBoolean(1, true); stmt.setObject(2, LocalDate.now()); stmt.setInt(3, tutorialId); stmt.setString(4, playerUUID); return stmt.executeUpdate() > 0; - } catch (SQLException ex) {Utils.logSqlException(ex);} + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 333a32aa..3c4c444a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -67,20 +67,22 @@ public boolean setName(String newName) { } public boolean addCityProject(CityProject city) { - if (DataProvider.BUILD_TEAM.addCityProject(ID, city.getID())) { + /*if (DataProvider.CITY_PROJECT.addCityProject(ID, city.getID())) { this.cityProjects.add(city); return true; - } + }*/ + // TODO: Implement return false; } public boolean removeCityProject(String cityId) { Optional removeCity = cityProjects.stream().filter(c -> c.getID().equalsIgnoreCase(cityId)).findFirst(); if (removeCity.isEmpty()) return false; - if (DataProvider.BUILD_TEAM.removeCityProject(ID, cityId)) { + /*if (DataProvider.BUILD_TEAM.removeCityProject(ID, cityId)) { this.cityProjects.remove(removeCity.get()); return true; - } + }*/ + // TODO: Implement return false; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 13309731..0b02a211 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -215,22 +215,7 @@ public BlockVector3 getCenter() { } public Slot getSlot() { - String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?"; - try (PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(query)) { - - stmt.setString(1, this.getPlotOwner().getUUID().toString()); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - for (int i = 1; i <= 3; i++) { - int slot = rs.getInt(i); - if (!rs.wasNull() && slot == getID()) { - return Slot.values()[i - 1]; - } - } - } - } - } + // TODO: Implement return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index a2aff1cc..fec20940 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -39,6 +39,7 @@ import org.apache.commons.io.FileUtils; import org.bukkit.configuration.file.FileConfiguration; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; @@ -118,6 +119,12 @@ public Builder getPlotOwner() { return Builder.byUUID(uuid); } + @Override + public boolean setPlotOwner(@Nullable Builder plotOwner) { + // TODO: Implement + return false; + } + @Override @SuppressWarnings("unchecked") public T getWorld() { From ad4b4f6f9455235df90aae75af45d9373f807846 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 3 Apr 2025 23:26:34 +0200 Subject: [PATCH 052/175] start review implementation, fix compile issues and update database --- .../commands/review/CMD_EditFeedback.java | 17 +- .../commands/review/CMD_EditPlot.java | 2 +- .../commands/review/CMD_Review.java | 4 +- .../commands/review/CMD_UndoReview.java | 2 +- .../plotsystem/core/EventListener.java | 7 +- .../database/providers/BuilderProvider.java | 10 +- .../providers/CityProjectProvider.java | 4 +- .../core/database/providers/PlotProvider.java | 18 +- .../database/providers/ReviewProvider.java | 38 ++ .../plotsystem/core/menus/FeedbackMenu.java | 91 ++- .../plotsystem/core/menus/ReviewPlotMenu.java | 539 ------------------ .../core/menus/review/ReviewItems.java | 62 ++ .../core/menus/review/ReviewPlotMenu.java | 328 +++++++++++ .../menus/review/ReviewPlotTogglesMenu.java | 201 +++++++ .../plotsystem/core/system/Builder.java | 4 + .../plotsystem/core/system/CityProject.java | 8 +- .../plotsystem/core/system/Review.java | 4 - .../plotsystem/core/system/plot/Plot.java | 26 +- .../core/system/plot/utils/PlotUtils.java | 2 +- .../core/system/review/PlotReview.java | 68 +++ .../core/system/review/ReviewRating.java | 40 ++ .../core/system/review/ToggleCriteria.java | 19 + .../utils/chat/PlayerFeedbackChatInput.java | 8 +- 23 files changed, 857 insertions(+), 645 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index 5066d524..396156e4 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -39,7 +40,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.text; @@ -74,7 +75,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_SEND_FEEDBACK))); return; } @@ -83,14 +84,16 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N for (int i = 2; i <= args.length; i++) { feedback.append(args.length == 2 ? "" : " ").append(args[i - 1]); } - try { - plot.getReview().setFeedback(feedback.toString()); - } catch (SQLException e) { + Optional review = plot.getLatestReview(); + if (review.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), e); + PlotSystem.getPlugin().getComponentLogger().error("Could not retrieve latest review!"); + return; } - sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, plot.getID() + ""))); + boolean successful = review.get().updateFeedback(feedback.toString()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, plot.getID() + ""))); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 0f6c8346..8b3762b5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -97,7 +97,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Builder builder = Builder.byUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index e9d38f15..2b1b2051 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -29,7 +29,7 @@ import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.ReviewMenu; -import com.alpsbte.plotsystem.core.menus.ReviewPlotMenu; +import com.alpsbte.plotsystem.core.menus.review.ReviewPlotMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -83,7 +83,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index dc894151..60d2152d 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -75,7 +75,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder, plot) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index fa0f323f..d636cdaf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -30,7 +30,6 @@ import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; @@ -199,7 +198,7 @@ public void onPlayerSwapHandItemsEvent(@NotNull PlayerSwapHandItemsEvent event) } @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerChatEvent(@NotNull AsyncChatEvent event) throws SQLException { + public void onPlayerChatEvent(@NotNull AsyncChatEvent event) { UUID playerUUID = event.getPlayer().getUniqueId(); if (ChatInput.awaitChatInput.containsKey(playerUUID)) { event.setCancelled(true); @@ -207,10 +206,10 @@ public void onPlayerChatEvent(@NotNull AsyncChatEvent event) throws SQLException ChatInput input = ChatInput.awaitChatInput.get(playerUUID); if (input instanceof PlayerFeedbackChatInput feedbackInput) { - feedbackInput.getReview().setFeedback(messageComp.content()); + feedbackInput.getReview().updateFeedback(messageComp.content()); ChatInput.awaitChatInput.remove(playerUUID); event.getPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(event.getPlayer(), - LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, String.valueOf(feedbackInput.getReview().getPlotID())))); + LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, String.valueOf(feedbackInput.getReview().getPlotId())))); } else if (input instanceof PlayerInviteeChatInput inviteeInput) { Player player = Bukkit.getPlayer(messageComp.content()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 60cfb29c..ef27679d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -197,13 +197,19 @@ public Slot getFreeSlot(UUID uuid) { return null; } + public Slot getSlot(UUID uuid, int plotId) { + // TODO: implement + // get the slot in which the given plot is allocated + return null; + } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean canReviewPlot(Builder builder, Plot plot) { + public boolean canReviewPlot(UUID uuid, Plot plot) { // TODO: cache String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, builder.getUUID().toString()); + stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 26530fae..85e2414d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -40,13 +40,13 @@ public class CityProjectProvider { public static final List cachedCityProjects = new ArrayList<>(); public CityProjectProvider() { - String query = "SELECT city_project_id, country_code, server_name, is_visible FROM city_project;"; + String query = "SELECT city_project_id, country_code, server_name, is_visible, build_team_id FROM city_project;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { cachedCityProjects.add(new CityProject(rs.getString(1), // cache all city projects - rs.getString(2), rs.getString(3), rs.getBoolean(4))); + rs.getString(2), rs.getString(3), rs.getBoolean(4), rs.getInt(5))); } } } catch (SQLException ex) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 998c3077..1892d299 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -41,11 +41,11 @@ public class PlotProvider { private static final String PLOT_SQL_COLUMNS = "plot.plot_id, plot.city_project_id, plot.difficulty_id, " + - "plot.owner_uuid, plot.status, plot.score, plot.outline_bounds, plot.last_activity_date, " + + "plot.owner_uuid, plot.status, plot.outline_bounds, plot.last_activity_date, " + "plot.plot_version, plot.plot_type"; public Plot getPlotById(int plotId) { - String query = "SELECT city_project_id, difficulty_id, owner_uuid, status, score, " + + String query = "SELECT city_project_id, difficulty_id, owner_uuid, status, " + "outline_bounds, last_activity_date, plot_version, plot_type FROM plot WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -56,13 +56,12 @@ public Plot getPlotById(int plotId) { PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString(2)).orElseThrow().getDifficulty(); UUID ownerUUID = UUID.fromString(rs.getString(3)); Status status = Status.valueOf(rs.getString(4)); - int score = rs.getInt(5); - String outlineBounds = rs.getString(6); - LocalDate lastActivity = rs.getDate(7).toLocalDate(); - double version = rs.getDouble(8); - PlotType type = PlotType.byId(rs.getInt(9)); + String outlineBounds = rs.getString(5); + LocalDate lastActivity = rs.getDate(6).toLocalDate(); + double version = rs.getDouble(7); + PlotType type = PlotType.byId(rs.getInt(8)); - return new Plot(plotId, cityProject, difficulty, ownerUUID, status, score, outlineBounds, + return new Plot(plotId, cityProject, difficulty, ownerUUID, status, outlineBounds, lastActivity, version, type, getPlotMembers(plotId)); } } catch (SQLException ex) { @@ -181,13 +180,12 @@ private Plot extractPlot(ResultSet rs) throws SQLException { PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString("difficulty_id")).orElseThrow().getDifficulty(); UUID ownerUUID = UUID.fromString(rs.getString("owner_uuid")); Status status = Status.valueOf(rs.getString("status")); - int score = rs.getInt("score"); String outlineBounds = rs.getString("outline_bounds"); LocalDate lastActivity = rs.getDate("last_activity_date").toLocalDate(); double version = rs.getDouble("plot_version"); PlotType type = PlotType.byId(rs.getInt("plot_type")); - return new Plot(plotId, cityProject, difficulty, ownerUUID, status, score, outlineBounds, lastActivity, version, type, getPlotMembers(plotId)); + return new Plot(plotId, cityProject, difficulty, ownerUUID, status, outlineBounds, lastActivity, version, type, getPlotMembers(plotId)); } public List getPlotMembers(int plotId) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index c5df1892..dc2d7eff 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,6 +1,44 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.system.review.PlotReview; +import com.alpsbte.plotsystem.core.system.review.ReviewRating; +import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + public class ReviewProvider { + public Optional getReview(int reviewId) { + // TODO: implement + return null; + } + + public Optional getLatestReview(int plotId) { + return null; + } + + public List getPlotReviewHistory(int plotId) { + // TODO: implement + return List.of(); + } + + public boolean updateFeedback(int reviewId, String newFeedback) { + // TODO: implement + return false; + } + + public List getBuildTeamToggleCriteria(int buildTeamId) { + // TODO: implement + return List.of(); + } + + public boolean createReview(ReviewRating rating, int score, UUID reviewerUUID, boolean isRejected) { + // TODO: implement + // also create feedback notification + return false; + } + public boolean undoReview() { return false; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 47df0c8a..45c337c4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -30,10 +30,9 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Category; import com.alpsbte.plotsystem.utils.items.MenuItems; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -52,7 +51,7 @@ public class FeedbackMenu extends AbstractMenu { - private Review review = null; + private PlotReview review = null; private final Plot plot; public FeedbackMenu(Player player, int plotID) { @@ -72,69 +71,49 @@ protected void setMenuItemsAsync() { try (ResultSet rs = DatabaseConnection.createStatement("SELECT review_id FROM plotsystem_plots WHERE id = ?") .setValue(plot.getID()).executeQuery()) { - if (rs.next()) this.review = new Review(rs.getInt(1)); + if (rs.next()) { + DataProvider.REVIEW.getReview(rs.getInt(1)).ifPresent(value -> this.review = value); + } DatabaseConnection.closeResultSet(rs); } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } // Set score item - try { - getMenu().getSlot(10).setItem(new ItemBuilder(Material.NETHER_STAR) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE), AQUA, BOLD)) - .setLore(new LoreBuilder() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY).append(text(plot.getTotalScore(), WHITE))) - .emptyLine() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating(Category.ACCURACY)) - .append(text("/", DARK_GRAY)) - .append(text("5", GREEN)))) - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating(Category.BLOCKPALETTE))) - .append(text("/", DARK_GRAY)) - .append(text("5", GREEN))) - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.DETAILING) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating(Category.DETAILING))) - .append(text("/", DARK_GRAY)) - .append(text("5", GREEN))) - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.TECHNIQUE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating(Category.TECHNIQUE))) - .append(text("/", DARK_GRAY)) - .append(text("5", GREEN))) - .emptyLine() - .addLine(plot.isRejected() - ? text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REJECTED), RED, BOLD) - : text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ACCEPTED), GREEN, BOLD)) - .build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(10).setItem(MenuItems.errorItem(getMenuPlayer())); - } + getMenu().getSlot(10).setItem(new ItemBuilder(Material.NETHER_STAR) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE), AQUA, BOLD)) + .setLore(new LoreBuilder() + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY).append(text(plot.getTotalScore(), WHITE))) + .emptyLine() + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) + .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getAccuracyPoints()) + .append(text("/", DARK_GRAY)) + .append(text("5", GREEN)))) + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE) + ": ", GRAY) + .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getBlockPalettePoints())) + .append(text("/", DARK_GRAY)) + .append(text("5", GREEN))) + .emptyLine() + .addLine(plot.isRejected() + ? text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REJECTED), RED, BOLD) + : text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ACCEPTED), GREEN, BOLD)) + .build()) + .build()); // Set feedback text item - try { - getMenu().getSlot(13).setItem(new ItemBuilder(Material.WRITABLE_BOOK) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA, BOLD)) - .setLore(new LoreBuilder() - .addLine(plot.getReview().getFeedback().replaceAll("//", " "), true) - .build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(13).setItem(MenuItems.errorItem(getMenuPlayer())); - } + String feedbackText = review.getFeedback() == null ? "No Feedback" : review.getFeedback(); // TODO: translate no feedback text + getMenu().getSlot(13).setItem(new ItemBuilder(Material.WRITABLE_BOOK) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA, BOLD)) + .setLore(new LoreBuilder() + .addLine(feedbackText.replaceAll("//", " "), true) + .build()) + .build()); // Set reviewer item - try { - getMenu().getSlot(16).setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(review.getReviewer().getUUID())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REVIEWER), AQUA, BOLD)) - .setLore(new LoreBuilder().addLine(review.getReviewer().getName()).build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(13).setItem(MenuItems.errorItem(getMenuPlayer())); - } + getMenu().getSlot(16).setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(review.getReviewerUUID())) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REVIEWER), AQUA, BOLD)) + .setLore(new LoreBuilder().addLine(review.getReviewer().getName()).build()) + .build()); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java deleted file mode 100644 index 4eb5a2b7..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java +++ /dev/null @@ -1,539 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.menus; - -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; -import com.alpsbte.alpslib.utils.item.ItemBuilder; -import com.alpsbte.alpslib.utils.item.LoreBuilder; -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; -import com.alpsbte.plotsystem.utils.chat.ChatInput; -import com.alpsbte.plotsystem.utils.chat.PlayerFeedbackChatInput; -import com.alpsbte.plotsystem.utils.io.LangPaths; -import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.BaseItems; -import com.alpsbte.plotsystem.utils.items.CustomHeads; -import com.sk89q.worldedit.WorldEditException; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Review; -import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.utils.items.MenuItems; -import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Status; -import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.ipvp.canvas.mask.BinaryMask; -import org.ipvp.canvas.mask.Mask; - -import java.io.IOException; -import java.sql.SQLException; -import java.util.Collections; -import java.util.Objects; - -import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; -import static net.kyori.adventure.text.format.TextDecoration.BOLD; - -public class ReviewPlotMenu extends AbstractMenu { - private final Plot plot; - - boolean sentWarning = false; - - public ReviewPlotMenu(Player player, Plot plot) { - super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); - this.plot = plot; - } - - @Override - protected void setPreviewItems() { - final ItemStack[] itemPointZero = new ItemStack[4]; - final ItemStack[] itemPointOne = new ItemStack[4]; - final ItemStack[] itemPointTwo = new ItemStack[4]; - final ItemStack[] itemPointThree = new ItemStack[4]; - final ItemStack[] itemPointFour = new ItemStack[4]; - final ItemStack[] itemPointFive = new ItemStack[4]; - - for (int i = 0; i < 54; i++) { - int column = (i % 9) + 1; - int row = (i - (i % 9)) / 9 + 1; - int position = ((i + 1) - (i + 1) % 9) / 54; - if (column > 2 && column < 9 && row > 1 && row < 6) { - if ((i + 1) % 9 == 3) { - itemPointZero[position] = getZeroPointItem(); - - //Add Enchantment - ItemMeta itemMeta = itemPointZero[position].getItemMeta(); - Objects.requireNonNull(itemMeta).addEnchant(Enchantment.POWER, 1, true); - itemPointZero[position].setItemMeta(itemMeta); - getMenu().getSlot(i).setItem(itemPointZero[(i - (i + 1) % 9) / 54]); - } else if ((i + 1) % 9 == 4) { - itemPointOne[position] = getOnePointItem(); - getMenu().getSlot(i).setItem(itemPointOne[(i - (i + 1) % 9) / 54]); - } else if ((i + 1) % 9 == 5) { - itemPointTwo[position] = getTwoPointItem(); - getMenu().getSlot(i).setItem(itemPointTwo[(i - (i + 1) % 9) / 54]); - } else if ((i + 1) % 9 == 6) { - itemPointThree[position] = getThreePointItem(); - getMenu().getSlot(i).setItem(itemPointThree[(i - (i + 1) % 9) / 54]); - } else if ((i + 1) % 9 == 7) { - itemPointFour[position] = getFourPointItem(); - getMenu().getSlot(i).setItem(itemPointFour[(i - (i + 1) % 9) / 54]); - } else if ((i + 1) % 9 == 8) { - itemPointFive[position] = getFivePointItem(); - getMenu().getSlot(i).setItem(itemPointFive[(i - (i + 1) % 9) / 54]); - } - } - } - - getMenu().getSlot(4).setItem(MenuItems.loadingItem(Material.MAP, getMenuPlayer())); - - getMenu().getSlot(10).setItem(getAccuracyItem()); - getMenu().getSlot(19).setItem(getBlockPaletteItem()); - getMenu().getSlot(28).setItem(getDetailingItem()); - getMenu().getSlot(37).setItem(getTechniqueItem()); - - getMenu().getSlot(48).setItem(getSubmitItem()); - getMenu().getSlot(50).setItem(getCancelItem()); - - super.setPreviewItems(); - } - - @Override - protected void setMenuItemsAsync() { - // Set back item - getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); - - // Set plot information item - getMenu().getSlot(4).setItem(getPlotInfoItem()); - - // Set review information item - getMenu().getSlot(7).setItem(getReviewInfoItem()); - } - - @Override - protected void setItemClickEventsAsync() { - // Set click event for back item - getMenu().getSlot(1).setClickHandler((clickPlayer, clickInformation) - -> new ReviewMenu(getMenuPlayer())); - - // Set click event for close item - getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) - -> clickPlayer.closeInventory()); - - // Set click event for plot info item - getMenu().getSlot(4).setClickHandler((clickPlayer, clickInformation) - -> new PlotActionsMenu(clickPlayer, plot)); - - /* Set click event for submit item */ - getMenu().getSlot(48).setClickHandler((clickPlayer, clickInformation) - -> Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - try { - StringBuilder score = new StringBuilder(); - - int totalRating = 0; - boolean isRejected = false; - - for (int i = 0; i < 4; i++) { - for (int j = 0; j < 6; j++) { - if (Objects.requireNonNull(getMenu().getSlot(11 + (i * 9) + j).getItem(clickPlayer).getItemMeta()).hasEnchant(Enchantment.POWER)) { - if (i == 3) { - score.append(j); - } else { - score.append(j).append(","); - } - totalRating += j; - if (j == 0) isRejected = true; - } - } - } - if (totalRating <= 8) isRejected = true; - - if (totalRating == 0 && !sentWarning) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_ABANDONED))); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); - sentWarning = true; - return; - } else if (isRejected && !sentWarning) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_REJECTED))); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); - sentWarning = true; - return; - } else if (totalRating == 0) { - plot.setStatus(Status.unfinished); - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> clickPlayer.performCommand("plot abandon " + plot.getID())); - return; - } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> clickPlayer.closeInventory()); - - if (plot.isReviewed()) { - plot.getReview().setRating(score.toString()); - plot.getReview().setReviewer(clickPlayer.getUniqueId()); - } else new Review(plot.getID(), clickPlayer.getUniqueId(), score.toString()); - - double totalRatingWithMultiplier = totalRating * Plot.getMultiplierByDifficulty(plot.getDifficulty()); - totalRating = (int) Math.floor(totalRatingWithMultiplier); - plot.setTotalScore(totalRating); - - Component reviewerConfirmationMessage; - - if (!isRejected) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); - try { - if (!PlotUtils.savePlotAsSchematic(plot)) { - clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); - return; - } - } catch (IOException | WorldEditException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); - } - - plot.setStatus(Status.completed); - plot.getReview().setFeedbackSent(false); - plot.getReview().setFeedback("No Feedback"); - - // Remove Plot from Owner - plot.getPlotOwner().setSlot(plot.getSlot(), -1); - - if (plot.getPlotMembers().isEmpty()) { - // Plot was made alone - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); - - // Builder gets 100% of score - plot.getPlotOwner().addScore(totalRating); - } else { - // Plot was made in a group - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), sb.toString())); - - // Score gets split between all participants - plot.getPlotOwner().addScore(plot.getSharedScore()); - - for (Builder builder : plot.getPlotMembers()) { - // Score gets split between all participants - builder.addScore(plot.getSharedScore()); - - // Remove Slot from Member - builder.setSlot(plot.getSlot(), -1); - } - } - } else { - if (!plot.getPlotMembers().isEmpty()) { - // Plot was made alone - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); - } else { - // Plot was made in a group - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), sb.toString())); - } - - PlotUtils.Actions.undoSubmit(plot); - } - - boolean finalIsRejected = isRejected; - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - for (Player player : plot.getWorld().getBukkitWorld().getPlayers()) { - player.teleport(Utils.getSpawnLocation()); - } - - // Delete plot world after reviewing - if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) - plot.getWorld().deleteWorld(); - - clickPlayer.sendMessage(reviewerConfirmationMessage); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1f, 1f); - - ChatInput.awaitChatInput.put(clickPlayer.getUniqueId(), - new PlayerFeedbackChatInput(clickPlayer.getUniqueId(), plot.getReview())); - PlayerFeedbackChatInput.sendChatInputMessage(clickPlayer); - }); - - for (Builder member : plot.getPlotMembers()) { - if (member.isOnline()) PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), member.getPlayer()); - } - - if (plot.getPlotOwner().isOnline()) { - PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), plot.getPlotOwner().getPlayer()); - plot.getReview().setFeedbackSent(true); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } - })); - - // Set click event for point selection items - for (int i = 0; i < 54; i++) { - int slot = i; - - int column = (slot % 9) + 1; - int row = (slot - (slot % 9)) / 9 + 1; - - ItemMeta meta = getMenu().getSlot(slot).getItem(getMenuPlayer()).getItemMeta(); - - if (column > 2 && column < 9 && row > 1 && row < 6) { - //Go through the whole points row - getMenu().getSlot(i).setClickHandler((clickPlayer, clickInformation) -> { - for (int j = 0; j < 6; j++) { - if (!Objects.requireNonNull(getMenu().getSlot(slot - (column - 1) + j + 2).getItem(clickPlayer).getItemMeta()).hasEnchant(Enchantment.POWER)) continue; - - ItemStack itemPrevious = getMenu().getSlot(slot - (column - 1) + j + 2).getItem(clickPlayer); - ItemMeta metaPrevious = itemPrevious.getItemMeta(); - assert metaPrevious != null; - metaPrevious.removeEnchant(Enchantment.POWER); - itemPrevious.setItemMeta(metaPrevious); - getMenu().getSlot(slot - (column - 1) + j + 2).setItem(itemPrevious); - } - - assert meta != null; - meta.addEnchant(Enchantment.POWER, 1, true); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - - ItemStack newItem = getMenu().getSlot(slot).getItem(clickPlayer); - newItem.setItemMeta(meta); - getMenu().getSlot(slot).setItem(newItem); - sentWarning = false; - }); - } - } - } - - @Override - protected Mask getMask() { - return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) - .pattern("101101101") - .pattern("100000001") - .pattern("100000001") - .pattern("100000001") - .pattern("100000001") - .pattern("111010111") - .build(); - } - - // --- Info Items --- - private ItemStack getPlotInfoItem() { - String plotOwner, city, country, difficulty; - Player plotOwnerPlayer; - - plotOwner = plot.getPlotOwner().getName(); - city = plot.getCityProject().getName(getMenuPlayer()); - country = plot.getCityProject().getCountry().getName(getMenuPlayer()); - difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); - - plotOwnerPlayer = plot.getPlotOwner().getPlayer(); - - - return new ItemBuilder(BaseItems.REVIEW_INFO_PLOT.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REVIEW_PLOT)) - .color(AQUA) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.ID) + ": ", GRAY).append(text(plot.getID(), WHITE))) - .emptyLine() - .addLines(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER) + ": ", GRAY).append(text(plotOwner, WHITE)), - text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": ", GRAY).append(text(city, WHITE)), - text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": ", GRAY).append(text(country, WHITE)), - text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": ", GRAY).append(text(difficulty, WHITE))) - .emptyLine() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.PLAYER_LANGUAGE) + ": ", GRAY).append(text(LangUtil.getInstance().get(plotOwnerPlayer, "lang.name"), WHITE))) - .build()) - .build(); - } - - private ItemStack getReviewInfoItem() { - String points = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS); - - return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.INFO_BUTTON.getId())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.INFORMATION), AQUA).decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.INFORMATION)) - .emptyLine() - .addLines(text(points + " <= 0: ", WHITE).append(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ABANDONED), RED)), - text(points + " <= 8: ", WHITE).append(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REJECTED), YELLOW)), - text(points + " > 8: ", WHITE).append(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ACCEPTED), GREEN))) - .build()) - .build(); - } - - // --- Category Items --- - private ItemStack getAccuracyItem() { - return new ItemBuilder(BaseItems.REVIEW_ACCURACY.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY_DESC)) - .build()) - .build(); - } - - private ItemStack getBlockPaletteItem() { - return new ItemBuilder(BaseItems.REVIEW_BLOCK_PALETTE.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE_DESC)) - .build()) - .build(); - } - - private ItemStack getDetailingItem() { - return new ItemBuilder(BaseItems.REVIEW_DETAILING.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.DETAILING)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.DETAILING_DESC)) - .build()) - .build(); - } - - private ItemStack getTechniqueItem() { - return new ItemBuilder(BaseItems.REVIEW_TECHNIQUE.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.TECHNIQUE)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.TECHNIQUE_DESC)) - .build()) - .build(); - } - - // --- Button Items --- - private ItemStack getSubmitItem() { - return new ItemBuilder(BaseItems.REVIEW_SUBMIT.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_REVIEW), true) - .build()) - .build(); - } - - private ItemStack getCancelItem() { - return new ItemBuilder(BaseItems.REVIEW_CANCEL.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.CANCEL)) - .color(RED) - .decoration(BOLD, true)) - .build(); - } - - // --- Point Items --- - private ItemStack getZeroPointItem() { - return new ItemBuilder(BaseItems.REVIEW_POINT_ZERO.getItem()) - .setName(text("0 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) - .color(GRAY) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) - .build()) - .build(); - } - - private ItemStack getOnePointItem() { - return new ItemBuilder(BaseItems.REVIEW_POINT_ONE.getItem()) - .setName(text("1 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINT)) - .color(RED) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) - .build()) - .build(); - } - - private ItemStack getTwoPointItem() { - ItemStack item = BaseItems.REVIEW_POINT_TWO.getItem(); - item.setAmount(2); - - return new ItemBuilder(item) - .setName(text("2 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) - .color(GOLD) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) - .build()) - .build(); - } - - private ItemStack getThreePointItem() { - ItemStack item = BaseItems.REVIEW_POINT_THREE.getItem(); - item.setAmount(3); - - return new ItemBuilder(item) - .setName(text("3 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) - .color(YELLOW) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) - .build()) - .build(); - } - - private ItemStack getFourPointItem() { - ItemStack item = BaseItems.REVIEW_POINT_FOUR.getItem(); - item.setAmount(4); - - return new ItemBuilder(item) - .setName(text("4 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) - .color(DARK_GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) - .build()) - .build(); - } - - private ItemStack getFivePointItem() { - ItemStack item = BaseItems.REVIEW_POINT_FIVE.getItem(); - item.setAmount(5); - - return new ItemBuilder(item) - .setName(text("5 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) - .build()) - .build(); - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java new file mode 100644 index 00000000..32def0d1 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java @@ -0,0 +1,62 @@ +package com.alpsbte.plotsystem.core.menus.review; + +import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; +import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.alpslib.utils.item.LoreBuilder; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.BaseItems; +import com.alpsbte.plotsystem.utils.items.CustomHeads; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.TextDecoration.BOLD; + +public class ReviewItems { + public static ItemStack getReviewInfoItem(Player player) { + String points = LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_POINTS); + + return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.INFO_BUTTON.getId())) + .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.INFORMATION), AQUA).decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLines(true, LangUtil.getInstance().get(player, LangPaths.MenuDescription.INFORMATION)) + .emptyLine() + .addLines(text(points + " <= 0: ", WHITE).append(text(LangUtil.getInstance().get(player, LangPaths.Review.ABANDONED), RED)), + text(points + " <= 8: ", WHITE).append(text(LangUtil.getInstance().get(player, LangPaths.Review.REJECTED), YELLOW)), + text(points + " > 8: ", WHITE).append(text(LangUtil.getInstance().get(player, LangPaths.Review.ACCEPTED), GREEN))) + .build()) + .build(); + } + + public static ItemStack getPlotInfoItem(Player player, Plot plot) { + String plotOwner, city, country, difficulty; + Player plotOwnerPlayer; + + plotOwner = plot.getPlotOwner().getName(); + city = plot.getCityProject().getName(player); + country = plot.getCityProject().getCountry().getName(player); + difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); + + plotOwnerPlayer = plot.getPlotOwner().getPlayer(); + + + return new ItemBuilder(BaseItems.REVIEW_INFO_PLOT.getItem()) + .setName(text(LangUtil.getInstance().get(player, LangPaths.Review.REVIEW_PLOT)) + .color(AQUA) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(text(LangUtil.getInstance().get(player, LangPaths.Plot.ID) + ": ", GRAY).append(text(plot.getID(), WHITE))) + .emptyLine() + .addLines(text(LangUtil.getInstance().get(player, LangPaths.Plot.OWNER) + ": ", GRAY).append(text(plotOwner, WHITE)), + text(LangUtil.getInstance().get(player, LangPaths.Plot.CITY) + ": ", GRAY).append(text(city, WHITE)), + text(LangUtil.getInstance().get(player, LangPaths.Plot.COUNTRY) + ": ", GRAY).append(text(country, WHITE)), + text(LangUtil.getInstance().get(player, LangPaths.Plot.DIFFICULTY) + ": ", GRAY).append(text(difficulty, WHITE))) + .emptyLine() + .addLine(text(LangUtil.getInstance().get(player, LangPaths.Review.PLAYER_LANGUAGE) + ": ", GRAY).append(text(LangUtil.getInstance().get(plotOwnerPlayer, "lang.name"), WHITE))) + .build()) + .build(); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java new file mode 100644 index 00000000..0caabeba --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -0,0 +1,328 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2023, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.alpsbte.plotsystem.core.menus.review; + +import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.alpslib.utils.item.LoreBuilder; +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.menus.AbstractMenu; +import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; +import com.alpsbte.plotsystem.core.menus.ReviewMenu; +import com.alpsbte.plotsystem.core.system.review.ReviewRating; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.BaseItems; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.items.MenuItems; +import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.enums.Status; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.ipvp.canvas.mask.BinaryMask; +import org.ipvp.canvas.mask.Mask; + +import java.util.List; +import java.util.Objects; + +import static net.kyori.adventure.text.Component.empty; +import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.TextDecoration.BOLD; + +public class ReviewPlotMenu extends AbstractMenu { + private final Plot plot; + private final ReviewRating rating; + + boolean sentWarning = false; + + public ReviewPlotMenu(Player player, Plot plot) { + super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); + this.plot = plot; + this.rating = new ReviewRating(0, 0, List.of()); + } + + @Override + protected void setPreviewItems() { + for (int col = 0; col < 6; col++) { + for (int row = 0; row < 2; row++) { + ItemStack item; + switch (col) { + case 0 -> { + item = getZeroPointItem(); + ItemMeta itemMeta = item.getItemMeta(); + Objects.requireNonNull(itemMeta).addEnchant(Enchantment.POWER, 1, true); + item.setItemMeta(itemMeta); + } + case 1 -> item = getOnePointItem(); + case 2 -> item = getTwoPointItem(); + case 3 -> item = getThreePointItem(); + case 4 -> item = getFourPointItem(); + default -> item = getFivePointItem(); + } + getMenu().getSlot(29 + col + (9 * row)).setItem(item); + } + } + + getMenu().getSlot(4).setItem(MenuItems.loadingItem(Material.MAP, getMenuPlayer())); + + getMenu().getSlot(28).setItem(getAccuracyItem()); + getMenu().getSlot(37).setItem(getBlockPaletteItem()); + + getMenu().getSlot(48).setItem(getSubmitItem()); + getMenu().getSlot(50).setItem(getCancelItem()); + + super.setPreviewItems(); + } + + @Override + protected void setMenuItemsAsync() { + // Set back item + getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); + + // Set plot information item + getMenu().getSlot(4).setItem(ReviewItems.getPlotInfoItem(getMenuPlayer(), plot)); + + // Set review information item + getMenu().getSlot(7).setItem(ReviewItems.getReviewInfoItem(getMenuPlayer())); + } + + @Override + protected void setItemClickEventsAsync() { + // Set click event for back item + getMenu().getSlot(1).setClickHandler((clickPlayer, clickInformation) + -> new ReviewMenu(getMenuPlayer())); + + // Set click event for close item + getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) + -> clickPlayer.closeInventory()); + + // Set click event for plot info item + getMenu().getSlot(4).setClickHandler((clickPlayer, clickInformation) + -> new PlotActionsMenu(clickPlayer, plot)); + + /* Set click event for submit item */ + getMenu().getSlot(48).setClickHandler((clickPlayer, clickInformation) + -> Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { + int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); + boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; + + if (totalRating == 0 && !sentWarning) { + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_ABANDONED))); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); + sentWarning = true; + return; + } else if (isRejected && !sentWarning) { + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_REJECTED))); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); + sentWarning = true; + return; + } else if (totalRating == 0) { + plot.setStatus(Status.unfinished); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + clickPlayer.closeInventory(); + clickPlayer.performCommand("plot abandon " + plot.getID()); + }); + return; + } + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + clickPlayer.closeInventory(); + new ReviewPlotTogglesMenu(clickPlayer, plot, rating); + }); + })); + + // Set click event for point selection items + for (int col = 0; col < 6; col++) { + for (int row = 0; row < 2; row++) { + int slot = 29 + col + (9 * row); + int captureRow = row; // need to assign separate variables so that they can be captured by the lambda + int points = col; + ItemMeta meta = getMenu().getSlot(slot).getItem(getMenuPlayer()).getItemMeta(); + getMenu().getSlot(slot).setClickHandler((clickPlayer, clickInformation) -> { + for (int j = 0; j < 6; j++) { + ItemStack previousItem = getMenu().getSlot(29 + j + (9 * captureRow)).getItem(clickPlayer); + if (previousItem == null || !previousItem.getItemMeta().hasEnchant(Enchantment.POWER)) continue; + + ItemMeta metaPrevious = previousItem.getItemMeta(); + assert metaPrevious != null; + metaPrevious.removeEnchant(Enchantment.POWER); + previousItem.setItemMeta(metaPrevious); + getMenu().getSlot(29 + j + (9 * captureRow)).setItem(previousItem); + } + + assert meta != null; + meta.addEnchant(Enchantment.POWER, 1, true); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); + + ItemStack newItem = getMenu().getSlot(slot).getItem(clickPlayer); + newItem.setItemMeta(meta); + getMenu().getSlot(slot).setItem(newItem); + sentWarning = false; + + if (captureRow == 0) rating.setAccuracyPoints(points); + else rating.setBlockPalettePoints(points); + }); + } + } + } + + @Override + protected Mask getMask() { + return BinaryMask.builder(getMenu()) + .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .pattern("101101101") + .pattern("100000001") + .pattern("100000001") + .pattern("100000001") + .pattern("100000001") + .pattern("111010111") + .build(); + } + + // --- Category Items --- + private ItemStack getAccuracyItem() { + return new ItemBuilder(BaseItems.REVIEW_ACCURACY.getItem()) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY)) + .color(GREEN) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY_DESC)) + .build()) + .build(); + } + + private ItemStack getBlockPaletteItem() { + return new ItemBuilder(BaseItems.REVIEW_BLOCK_PALETTE.getItem()) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE)) + .color(GREEN) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLines(true, LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE_DESC)) + .build()) + .build(); + } + + // --- Button Items --- + private ItemStack getSubmitItem() { + return new ItemBuilder(BaseItems.REVIEW_SUBMIT.getItem()) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT)) + .color(GREEN) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_REVIEW), true) + .build()) + .build(); + } + + private ItemStack getCancelItem() { + return new ItemBuilder(BaseItems.REVIEW_CANCEL.getItem()) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.CANCEL)) + .color(RED) + .decoration(BOLD, true)) + .build(); + } + + // --- Point Items --- + private ItemStack getZeroPointItem() { + return new ItemBuilder(BaseItems.REVIEW_POINT_ZERO.getItem()) + .setName(text("0 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) + .color(GRAY) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) + .build()) + .build(); + } + + private ItemStack getOnePointItem() { + return new ItemBuilder(BaseItems.REVIEW_POINT_ONE.getItem()) + .setName(text("1 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINT)) + .color(RED) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) + .build()) + .build(); + } + + private ItemStack getTwoPointItem() { + ItemStack item = BaseItems.REVIEW_POINT_TWO.getItem(); + item.setAmount(2); + + return new ItemBuilder(item) + .setName(text("2 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) + .color(GOLD) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) + .build()) + .build(); + } + + private ItemStack getThreePointItem() { + ItemStack item = BaseItems.REVIEW_POINT_THREE.getItem(); + item.setAmount(3); + + return new ItemBuilder(item) + .setName(text("3 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) + .color(YELLOW) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) + .build()) + .build(); + } + + private ItemStack getFourPointItem() { + ItemStack item = BaseItems.REVIEW_POINT_FOUR.getItem(); + item.setAmount(4); + + return new ItemBuilder(item) + .setName(text("4 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) + .color(DARK_GREEN) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) + .build()) + .build(); + } + + private ItemStack getFivePointItem() { + ItemStack item = BaseItems.REVIEW_POINT_FIVE.getItem(); + item.setAmount(5); + + return new ItemBuilder(item) + .setName(text("5 " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.REVIEW_POINTS)) + .color(GREEN) + .decoration(BOLD, true)) + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.REVIEW_POINTS)) + .build()) + .build(); + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java new file mode 100644 index 00000000..f2e30477 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -0,0 +1,201 @@ +package com.alpsbte.plotsystem.core.menus.review; + +import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.menus.AbstractMenu; +import com.alpsbte.plotsystem.core.system.BuildTeam; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; +import com.alpsbte.plotsystem.core.system.review.ReviewRating; +import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; +import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.chat.ChatInput; +import com.alpsbte.plotsystem.utils.chat.PlayerFeedbackChatInput; +import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.MenuItems; +import com.sk89q.worldedit.WorldEditException; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.ipvp.canvas.mask.BinaryMask; +import org.ipvp.canvas.mask.Mask; + +import java.io.IOException; +import java.util.List; + +import static net.kyori.adventure.text.Component.empty; +import static net.kyori.adventure.text.Component.text; + +public class ReviewPlotTogglesMenu extends AbstractMenu { + + private final Plot plot; + private final ReviewRating rating; + + public ReviewPlotTogglesMenu(Player player, Plot plot, ReviewRating rating) { + super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); + this.plot = plot; + this.rating = rating; + } + + @Override + protected void setMenuItemsAsync() { + // Set back item + getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); + + // Set plot information item + getMenu().getSlot(4).setItem(ReviewItems.getPlotInfoItem(getMenuPlayer(), plot)); + + // Set review information item + getMenu().getSlot(7).setItem(ReviewItems.getReviewInfoItem(getMenuPlayer())); + } + + @Override + protected void setItemClickEventsAsync() { + + } + + @Override + protected Mask getMask() { + return BinaryMask.builder(getMenu()) + .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .pattern("111101111") + .pattern("100000001") + .pattern("100000001") + .pattern("100000001") + .pattern("100000001") + .pattern("111010111") + .build(); + } + + + + private void submitReview() { + // a plot is rejected if either of the point sliders are 0 + boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; + + int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); + BuildTeam bt = plot.getCityProject().getBuildTeam(); + List buildTeamCriteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(bt.getID()); + int checkedCounter = 0; + for (ToggleCriteria criteria : buildTeamCriteria) { + boolean checked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); + if (checked) checkedCounter++; + else if (!criteria.isOptional()) { + isRejected = true; // a plot is also rejected if any of the required toggles are not checked + } + } + int checkedPoints = (int) Math.floor(((double)checkedCounter / buildTeamCriteria.size())*10); + totalRating += checkedPoints; + + if (totalRating <= 8) isRejected = true; // a plot is also rejected if the total rating is less than or equal to 8 + + double scoreMultiplier = DataProvider.DIFFICULTY.getDifficultyByEnum(plot.getDifficulty()).orElseThrow().getMultiplier(); + double totalRatingWithMultiplier = totalRating * scoreMultiplier; + int score = (int) Math.floor(totalRatingWithMultiplier); + + boolean successful = DataProvider.REVIEW.createReview(rating, score, getMenuPlayer().getUniqueId(), isRejected); + if (!successful) { + getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); + return; + } + + Component reviewerConfirmationMessage; + if (!isRejected) { + getMenuPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); + try { + if (!PlotUtils.savePlotAsSchematic(plot)) { + getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); + return; + } + } catch (IOException | WorldEditException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); + } + + plot.setStatus(Status.completed); + + // Remove Plot from Owner + plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(plot), -1); + + if (plot.getPlotMembers().isEmpty()) { + // Plot was made alone + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); + + // Builder gets 100% of score + plot.getPlotOwner().addScore(totalRating); + } else { + // Plot was made in a group + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < plot.getPlotMembers().size(); i++) { + sb.append(i == plot.getPlotMembers().size() - 1 ? + plot.getPlotMembers().get(i).getName() : + plot.getPlotMembers().get(i).getName() + ", "); + } + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), sb.toString())); + + // Score gets split between all participants + plot.getPlotOwner().addScore(plot.getSharedScore()); + + for (Builder builder : plot.getPlotMembers()) { + // Score gets split between all participants + builder.addScore(plot.getSharedScore()); + + // Remove Slot from Member + builder.setSlot(builder.getSlot(plot), -1); + } + } + } else { + if (!plot.getPlotMembers().isEmpty()) { + // Plot was made alone + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); + } else { + // Plot was made in a group + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < plot.getPlotMembers().size(); i++) { + sb.append(i == plot.getPlotMembers().size() - 1 ? + plot.getPlotMembers().get(i).getName() : + plot.getPlotMembers().get(i).getName() + ", "); + } + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), sb.toString())); + } + + PlotUtils.Actions.undoSubmit(plot); + } + + boolean finalIsRejected = isRejected; + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + for (Player player : plot.getWorld().getBukkitWorld().getPlayers()) { + player.teleport(Utils.getSpawnLocation()); + } + + // Delete plot world after reviewing + if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) + plot.getWorld().deleteWorld(); + + getMenuPlayer().sendMessage(reviewerConfirmationMessage); + getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1f, 1f); + + + ChatInput.awaitChatInput.put(getMenuPlayer().getUniqueId(), + new PlayerFeedbackChatInput(getMenuPlayer().getUniqueId(), plot.getLatestReview().orElseThrow())); + PlayerFeedbackChatInput.sendChatInputMessage(getMenuPlayer()); + }); + + // TODO: send feedback messages to owner and members + /*for (Builder member : plot.getPlotMembers()) { + if (member.isOnline()) PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), member.getPlayer()); + } + + if (plot.getPlotOwner().isOnline()) { + PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), plot.getPlotOwner().getPlayer()); + plot.getReview().setFeedbackSent(true); + }*/ + + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 72a261e1..851f108d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -91,6 +91,10 @@ public Plot getSlot(Slot slot) { return null; } + public Slot getSlot(Plot plot) { + return DataProvider.BUILDER.getSlot(this.uuid, plot.getID()); + } + public boolean setSlot(Slot slot, int plotId) { if (DataProvider.BUILDER.setSlot(this.uuid, plotId, slot)) { switch (slot) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index 2b5c8cc9..26c71a50 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -52,12 +52,14 @@ public class CityProject { private final String countryCode; private String serverName; private boolean isVisible; + private int buildTeamId; - public CityProject(String id, String countryCode, String serverName, boolean isVisible) { + public CityProject(String id, String countryCode, String serverName, boolean isVisible, int buildTeamId) { this.ID = id; this.countryCode = countryCode; this.serverName = serverName; this.isVisible = isVisible; + this.buildTeamId = buildTeamId; } public String getID() { @@ -101,6 +103,10 @@ public String getDescription(Player player) { return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + ID + ".description"); } + public BuildTeam getBuildTeam() { + return DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId).orElseThrow(); + } + public List getDescriptionComponents(Player player) { ArrayList descriptionLines = new ArrayList<>(); for (String line : getDescription(player).split("%newline%")) descriptionLines.add(text(line)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java index 66cf34a2..e136f55f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java @@ -43,10 +43,6 @@ public class Review { private final int reviewID; - public Review(int reviewID) { - this.reviewID = reviewID; - } - public Review(int plotID, UUID reviewer, String rating) throws SQLException { this.reviewID = DatabaseConnection.getTableID("plotsystem_reviews"); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 0b02a211..52ee646b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -34,6 +34,7 @@ import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Slot; import com.alpsbte.plotsystem.utils.enums.Status; @@ -44,12 +45,11 @@ import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; -import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -59,21 +59,19 @@ public class Plot extends AbstractPlot { private final CityProject cityProject; private final PlotDifficulty difficulty; private Status status; - private final int score; - private String outlineBounds; + private final String outlineBounds; private LocalDate lastActivity; private final List members; private CityPlotWorld cityPlotWorld; public Plot( - int id, CityProject cityProject, PlotDifficulty difficulty, UUID ownerUUID, Status status, int score, + int id, CityProject cityProject, PlotDifficulty difficulty, UUID ownerUUID, Status status, String outlineBounds, LocalDate lastActivity, double version, PlotType type, List members) { super(id, ownerUUID); this.cityProject = cityProject; this.difficulty = difficulty; this.status = status; - this.score = score; this.outlineBounds = outlineBounds; this.lastActivity = lastActivity; this.plotVersion = version; @@ -172,7 +170,8 @@ public T getWorld() { } public int getTotalScore() { - return score; + Optional review = getLatestReview(); + return review.map(PlotReview::getScore).orElse(-1); } public void setTotalScore(int score) throws SQLException { @@ -214,13 +213,18 @@ public BlockVector3 getCenter() { return null; } - public Slot getSlot() { - // TODO: Implement - return null; + public List getReviewHistory() { + return DataProvider.REVIEW.getPlotReviewHistory(getID()); + } + + public Optional getLatestReview() { + return DataProvider.REVIEW.getLatestReview(getID()); } public Review getReview() { - return DataProvider.PLOT.getReview(getID()); + // TODO: to be deleted + return null; + //return DataProvider.REVIEW.getReview(getID()); } public boolean setPasted(boolean pasted) throws SQLException { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 9060ca38..9314c626 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -409,7 +409,7 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { if (plot.getPlotOwner() != null) { Cache.clearCache(plot.getPlotOwner().getUUID()); - plot.getPlotOwner().setSlot(dPlot.getSlot(), -1); + plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1); } dPlot.setPlotOwner(null); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java new file mode 100644 index 00000000..9fa97e61 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -0,0 +1,68 @@ +package com.alpsbte.plotsystem.core.system.review; + +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import org.jetbrains.annotations.Nullable; + +import java.util.List; +import java.util.UUID; + +public class PlotReview { + private final int reviewId; + private final int plotId; + private final ReviewRating rating; + private List toggleCriteria; + private int score; + @Nullable + private String feedback; + private UUID reviewedBy; + + public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, @Nullable String feedback) { + this.reviewId = reviewId; + this.plotId = plotId; + this.rating = rating; + this.score = score; + this.feedback = feedback; + } + + public int getReviewId() { + return reviewId; + } + + public ReviewRating getRating() { + return rating; + } + + public @Nullable String getFeedback() { + return feedback; + } + + public Plot getPlot() { + return DataProvider.PLOT.getPlotById(plotId); + } + + public int getPlotId() { + return plotId; + } + + public Builder getReviewer() { + return DataProvider.BUILDER.getBuilderByUUID(reviewedBy); + } + + public UUID getReviewerUUID() { + return reviewedBy; + } + + public int getScore() { + return score; + } + + public boolean updateFeedback(String feedback) { + if (DataProvider.REVIEW.updateFeedback(reviewId, feedback)) { + this.feedback = feedback; + return true; + } + return false; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java new file mode 100644 index 00000000..81dcd8fe --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java @@ -0,0 +1,40 @@ +package com.alpsbte.plotsystem.core.system.review; + +import java.util.List; +import java.util.Optional; + +public class ReviewRating { + private int accuracyPoints; + private int blockPalettePoints; + private List checkedToggles; + + public ReviewRating(int accuracyPoints, int blockPalettePoints, List checkedToggles) { + this.accuracyPoints = accuracyPoints; + this.blockPalettePoints = blockPalettePoints; + this.checkedToggles = checkedToggles; + } + + public int getAccuracyPoints() { + return accuracyPoints; + } + + public void setAccuracyPoints(int points) { + accuracyPoints = points; + } + + public int getBlockPalettePoints() { + return blockPalettePoints; + } + + public void setBlockPalettePoints(int points) { + blockPalettePoints = points; + } + + public List getCheckedToggles() { + return checkedToggles; + } + + public void setCheckedToggles(List checkedToggles) { + this.checkedToggles = checkedToggles; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java new file mode 100644 index 00000000..5f62dfc5 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java @@ -0,0 +1,19 @@ +package com.alpsbte.plotsystem.core.system.review; + +public class ToggleCriteria { + private String criteriaName; + private boolean isOptional; + + public ToggleCriteria(String criteriaName, boolean isOptional) { + this.criteriaName = criteriaName; + this.isOptional = isOptional; + } + + public String getCriteriaName() { + return criteriaName; + } + + public boolean isOptional() { + return isOptional; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java b/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java index c48807f9..6ee82f9e 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java @@ -24,7 +24,7 @@ package com.alpsbte.plotsystem.utils.chat; -import com.alpsbte.plotsystem.core.system.Review; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -39,9 +39,9 @@ public class PlayerFeedbackChatInput implements ChatInput { private final LocalDateTime dateTime; - private final Review review; + private final PlotReview review; - public PlayerFeedbackChatInput(UUID playerUUID, Review review) { + public PlayerFeedbackChatInput(UUID playerUUID, PlotReview review) { this.dateTime = LocalDateTime.now(); this.review = review; awaitChatInput.put(playerUUID, this); @@ -52,7 +52,7 @@ public LocalDateTime getDateTime() { return dateTime; } - public Review getReview() { + public PlotReview getReview() { return review; } From 3e0eb61facfac73c265b5deaaa0e8e789702f769 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 4 Apr 2025 18:19:53 +0200 Subject: [PATCH 053/175] implement ReviewNotification, BuildTeamToggleCriteria and continue review rework --- .../commands/review/CMD_Review.java | 5 +- .../commands/review/CMD_UndoReview.java | 20 +- .../plotsystem/core/EventListener.java | 35 +-- .../core/database/providers/PlotProvider.java | 6 +- .../database/providers/ReviewProvider.java | 204 ++++++++++++++-- .../plotsystem/core/menus/FeedbackMenu.java | 16 +- .../core/menus/PlayerPlotsMenu.java | 19 +- .../core/menus/companion/CityProjectMenu.java | 7 +- .../plotsystem/core/system/CityProject.java | 5 +- .../plotsystem/core/system/Review.java | 224 ------------------ .../plotsystem/core/system/plot/Plot.java | 69 +----- .../core/system/plot/utils/PlotUtils.java | 57 ++--- .../review/BuildTeamToggleCriteria.java | 19 ++ .../core/system/review/PlotReview.java | 38 ++- .../system/review/ReviewNotification.java | 21 ++ 15 files changed, 343 insertions(+), 402 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/Review.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java create mode 100644 src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 2b1b2051..76a67423 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -88,10 +88,9 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - // TODO: clarify if plot members will include owner as well // Players cannot review their own plots - if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) - && plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId())) { + boolean isParticipant = plot.getPlotOwner().getUUID() == player.getUniqueId() || plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId()); + if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) && isParticipant) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index 60d2152d..bc26fc76 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -29,8 +29,8 @@ import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigPaths; @@ -43,6 +43,7 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.Optional; import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.format.NamedTextColor.RED; @@ -80,15 +81,22 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - // TODO: clarify if plot members will include owner as well // Players cannot review their own plots - if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) - && plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId())) { + boolean isParticipant = plot.getPlotOwner().getUUID() == player.getUniqueId() || plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId()); + if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) && isParticipant) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); + return; + } + + Optional review = plot.getLatestReview(); + if (review.isEmpty()) { + player.sendMessage(Utils.ChatUtils.getAlertFormat("Review could not be found!")); // TODO: translate text + return; } - Review.undoReview(plot.getReview()); - sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UNDID_REVIEW, plot.getID() + "", plot.getPlotOwner().getName()))); + boolean successful = review.get().undoReview(); + if (successful) player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.UNDID_REVIEW, plot.getID() + "", plot.getPlotOwner().getName()))); + else player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.ERROR_OCCURRED))); }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index d636cdaf..2082de8c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -35,6 +35,7 @@ import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; +import com.alpsbte.plotsystem.core.system.review.ReviewNotification; import com.alpsbte.plotsystem.core.system.tutorial.AbstractPlotTutorial; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; import com.alpsbte.plotsystem.core.system.tutorial.Tutorial; @@ -75,9 +76,7 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; import java.time.Duration; -import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.UUID; @@ -275,28 +274,16 @@ private void sendNotices(@NotNull Player player, Builder builder) { } // Informing player about new feedback - try { - List plots = DataProvider.PLOT.getPlots(builder, Status.completed, Status.unfinished); - List reviewedPlots = new ArrayList<>(); - - for (Plot plot : plots) { - if (plot.isReviewed() && !plot.getReview().isFeedbackSent()) { - reviewedPlots.add(plot); - plot.getReview().setFeedbackSent(true); - } - } - - if (!reviewedPlots.isEmpty()) { - PlotUtils.ChatFormatting.sendFeedbackMessage(reviewedPlots, player); - String subtitleText = " Plot" + (reviewedPlots.size() == 1 ? " " : "s ") + (reviewedPlots.size() == 1 ? "has" : "have") + " been reviewed!"; - player.showTitle(Title.title( - empty(), - text(reviewedPlots.size(), GOLD).decoration(BOLD, true).append(text(subtitleText, GREEN).decoration(BOLD, true)), - Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofSeconds(1))) - ); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his plot feedback!"), ex); + List notifications = DataProvider.REVIEW.getReviewNotifications(player.getUniqueId()); + + if (!notifications.isEmpty()) { + PlotUtils.ChatFormatting.sendFeedbackMessage(notifications, player); + String subtitleText = " Plot" + (notifications.size() == 1 ? " " : "s ") + (notifications.size() == 1 ? "has" : "have") + " been reviewed!"; + player.showTitle(Title.title( + empty(), + text(notifications.size(), GOLD).decoration(BOLD, true).append(text(subtitleText, GREEN).decoration(BOLD, true)), + Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofSeconds(1))) + ); } PlotUtils.informPlayerAboutUnfinishedPlots(player, builder); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 1892d299..a52bd9d4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -28,6 +28,7 @@ import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.*; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; @@ -37,6 +38,7 @@ import java.time.LocalDate; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.UUID; public class PlotProvider { @@ -206,9 +208,9 @@ public List getPlotMembers(int plotId) { return new ArrayList<>(); } - public Review getReview(int plotId) { + public Optional getReview(int plotId) { // TODO: implement - return null; + return Optional.empty(); } public byte[] getInitialSchematic(int plotId) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index dc2d7eff..db2e5882 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,20 +1,92 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.core.system.review.PlotReview; -import com.alpsbte.plotsystem.core.system.review.ReviewRating; -import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; +import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.system.review.*; +import com.alpsbte.plotsystem.utils.Utils; -import java.util.List; -import java.util.Optional; -import java.util.UUID; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; public class ReviewProvider { + private static final List cachedNotifications = new ArrayList<>(); + private static final List cachedToggleCriteria = new ArrayList<>(); + private static final List cachedBuildTeamToggleCriteria = new ArrayList<>(); + + public ReviewProvider() { + // cache all review notifications + String query = "SELECT review_id, uuid FROM builder_has_review_notification;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + cachedNotifications.add(new ReviewNotification(rs.getInt(1), UUID.fromString(rs.getString(2)))); + } + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + + // cache all toggle criteria + query = "SELECT criteria_name, is_optional FROM review_toggle_criteria;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + cachedToggleCriteria.add(new ToggleCriteria(rs.getString(1), rs.getBoolean(2))); + } + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + + // cache all build team toggle criteria + query = "SELECT criteria_name, build_team_id FROM build_team_uses_toggle_criteria;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + String criteriaName = rs.getString(1); + ToggleCriteria toggle = cachedToggleCriteria.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst().orElseThrow(); + cachedBuildTeamToggleCriteria.add(new BuildTeamToggleCriteria(rs.getInt(2), toggle)); + } + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + } + public Optional getReview(int reviewId) { - // TODO: implement - return null; + String query = "SELECT plot_id, rating, feedback, score, reviewed_by, review_date FROM plot_review WHERE review_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return Optional.empty(); + + int plotId = rs.getInt(1); + String feedback = rs.getString(3); + int score = rs.getInt(4); + + String ratingString = rs.getString(2); + int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); + int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); + List checkedCriteria = getCheckedToggleCriteria(reviewId); + ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); + + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback)); + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return Optional.empty(); } public Optional getLatestReview(int plotId) { + // TODO: implement return null; } @@ -28,18 +100,122 @@ public boolean updateFeedback(int reviewId, String newFeedback) { return false; } - public List getBuildTeamToggleCriteria(int buildTeamId) { - // TODO: implement - return List.of(); - } - public boolean createReview(ReviewRating rating, int score, UUID reviewerUUID, boolean isRejected) { // TODO: implement // also create feedback notification return false; } - public boolean undoReview() { + public boolean removeReview(int reviewId) { + // remove all review notifications + List notifications = getReviewNotifications(reviewId); + for (ReviewNotification notification : notifications) { + removeReviewNotification(notification.getReviewId(), notification.getUuid()); + } + + // remove checked toggle criteria + removeCheckedToggleCriteria(reviewId); + + // remove review + String query = "DELETE FROM plot_review WHERE review_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + + public boolean removeAllReviewsOfPlot(int plotId) { + List reviewIds = new ArrayList<>(); + String query = "SELECT review_id FROM plot_review WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, plotId); + + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) reviewIds.add(rs.getInt(1)); + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + + boolean successful = true; + for (int reviewId : reviewIds) { + successful = successful && removeReview(reviewId); + } + return successful; + } + + // --- Toggle Criteria --- + public Optional getToggleCriteria(String criteriaName) { + return cachedToggleCriteria.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst(); + } + + public List getCheckedToggleCriteria(int reviewId) { + List toggleCriteriaList = new ArrayList<>(); + String query = "SELECT criteria_name FROM review_contains_toggle_criteria WHERE review_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + toggleCriteriaList.add(getToggleCriteria(rs.getString(1)).orElseThrow()); + } + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return toggleCriteriaList; + } + + public List getBuildTeamToggleCriteria(int buildTeamId) { + return cachedBuildTeamToggleCriteria.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); + } + + public boolean removeCheckedToggleCriteria(int reviewId) { + String query = "DELETE FROM review_contains_toggle_criteria WHERE review_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + + // --- Review Notification --- + public Optional getReviewNotification(int reviewId, UUID uuid) { + return cachedNotifications.stream().filter(n -> n.getReviewId() == reviewId && n.getUuid() == uuid).findFirst(); + } + + public List getReviewNotifications(int reviewId) { + return cachedNotifications.stream().filter(n -> n.getReviewId() == reviewId).toList(); + } + + public List getReviewNotifications(UUID uuid) { + return cachedNotifications.stream().filter(n -> n.getUuid() == uuid).toList(); + } + + public boolean removeReviewNotification(int reviewId, UUID uuid) { + Optional notification = getReviewNotification(reviewId, uuid); + if (notification.isEmpty()) return false; + + String query = "DELETE FROM builder_has_review_notification WHERE review_id = ? AND uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + stmt.setString(2, uuid.toString()); + boolean result = stmt.executeUpdate() > 0; + if (result) cachedNotifications.remove(notification.get()); + return result; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 45c337c4..d73f6a92 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -27,9 +27,7 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; @@ -41,9 +39,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.ResultSet; -import java.sql.SQLException; - import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; @@ -68,16 +63,7 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Get review id from plot - try (ResultSet rs = DatabaseConnection.createStatement("SELECT review_id FROM plotsystem_plots WHERE id = ?") - .setValue(plot.getID()).executeQuery()) { - - if (rs.next()) { - DataProvider.REVIEW.getReview(rs.getInt(1)).ifPresent(value -> this.review = value); - } - DatabaseConnection.closeResultSet(rs); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - } + DataProvider.PLOT.getReview(plot.getID()).ifPresent(value -> this.review = value); // Set score item getMenu().getSlot(10).setItem(new ItemBuilder(Material.NETHER_STAR) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index f40a4e43..1b1f56d6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -31,8 +31,8 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Category; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import com.alpsbte.plotsystem.utils.io.LangPaths; @@ -45,6 +45,7 @@ import java.sql.SQLException; import java.util.List; +import java.util.Optional; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; @@ -162,25 +163,21 @@ private LoreBuilder getLore(Plot plot, Player p) throws SQLException { .append(text(LangUtil.getInstance().get(p, LangPaths.Plot.GroupSystem.SHARED_BY_MEMBERS, Integer.toString(plot.getPlotMembers().size() + 1)), DARK_GRAY))); } - if (plot.isReviewed() || plot.isRejected()) { + Optional review = plot.getLatestReview(); + if (review.isPresent()) { builder.emptyLine(); builder.addLines( text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(plot.getReview().getRating(Category.ACCURACY))) + .append(Utils.ItemUtils.getColoredPointsComponent(review.get().getRating().getAccuracyPoints())) .append(text("/", DARK_GRAY)).append(text("5", GREEN)), text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.BLOCK_PALETTE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(plot.getReview().getRating(Category.BLOCKPALETTE))) - .append(text("/", DARK_GRAY)).append(text("5", GREEN)), - text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.DETAILING) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(plot.getReview().getRating(Category.DETAILING))) - .append(text("/", DARK_GRAY)).append(text("5", GREEN)), - text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.TECHNIQUE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(plot.getReview().getRating(Category.TECHNIQUE))) + .append(Utils.ItemUtils.getColoredPointsComponent(review.get().getRating().getBlockPalettePoints())) .append(text("/", DARK_GRAY)).append(text("5", GREEN)) ); builder.emptyLine(); builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.FEEDBACK) + ":", GRAY)); - builder.addLine(text(plot.getReview().getFeedback().replaceAll("//", " "), WHITE), true); + String feedback = review.get().getFeedback() == null ? "No Feedback" : review.get().getFeedback().replaceAll("//", " "); // TODO: translate + builder.addLine(text(feedback, WHITE), true); } builder.emptyLine(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 5a2ea320..422b215f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -48,7 +48,6 @@ import org.ipvp.canvas.mask.Mask; import org.jetbrains.annotations.NotNull; -import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; @@ -142,7 +141,7 @@ public static boolean generateRandomPlot(Player player, @NotNull List getValidCityProjects(PlotDifficulty selectedPlot if (pd == null) pd = PlotDifficulty.EASY; return project.isVisible() && !DataProvider.PLOT.getPlots(project, pd, Status.unclaimed).isEmpty(); - } catch (SQLException | ExecutionException | InterruptedException e) { + } catch (ExecutionException | InterruptedException e) { sqlError(player, e); } } else { @@ -229,7 +228,7 @@ protected void setPaginatedItemClickEventsAsync(List source) { } new DefaultPlotGenerator(city, plotDifficultyForCity, builder); - } catch (SQLException | ExecutionException | InterruptedException ex) { + } catch (ExecutionException | InterruptedException ex) { sqlError(clickPlayer, ex); } }); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index 26c71a50..363c3b31 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -38,7 +38,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; @@ -52,7 +51,7 @@ public class CityProject { private final String countryCode; private String serverName; private boolean isVisible; - private int buildTeamId; + private final int buildTeamId; public CityProject(String id, String countryCode, String serverName, boolean isVisible, int buildTeamId) { this.ID = id; @@ -149,7 +148,7 @@ public ItemStack getItem(Player player, PlotDifficulty selectedPlotDifficulty) { : text(LangUtil.getInstance().get(player, LangPaths.CityProject.PROJECT_NO_PLOTS_AVAILABLE), WHITE).decoration(BOLD, true)) .build()) .build(); - } catch (SQLException | ExecutionException | InterruptedException ex) { + } catch (ExecutionException | InterruptedException ex) { Utils.logSqlException(ex); Thread.currentThread().interrupt(); return MenuItems.errorItem(player); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java b/src/main/java/com/alpsbte/plotsystem/core/system/Review.java deleted file mode 100644 index e136f55f..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Review.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.system; - -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.utils.enums.Category; -import com.alpsbte.plotsystem.utils.enums.Status; -import org.bukkit.Bukkit; - -import java.sql.Date; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.time.LocalDate; -import java.util.UUID; - -import static net.kyori.adventure.text.Component.text; - -public class Review { - private final int reviewID; - - public Review(int plotID, UUID reviewer, String rating) throws SQLException { - this.reviewID = DatabaseConnection.getTableID("plotsystem_reviews"); - - DatabaseConnection.createStatement("INSERT INTO plotsystem_reviews (id, reviewer_uuid, rating, review_date, feedback) VALUES (?, ?, ?, ?, ?)") - .setValue(this.reviewID) - .setValue(reviewer.toString()) - .setValue(rating) - .setValue(java.sql.Date.valueOf(java.time.LocalDate.now())) - .setValue("No Feedback") - .executeUpdate(); - - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET review_id = ? WHERE id = ?") - .setValue(this.reviewID) - .setValue(plotID) - .executeUpdate(); - } - - public int getReviewID() { - return reviewID; - } - - public int getPlotID() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT id FROM plotsystem_plots WHERE review_id = ?") - .setValue(this.reviewID).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } - } - - public Builder getReviewer() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT reviewer_uuid FROM plotsystem_reviews WHERE id = ?") - .setValue(this.reviewID).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return Builder.byUUID(UUID.fromString(s)); - } - - DatabaseConnection.closeResultSet(rs); - return null; - } - } - - public int getRating(Category category) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT rating FROM plotsystem_reviews WHERE id = ?") - .setValue(this.reviewID).executeQuery()) { - - if (rs.next()) { - String[] scoreAsString = rs.getString("rating").split(","); - DatabaseConnection.closeResultSet(rs); - - return switch (category) { - case ACCURACY -> Integer.parseInt(scoreAsString[0]); - case BLOCKPALETTE -> Integer.parseInt(scoreAsString[1]); - case DETAILING -> Integer.parseInt(scoreAsString[2]); - case TECHNIQUE -> Integer.parseInt(scoreAsString[3]); - case ALL -> Integer.parseInt(scoreAsString[0]) + Integer.parseInt(scoreAsString[1]) + Integer.parseInt(scoreAsString[2]) + Integer.parseInt(scoreAsString[3]); - }; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } - } - - public String getFeedback() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT feedback FROM plotsystem_reviews WHERE id = ?") - .setValue(this.reviewID).executeQuery()) { - - if (rs.next()) { - String s = rs.getString(1); - DatabaseConnection.closeResultSet(rs); - return s; - } - - DatabaseConnection.closeResultSet(rs); - return null; - } - } - - public Date getReviewDate() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT review_date FROM plotsystem_reviews WHERE id = ?") - .setValue(this.reviewID).executeQuery()) { - - if (rs.next()) { - Date d = rs.getDate(1); - DatabaseConnection.closeResultSet(rs); - return d; - } - - DatabaseConnection.closeResultSet(rs); - return null; - } - } - - public void setReviewer(UUID reviewer) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_reviews SET reviewer_uuid = ? WHERE id = ?") - .setValue(reviewer.toString()).setValue(this.reviewID).executeUpdate(); - } - - public void setRating(String ratingFormat) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_reviews SET rating = ? WHERE id = ?") - .setValue(ratingFormat).setValue(this.reviewID).executeUpdate(); - } - - public void setFeedback(String feedback) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_reviews SET feedback = ? WHERE id = ?") - .setValue(feedback).setValue(this.reviewID).executeUpdate(); - } - - public void setFeedbackSent(boolean isSent) throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_reviews SET sent = ? WHERE id = ?") - .setValue(isSent ? 1 : 0).setValue(this.reviewID).executeUpdate(); - } - - public void setReviewDate() throws SQLException { - DatabaseConnection.createStatement("UPDATE plotsystem_reviews SET review_date = ? WHERE id = ?") - .setValue(Date.valueOf(LocalDate.now())).setValue(this.reviewID).executeUpdate(); - } - - public boolean isFeedbackSent() throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT sent FROM plotsystem_reviews WHERE id = ?") - .setValue(this.reviewID).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i != 0; - } - - DatabaseConnection.closeResultSet(rs); - return false; - } - } - - public static void undoReview(Review review) { - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - try { - Plot plot = DataProvider.PLOT.getPlotById(review.getPlotID()); - - for (Builder member : plot.getPlotMembers()) { - member.addScore(-plot.getSharedScore()); - - if (member.getFreeSlot() != null) { - member.setSlot(member.getFreeSlot(), plot.getID()); - } - } - - plot.getPlotOwner().addScore(-plot.getSharedScore()); - plot.setTotalScore(-1); - plot.setStatus(Status.unreviewed); - plot.setPasted(false); - - if (plot.getPlotOwner().getFreeSlot() != null) { - plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID()); - } - - DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); - - // TODO: extract sql to data provider - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET review_id = DEFAULT(review_id) WHERE id = ?") - .setValue(review.getPlotID()).executeUpdate(); - - DatabaseConnection.createStatement("DELETE FROM plotsystem_reviews WHERE id = ?") - .setValue(review.reviewID).executeUpdate(); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while undoing review!"), ex); - } - }); - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 52ee646b..f2a10f36 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -26,10 +26,8 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; -import com.alpsbte.plotsystem.core.system.Review; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; @@ -45,8 +43,6 @@ import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.sql.ResultSet; -import java.sql.SQLException; import java.time.LocalDate; import java.util.List; import java.util.Optional; @@ -174,16 +170,6 @@ public int getTotalScore() { return review.map(PlotReview::getScore).orElse(-1); } - public void setTotalScore(int score) throws SQLException { - if (score == -1) { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET score = DEFAULT(score) WHERE id = ?") - .setValue(getID()).executeUpdate(); - } else { - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET score = ? WHERE id = ?") - .setValue(score).setValue(getID()).executeUpdate(); - } - } - public int getSharedScore() { int score = getTotalScore(); if (score != -1 && !getPlotMembers().isEmpty()) { @@ -221,13 +207,7 @@ public Optional getLatestReview() { return DataProvider.REVIEW.getLatestReview(getID()); } - public Review getReview() { - // TODO: to be deleted - return null; - //return DataProvider.REVIEW.getReview(getID()); - } - - public boolean setPasted(boolean pasted) throws SQLException { + public boolean setPasted(boolean pasted) { return DataProvider.PLOT.setPasted(getID(), pasted); } @@ -262,64 +242,35 @@ public boolean removePlotMember(Builder member) { } public boolean isReviewed() { - return getReview() != null; + return getLatestReview().isPresent(); } public boolean isRejected() { return (getStatus() == Status.unfinished || getStatus() == Status.unreviewed) && getTotalScore() != -1; // -1 == null } - public static double getMultiplierByDifficulty(PlotDifficulty plotDifficulty) throws SQLException { - ResultSet rs = DatabaseConnection.createStatement("SELECT multiplier FROM plotsystem_difficulties WHERE id = ?") - .setValue(plotDifficulty.ordinal() + 1).executeQuery(); - - if (rs.next()) { - double d = rs.getDouble(1); - DatabaseConnection.closeResultSet(rs); - return d; - } - - DatabaseConnection.closeResultSet(rs); - return 1; - } - - public static int getScoreRequirementByDifficulty(PlotDifficulty plotDifficulty) throws SQLException { - try (ResultSet rs = DatabaseConnection.createStatement("SELECT score_requirment FROM plotsystem_difficulties WHERE id = ?") - .setValue(plotDifficulty.ordinal() + 1).executeQuery()) { - - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 0; - } - } - - public static boolean hasPlotDifficultyScoreRequirement(@NotNull Builder builder, PlotDifficulty plotDifficulty) throws SQLException { + public static boolean meetsPlotDifficultyScoreRequirement(@NotNull Builder builder, PlotDifficulty plotDifficulty) { int playerScore = builder.getScore(); - int scoreRequirement = Plot.getScoreRequirementByDifficulty(plotDifficulty); + int scoreRequirement = DataProvider.DIFFICULTY.getDifficultyByEnum(plotDifficulty).orElseThrow().getScoreRequirement(); return playerScore >= scoreRequirement; } - public static CompletableFuture getPlotDifficultyForBuilder(CityProject city, Builder builder) throws SQLException { + public static CompletableFuture getPlotDifficultyForBuilder(CityProject city, Builder builder) { // Check if plot difficulties are available boolean easyHasPlots = false, mediumHasPlots = false, hardHasPlots = false; if (!DataProvider.PLOT.getPlots(city, PlotDifficulty.EASY, Status.unclaimed).isEmpty()) easyHasPlots = true; if (!DataProvider.PLOT.getPlots(city, PlotDifficulty.MEDIUM, Status.unclaimed).isEmpty()) mediumHasPlots = true; if (!DataProvider.PLOT.getPlots(city, PlotDifficulty.HARD, Status.unclaimed).isEmpty()) hardHasPlots = true; - if (hardHasPlots && hasPlotDifficultyScoreRequirement(builder, PlotDifficulty.HARD)) { // Return hard + if (hardHasPlots && meetsPlotDifficultyScoreRequirement(builder, PlotDifficulty.HARD)) { // Return hard return CompletableFuture.completedFuture(PlotDifficulty.HARD); - } else if (mediumHasPlots && hasPlotDifficultyScoreRequirement(builder, PlotDifficulty.MEDIUM)) { // Return medium + } else if (mediumHasPlots && meetsPlotDifficultyScoreRequirement(builder, PlotDifficulty.MEDIUM)) { // Return medium return CompletableFuture.completedFuture(PlotDifficulty.MEDIUM); - } else if (easyHasPlots && hasPlotDifficultyScoreRequirement(builder, PlotDifficulty.EASY)) { // Return easy + } else if (easyHasPlots && meetsPlotDifficultyScoreRequirement(builder, PlotDifficulty.EASY)) { // Return easy return CompletableFuture.completedFuture(PlotDifficulty.EASY); - } else if (mediumHasPlots && hasPlotDifficultyScoreRequirement(builder, PlotDifficulty.HARD)) { // If hard has no plots return medium + } else if (mediumHasPlots && meetsPlotDifficultyScoreRequirement(builder, PlotDifficulty.HARD)) { // If hard has no plots return medium return CompletableFuture.completedFuture(PlotDifficulty.EASY); - } else if (easyHasPlots && hasPlotDifficultyScoreRequirement(builder, PlotDifficulty.MEDIUM)) { // If medium has no plots return easy + } else if (easyHasPlots && meetsPlotDifficultyScoreRequirement(builder, PlotDifficulty.MEDIUM)) { // If medium has no plots return easy return CompletableFuture.completedFuture(PlotDifficulty.MEDIUM); } else if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_SCORE_REQUIREMENT)) { // If score requirement is disabled get plot from any available difficulty if (easyHasPlots) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 9314c626..ceeb6ac4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -26,7 +26,6 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; @@ -36,6 +35,8 @@ import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; +import com.alpsbte.plotsystem.core.system.review.PlotReview; +import com.alpsbte.plotsystem.core.system.review.ReviewNotification; import com.alpsbte.plotsystem.utils.ShortLink; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; @@ -81,7 +82,6 @@ import java.math.RoundingMode; import java.net.URISyntaxException; import java.nio.file.Paths; -import java.sql.SQLException; import java.text.DecimalFormat; import java.time.LocalDate; import java.util.*; @@ -393,34 +393,20 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { try { CompletableFuture.runAsync(() -> { - try { - if (plot.getPlotType() != PlotType.TUTORIAL) { - Plot dPlot = (Plot) plot; - if (dPlot.isReviewed()) { - // TODO: extract to data provider - DatabaseConnection.createStatement("UPDATE plotsystem_plots SET review_id = DEFAULT(review_id) WHERE id = ?") - .setValue(plot.getID()).executeUpdate(); - - DatabaseConnection.createStatement("DELETE FROM plotsystem_reviews WHERE id = ?") - .setValue(dPlot.getReview().getReviewID()).executeUpdate(); - } - - for (Builder builder : dPlot.getPlotMembers()) dPlot.removePlotMember(builder); - - if (plot.getPlotOwner() != null) { - Cache.clearCache(plot.getPlotOwner().getUUID()); - plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1); - } - - dPlot.setPlotOwner(null); - dPlot.setLastActivity(true); - dPlot.setTotalScore(-1); - dPlot.setStatus(Status.unclaimed); - dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); + if (plot.getPlotType() != PlotType.TUTORIAL) { + Plot dPlot = (Plot) plot; + DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getID()); + for (Builder builder : dPlot.getPlotMembers()) dPlot.removePlotMember(builder); + + if (plot.getPlotOwner() != null) { + Cache.clearCache(plot.getPlotOwner().getUUID()); + plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - throw new CompletionException(ex); + + dPlot.setPlotOwner(null); + dPlot.setLastActivity(true); + dPlot.setStatus(Status.unclaimed); + dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); } }).join(); } catch (CompletionException ex) { @@ -610,17 +596,20 @@ public static void sendGroupTipMessage(@NotNull Plot plot, Player player) { } } - public static void sendFeedbackMessage(@NotNull List plots, @NotNull Player player) { + public static void sendFeedbackMessage(@NotNull List notifications, @NotNull Player player) { player.sendMessage(text(MSG_LINE, DARK_GRAY)); - for (Plot plot : plots) { - player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(plot.getID())), GREEN))); + for (ReviewNotification notification : notifications) { + PlotReview review = DataProvider.REVIEW.getReview(notification.getReviewId()).orElseThrow(); + player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(review.getPlotId())), GREEN))); Component tc = text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_SHOW_FEEDBACK), GOLD) - .clickEvent(ClickEvent.runCommand("/plot feedback " + plot.getID())) + .clickEvent(ClickEvent.runCommand("/plot feedback " + review.getPlotId())) .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.PLOT_NAME) + " " + LangUtil.getInstance().get(player, LangPaths.Review.FEEDBACK))); player.sendMessage(tc); - if (plots.size() != plots.indexOf(plot) + 1) { + DataProvider.REVIEW.removeReviewNotification(notification.getReviewId(), notification.getUuid()); + + if (notifications.size() != notifications.indexOf(notification) + 1) { player.sendMessage(empty()); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java new file mode 100644 index 00000000..7006ddfc --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java @@ -0,0 +1,19 @@ +package com.alpsbte.plotsystem.core.system.review; + +public class BuildTeamToggleCriteria { + private final int buildTeamId; + private final ToggleCriteria criteria; + + public BuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { + this.buildTeamId = buildTeamId; + this.criteria = criteria; + } + + public int getBuildTeamId() { + return buildTeamId; + } + + public ToggleCriteria getCriteria() { + return criteria; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 9fa97e61..804e41a6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -1,19 +1,21 @@ package com.alpsbte.plotsystem.core.system.review; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.enums.Status; import org.jetbrains.annotations.Nullable; -import java.util.List; import java.util.UUID; +import static net.kyori.adventure.text.Component.text; + public class PlotReview { private final int reviewId; private final int plotId; private final ReviewRating rating; - private List toggleCriteria; - private int score; + private final int score; @Nullable private String feedback; private UUID reviewedBy; @@ -65,4 +67,34 @@ public boolean updateFeedback(String feedback) { } return false; } + + public boolean undoReview() { + Plot plot = DataProvider.PLOT.getPlotById(this.plotId); + if (plot == null) { + PlotSystem.getPlugin().getComponentLogger().error(text("Plot of review could not be found!")); + return false; + } + + // remove owner score and remove plot from slot + plot.getPlotOwner().addScore(-plot.getSharedScore()); + if (plot.getPlotOwner().getFreeSlot() != null) { + plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID()); + } + + // remove members score and remove plot from slot + for (Builder member : plot.getPlotMembers()) { + member.addScore(-plot.getSharedScore()); + + if (member.getFreeSlot() != null) { + member.setSlot(member.getFreeSlot(), plot.getID()); + } + } + + plot.setStatus(Status.unreviewed); + plot.setPasted(false); + + DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); + + return DataProvider.REVIEW.removeReview(reviewId); + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java new file mode 100644 index 00000000..1a206bdc --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java @@ -0,0 +1,21 @@ +package com.alpsbte.plotsystem.core.system.review; + +import java.util.UUID; + +public class ReviewNotification { + private final int reviewId; + private final UUID uuid; + + public ReviewNotification(int reviewId, UUID uuid) { + this.reviewId = reviewId; + this.uuid = uuid; + } + + public int getReviewId() { + return reviewId; + } + + public UUID getUuid() { + return uuid; + } +} From dfdd980bdd127b56b6837bc343c1d63eed270c03 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 4 Apr 2025 19:57:56 +0200 Subject: [PATCH 054/175] finish most core review features/systems --- .../database/providers/ReviewProvider.java | 121 ++++++++++++++++-- .../core/menus/companion/CityProjectMenu.java | 2 +- .../menus/review/ReviewPlotTogglesMenu.java | 13 +- .../core/system/review/PlotReview.java | 6 +- .../core/system/review/ReviewRating.java | 5 +- .../core/system/review/ToggleCriteria.java | 4 +- 6 files changed, 123 insertions(+), 28 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index db2e5882..9e2251d8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,8 +1,13 @@ package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.core.system.review.*; import com.alpsbte.plotsystem.utils.Utils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; import java.sql.Connection; import java.sql.PreparedStatement; @@ -70,6 +75,7 @@ public Optional getReview(int reviewId) { int plotId = rs.getInt(1); String feedback = rs.getString(3); int score = rs.getInt(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); String ratingString = rs.getString(2); int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); @@ -77,7 +83,7 @@ public Optional getReview(int reviewId) { List checkedCriteria = getCheckedToggleCriteria(reviewId); ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); - return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback)); + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -86,24 +92,100 @@ public Optional getReview(int reviewId) { } public Optional getLatestReview(int plotId) { - // TODO: implement - return null; + String query = "SELECT review_id, rating, feedback, score, reviewed_by, review_date FROM plot_review WHERE plot_id = ? ORDER BY review_date DESC LIMIT 1;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, plotId); + + try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return Optional.empty(); + + int reviewId = rs.getInt(1); + String feedback = rs.getString(3); + int score = rs.getInt(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); + + String ratingString = rs.getString(2); + int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); + int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); + List checkedCriteria = getCheckedToggleCriteria(reviewId); + ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); + + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return Optional.empty(); } public List getPlotReviewHistory(int plotId) { - // TODO: implement - return List.of(); + List reviews = new ArrayList<>(); + String query = "SELECT review_id, rating, feedback, score, reviewed_by, review_date FROM plot_review WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, plotId); + + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + int reviewId = rs.getInt(1); + String feedback = rs.getString(3); + int score = rs.getInt(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); + + String ratingString = rs.getString(2); + int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); + int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); + List checkedCriteria = getCheckedToggleCriteria(reviewId); + ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); + + reviews.add(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + } + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return reviews; } public boolean updateFeedback(int reviewId, String newFeedback) { - // TODO: implement + String query = "UPDATE plot_review SET feedback = ? WHERE review_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, newFeedback); + stmt.setInt(2, reviewId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return false; } - public boolean createReview(ReviewRating rating, int score, UUID reviewerUUID, boolean isRejected) { - // TODO: implement - // also create feedback notification - return false; + public boolean createReview(Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { + boolean result = false; + String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by, is_rejected) " + + "VALUES (?, ?, ?, ?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, plot.getID()); + stmt.setString(2, rating.getRatingDatabaseString()); + stmt.setInt(3, score); + stmt.setString(4, reviewerUUID.toString()); + result = stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + + if (!result) return false; + + // create feedback notifications + PlotReview review = plot.getLatestReview().orElseThrow(); + + createReviewNotification(review.getReviewId(), plot.getPlotOwner().getUUID()); + for (Builder builder : plot.getPlotMembers()) { + createReviewNotification(review.getReviewId(), builder.getUUID()); + } + return true; } public boolean removeReview(int reviewId) { @@ -218,4 +300,23 @@ public boolean removeReviewNotification(int reviewId, UUID uuid) { } return false; } + + public void createReviewNotification(int reviewId, UUID uuid) { + Player player = Bukkit.getPlayer(uuid); + if (player != null && player.isOnline()) { + PlotUtils.ChatFormatting.sendFeedbackMessage(List.of(new ReviewNotification(reviewId, uuid)), player); + return; + } + + String query = "INSERT INTO builder_has_review_notification (review_id, uuid) VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + stmt.setString(2, uuid.toString()); + boolean result = stmt.executeUpdate() > 0; + if (result) cachedNotifications.add(new ReviewNotification(reviewId, uuid)); + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 422b215f..ee01da7d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -215,7 +215,7 @@ protected void setPaginatedItemClickEventsAsync(List source) { try { PlotDifficulty plotDifficultyForCity = selectedPlotDifficulty != null ? selectedPlotDifficulty : Plot.getPlotDifficultyForBuilder(city, builder).get(); List unclaimedPlots = DataProvider.PLOT.getPlots(city, plotDifficultyForCity, Status.unclaimed); - if (plotDifficultyForCity == null || unclaimedPlots.isEmpty()) { + if (unclaimedPlots.isEmpty()) { clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(clickPlayer, LangPaths.Message.Error.NO_PLOTS_LEFT))); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.ERROR_SOUND, 1, 1); return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index f2e30477..11b84e21 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -98,7 +98,7 @@ else if (!criteria.isOptional()) { double totalRatingWithMultiplier = totalRating * scoreMultiplier; int score = (int) Math.floor(totalRatingWithMultiplier); - boolean successful = DataProvider.REVIEW.createReview(rating, score, getMenuPlayer().getUniqueId(), isRejected); + boolean successful = DataProvider.REVIEW.createReview(plot, rating, score, getMenuPlayer().getUniqueId()); if (!successful) { getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); return; @@ -186,16 +186,5 @@ else if (!criteria.isOptional()) { new PlayerFeedbackChatInput(getMenuPlayer().getUniqueId(), plot.getLatestReview().orElseThrow())); PlayerFeedbackChatInput.sendChatInputMessage(getMenuPlayer()); }); - - // TODO: send feedback messages to owner and members - /*for (Builder member : plot.getPlotMembers()) { - if (member.isOnline()) PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), member.getPlayer()); - } - - if (plot.getPlotOwner().isOnline()) { - PlotUtils.ChatFormatting.sendFeedbackMessage(Collections.singletonList(plot), plot.getPlotOwner().getPlayer()); - plot.getReview().setFeedbackSent(true); - }*/ - } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 804e41a6..4192f56d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -16,16 +16,18 @@ public class PlotReview { private final int plotId; private final ReviewRating rating; private final int score; + private final UUID reviewedBy; @Nullable private String feedback; - private UUID reviewedBy; - public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, @Nullable String feedback) { + + public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, @Nullable String feedback, UUID reviewedBy) { this.reviewId = reviewId; this.plotId = plotId; this.rating = rating; this.score = score; this.feedback = feedback; + this.reviewedBy = reviewedBy; } public int getReviewId() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java index 81dcd8fe..60488bfb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java @@ -1,7 +1,6 @@ package com.alpsbte.plotsystem.core.system.review; import java.util.List; -import java.util.Optional; public class ReviewRating { private int accuracyPoints; @@ -37,4 +36,8 @@ public List getCheckedToggles() { public void setCheckedToggles(List checkedToggles) { this.checkedToggles = checkedToggles; } + + public String getRatingDatabaseString() { + return accuracyPoints + "," + blockPalettePoints; + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java index 5f62dfc5..56e02bd5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java @@ -1,8 +1,8 @@ package com.alpsbte.plotsystem.core.system.review; public class ToggleCriteria { - private String criteriaName; - private boolean isOptional; + private final String criteriaName; + private final boolean isOptional; public ToggleCriteria(String criteriaName, boolean isOptional) { this.criteriaName = criteriaName; From 2665b1b489d749968bb690b09d72be1caee3cdea Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 5 Apr 2025 23:05:35 +0200 Subject: [PATCH 055/175] set build team via cityproject and not vice versa, fix pss commands and remove unnecessary provider methods --- .../admin/setup/CMD_Setup_BuildTeam.java | 102 ------------------ .../commands/admin/setup/CMD_Setup_City.java | 60 ++++++++++- .../plotsystem/core/EventListener.java | 2 +- .../database/providers/BuilderProvider.java | 15 ++- .../providers/CityProjectProvider.java | 13 +++ .../core/database/providers/PlotProvider.java | 7 +- .../plotsystem/core/menus/FeedbackMenu.java | 2 +- .../menus/review/ReviewPlotTogglesMenu.java | 7 +- .../plotsystem/core/system/BuildTeam.java | 20 ---- .../plotsystem/core/system/CityProject.java | 10 +- 10 files changed, 100 insertions(+), 138 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 73ce204e..84507b52 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -52,8 +52,6 @@ private void register() { registerSubCommand(new CMD_Setup_BuildTeam_Add(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_Remove(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_SetName(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_BuildTeam_AddCityProject(getBaseCommand(), this)); - registerSubCommand(new CMD_Setup_BuildTeam_RemoveCityProject(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_AddReviewer(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_RemoveReviewer(getBaseCommand(), this)); } @@ -267,106 +265,6 @@ public String getPermission() { } } - public static class CMD_Setup_BuildTeam_AddCityProject extends SubCommand { - public CMD_Setup_BuildTeam_AddCityProject(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) { - sendInfo(sender); - return; - } - - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - Optional cityProject = DataProvider.CITY_PROJECT.getById(args[2]); - - if (buildTeam.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); - return; - } - if (cityProject.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("City Project could not be found!")); - return; - } - - boolean successful = buildTeam.get().addCityProject(cityProject.get()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added city project '" + cityProject.get().getID() + "' to build team with ID " + args[1] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - } - - @Override - public String[] getNames() { - return new String[]{"addcityproject"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"BuildTeam-ID", "CityProject-ID"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.buildteam.addcityproject"; - } - } - - public static class CMD_Setup_BuildTeam_RemoveCityProject extends SubCommand { - public CMD_Setup_BuildTeam_RemoveCityProject(BaseCommand baseCommand, SubCommand subCommand) { - super(baseCommand, subCommand); - } - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) { - sendInfo(sender); - return; - } - - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - Optional cityProject = DataProvider.CITY_PROJECT.getById(args[2]); - - if (buildTeam.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team could not be found!")); - return; - } - if (cityProject.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("City project could not be found!")); - return; - } - - boolean successful = buildTeam.get().removeCityProject(cityProject.get().getID()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed city project '" + cityProject.get().getID() + "' from build team with ID " + args[1] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - } - - @Override - public String[] getNames() { - return new String[]{"removecityproject"}; - } - - @Override - public String getDescription() { - return null; - } - - @Override - public String[] getParameter() { - return new String[]{"BuildTeam-ID", "CityProject-ID"}; - } - - @Override - public String getPermission() { - return "plotsystem.admin.pss.buildteam.removecityproject"; - } - } - public static class CMD_Setup_BuildTeam_AddReviewer extends SubCommand { public CMD_Setup_BuildTeam_AddReviewer(BaseCommand baseCommand, SubCommand subCommand) { super(baseCommand, subCommand); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 0fb91c52..14432db7 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -50,6 +50,7 @@ private void register() { registerSubCommand(new CMD_Setup_City_Add(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_City_Remove(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_City_SetServer(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_City_SetBuildTeam(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_City_SetVisible(getBaseCommand(), this)); } @@ -99,6 +100,7 @@ public void onCommand(CommandSender sender, String[] args) { .append(text(c.getID(), AQUA)) .append(text(" - Country: " + c.getCountry().getCode() + " - Server: " + c.getServerName() + + " - Build Team: " + c.getBuildTeam().getName() + " - Visible: " + c.isVisible(), WHITE))); } sender.sendMessage(text("--------------------------", DARK_GRAY)); @@ -132,7 +134,7 @@ public CMD_Setup_City_Add(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 3) {sendInfo(sender); return;} + if (args.length <= 4) {sendInfo(sender); return;} String cityProjectId = args[1]; String countryCode = args[2]; @@ -154,8 +156,14 @@ public void onCommand(CommandSender sender, String[] args) { return; } - // TODO: Add build team id to parameter - boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, -1, country.get().getCode(), serverName); + int buildTeamId = Integer.parseInt(args[4]); + if (DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId).isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any build team with ID " + buildTeamId + "!")); + sendInfo(sender); + return; + } + + boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, buildTeamId, country.get().getCode(), serverName); if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); } @@ -172,7 +180,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"City-Project-ID", "Country-Code", "Server-Name"}; + return new String[]{"City-Project-ID", "Country-Code", "Server-Name", "Build-Team-ID"}; } @Override @@ -276,6 +284,50 @@ public String getPermission() { } } + public static class CMD_Setup_City_SetBuildTeam extends SubCommand { + public CMD_Setup_City_SetBuildTeam(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 2) {sendInfo(sender); return;} + + // Check if City Project exits + Optional cityProject = DataProvider.CITY_PROJECT.getById(args[1]); + if (cityProject.isEmpty()) return; + + // Check if Build Team exists + int buildTeamId = Integer.parseInt(args[2]); + if (DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId).isEmpty()) return; + + boolean successful = cityProject.get().setBuildTeam(buildTeamId); + + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set Build Team of City Project with ID " + args[1] + " to " + buildTeamId + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project build team!")); + } + + @Override + public String[] getNames() { + return new String[]{"setbuildteam"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"City-ID", "Build-Team-ID"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.city.setbuildteam"; + } + } + public static class CMD_Setup_City_SetVisible extends SubCommand { public CMD_Setup_City_SetVisible(BaseCommand baseCommand, SubCommand subCommand) { super(baseCommand, subCommand); diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 2082de8c..9dca8132 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -278,7 +278,7 @@ private void sendNotices(@NotNull Player player, Builder builder) { if (!notifications.isEmpty()) { PlotUtils.ChatFormatting.sendFeedbackMessage(notifications, player); - String subtitleText = " Plot" + (notifications.size() == 1 ? " " : "s ") + (notifications.size() == 1 ? "has" : "have") + " been reviewed!"; + String subtitleText = " Plot" + (notifications.size() == 1 ? " " : "s ") + (notifications.size() == 1 ? "has" : "have") + " been reviewed!"; // TODO: translate player.showTitle(Title.title( empty(), text(notifications.size(), GOLD).decoration(BOLD, true).append(text(subtitleText, GREEN).decoration(BOLD, true)), diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index ef27679d..e0824090 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -198,8 +198,19 @@ public Slot getFreeSlot(UUID uuid) { } public Slot getSlot(UUID uuid, int plotId) { - // TODO: implement - // get the slot in which the given plot is allocated + String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, uuid.toString()); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.getInt(1) == plotId) return Slot.FIRST; + if (rs.getInt(2) == plotId) return Slot.SECOND; + if (rs.getInt(3) == plotId) return Slot.THIRD; + } + } catch (SQLException ex) { + Utils.logSqlException(ex); + } return null; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 85e2414d..33b4ae5a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -147,4 +147,17 @@ public boolean setServer(String id, String serverName) { } return false; } + + public boolean setBuildTeam(String id, int buildTeamId) { + String query = "UPDATE city_project SET build_team_id = ? WHERE city_project_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, buildTeamId); + stmt.setString(2, id); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index a52bd9d4..a86a8260 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -207,12 +207,7 @@ public List getPlotMembers(int plotId) { } return new ArrayList<>(); } - - public Optional getReview(int plotId) { - // TODO: implement - return Optional.empty(); - } - + public byte[] getInitialSchematic(int plotId) { return getSchematic(plotId, "initial_schematic"); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index d73f6a92..f1e13a9d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -63,7 +63,7 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { // Get review id from plot - DataProvider.PLOT.getReview(plot.getID()).ifPresent(value -> this.review = value); + plot.getLatestReview().ifPresent(value -> this.review = value); // Set score item getMenu().getSlot(10).setItem(new ItemBuilder(Material.NETHER_STAR) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 11b84e21..02d13864 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -32,7 +32,6 @@ import static net.kyori.adventure.text.Component.text; public class ReviewPlotTogglesMenu extends AbstractMenu { - private final Plot plot; private final ReviewRating rating; @@ -52,6 +51,12 @@ protected void setMenuItemsAsync() { // Set review information item getMenu().getSlot(7).setItem(ReviewItems.getReviewInfoItem(getMenuPlayer())); + + // Set submit item + getMenu().getSlot(49); + + // Set cancel item + getMenu().getSlot(51); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 3c4c444a..08a5e085 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -66,26 +66,6 @@ public boolean setName(String newName) { return false; } - public boolean addCityProject(CityProject city) { - /*if (DataProvider.CITY_PROJECT.addCityProject(ID, city.getID())) { - this.cityProjects.add(city); - return true; - }*/ - // TODO: Implement - return false; - } - - public boolean removeCityProject(String cityId) { - Optional removeCity = cityProjects.stream().filter(c -> c.getID().equalsIgnoreCase(cityId)).findFirst(); - if (removeCity.isEmpty()) return false; - /*if (DataProvider.BUILD_TEAM.removeCityProject(ID, cityId)) { - this.cityProjects.remove(removeCity.get()); - return true; - }*/ - // TODO: Implement - return false; - } - public boolean removeReviewer(String reviewerUUID) { Optional removeReviewer = reviewers.stream().filter(r -> r.getUUID().toString().equals(reviewerUUID)).findFirst(); if (removeReviewer.isEmpty()) return false; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index 363c3b31..24cb40ea 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -51,7 +51,7 @@ public class CityProject { private final String countryCode; private String serverName; private boolean isVisible; - private final int buildTeamId; + private int buildTeamId; public CityProject(String id, String countryCode, String serverName, boolean isVisible, int buildTeamId) { this.ID = id; @@ -106,6 +106,14 @@ public BuildTeam getBuildTeam() { return DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId).orElseThrow(); } + public boolean setBuildTeam(int buildTeamId) { + if (DataProvider.CITY_PROJECT.setBuildTeam(ID, buildTeamId)) { + this.buildTeamId = buildTeamId; + return true; + } + return false; + } + public List getDescriptionComponents(Player player) { ArrayList descriptionLines = new ArrayList<>(); for (String line : getDescription(player).split("%newline%")) descriptionLines.add(text(line)); From eac3260114721543a989b9118eaf9355bd8db0f8 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 5 Apr 2025 23:20:20 +0200 Subject: [PATCH 056/175] implement codacy suggestions --- .../alpsbte/plotsystem/core/menus/review/ReviewItems.java | 8 +++++--- .../java/com/alpsbte/plotsystem/core/system/Builder.java | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java index 32def0d1..fc576588 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java @@ -32,7 +32,10 @@ public static ItemStack getReviewInfoItem(Player player) { } public static ItemStack getPlotInfoItem(Player player, Plot plot) { - String plotOwner, city, country, difficulty; + String plotOwner; + String city; + String country; + String difficulty; Player plotOwnerPlayer; plotOwner = plot.getPlotOwner().getName(); @@ -41,8 +44,7 @@ public static ItemStack getPlotInfoItem(Player player, Plot plot) { difficulty = plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(); plotOwnerPlayer = plot.getPlotOwner().getPlayer(); - - + return new ItemBuilder(BaseItems.REVIEW_INFO_PLOT.getItem()) .setName(text(LangUtil.getInstance().get(player, LangPaths.Review.REVIEW_PLOT)) .color(AQUA) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 851f108d..d834eced 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -100,7 +100,7 @@ public boolean setSlot(Slot slot, int plotId) { switch (slot) { case FIRST -> firstSlot = plotId; case SECOND -> secondSlot = plotId; - case THIRD -> thirdSlot = plotId; + default -> thirdSlot = plotId; } return true; } From 2dc3d69601a1756e92ea6a4f56b2af418bd53f42 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 5 Apr 2025 23:54:49 +0200 Subject: [PATCH 057/175] use return values of Builder.java methods --- .../alpsbte/plotsystem/core/EventListener.java | 8 ++++---- .../database/providers/BuilderProvider.java | 1 - .../plotsystem/core/menus/PlotTypeMenu.java | 9 ++++++--- .../menus/review/ReviewPlotTogglesMenu.java | 10 +++++----- .../alpsbte/plotsystem/core/system/Builder.java | 2 ++ .../plotsystem/core/system/plot/Plot.java | 4 ++-- .../plot/generator/DefaultPlotGenerator.java | 17 ++++++++--------- .../core/system/plot/utils/PlotUtils.java | 2 +- .../core/system/review/PlotReview.java | 8 ++++---- 9 files changed, 32 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 9dca8132..be8f1554 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -83,8 +83,7 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.GOLD; -import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.*; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class EventListener implements Listener { @@ -100,12 +99,13 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { // Create builder if it does not exist in database. boolean successful = DataProvider.BUILDER.addBuilderIfNotExists(player.getUniqueId(), player.getName()); - if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("BUILDER COULD NOT BE CREATED!!")); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("BUILDER COULD NOT BE CREATED!!", RED)); // Check if player has changed their name Builder builder = Builder.byUUID(player.getUniqueId()); if (!builder.getName().equals(player.getName())) { - builder.setName(player.getName()); + successful = builder.setName(player.getName()); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Builder name could not be updated!", RED)); } sendNotices(event.getPlayer(), builder); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index e0824090..4c865f24 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -110,7 +110,6 @@ public boolean setName(UUID uuid, String name) { stmt.setString(1, name); stmt.setString(2, uuid.toString()); stmt.executeUpdate(); - if (builders.containsKey(uuid)) builders.get(uuid).setName(name); return true; } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index 00c462a1..250ba603 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -106,19 +106,22 @@ protected void setMenuItemsAsync() { protected void setItemClickEventsAsync() { // Set click event for plot type items getMenu().getSlot(11).setClickHandler(((clickPlayer, clickInformation) -> { - builder.setPlotType(PlotType.FOCUS_MODE); + boolean successful = builder.setPlotType(PlotType.FOCUS_MODE); + if (!successful) return; getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); reloadMenuAsync(); })); getMenu().getSlot(13).setClickHandler(((clickPlayer, clickInformation) -> { - builder.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); + boolean successful = builder.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); + if (!successful) return; getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); reloadMenuAsync(); })); getMenu().getSlot(15).setClickHandler(((clickPlayer, clickInformation) -> { - builder.setPlotType(PlotType.CITY_INSPIRATION_MODE); + boolean successful = builder.setPlotType(PlotType.CITY_INSPIRATION_MODE); + if (!successful) return; getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); reloadMenuAsync(); })); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 02d13864..9e1a23c0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -125,14 +125,14 @@ else if (!criteria.isOptional()) { plot.setStatus(Status.completed); // Remove Plot from Owner - plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(plot), -1); + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(plot), -1)) return; if (plot.getPlotMembers().isEmpty()) { // Plot was made alone reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); // Builder gets 100% of score - plot.getPlotOwner().addScore(totalRating); + if (!plot.getPlotOwner().addScore(totalRating)) return; } else { // Plot was made in a group StringBuilder sb = new StringBuilder(); @@ -144,14 +144,14 @@ else if (!criteria.isOptional()) { reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), sb.toString())); // Score gets split between all participants - plot.getPlotOwner().addScore(plot.getSharedScore()); + if (!plot.getPlotOwner().addScore(plot.getSharedScore())) return; for (Builder builder : plot.getPlotMembers()) { // Score gets split between all participants - builder.addScore(plot.getSharedScore()); + if (!builder.addScore(plot.getSharedScore())) return; // Remove Slot from Member - builder.setSlot(builder.getSlot(plot), -1); + if (!builder.setSlot(builder.getSlot(plot), -1)) return; } } } else { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index d834eced..f57968d9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -72,6 +72,7 @@ public int getScore() { return score; } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean addScore(int score) { if (DataProvider.BUILDER.addScore(this.uuid, score)) { this.score = this.score + score; @@ -95,6 +96,7 @@ public Slot getSlot(Plot plot) { return DataProvider.BUILDER.getSlot(this.uuid, plot.getID()); } + @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean setSlot(Slot slot, int plotId) { if (DataProvider.BUILDER.setSlot(this.uuid, plotId, slot)) { switch (slot) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index f2a10f36..093f56b0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -218,7 +218,7 @@ public boolean addPlotMember(Builder member) { if (slot != null) { members.add(member); if (DataProvider.PLOT.setPlotMembers(getID(), members)) { - member.setSlot(slot, getID()); + if (!member.setSlot(slot, getID())) return false; getPermissions().addBuilderPerms(member.getUUID()); return true; } @@ -233,7 +233,7 @@ public boolean removePlotMember(Builder member) { members.remove(member); if (DataProvider.PLOT.setPlotMembers(getID(), members)) { Slot slot = member.getSlotByPlotId(getID()); - if (slot != null) member.setSlot(slot, -1); + if (slot != null && !member.setSlot(slot, -1)) return false; if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 4c92cb28..a58e6fac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -131,16 +131,15 @@ protected void onException(Throwable ex) { @Override protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { super.onComplete(failed, false); + if (failed) return; - if (!failed) { - getBuilder().setSlot(getBuilder().getFreeSlot(), plot.getID()); - plot.setStatus(Status.unfinished); - ((Plot) plot).setPlotType(plotType); - ((Plot) plot).setPlotOwner(getBuilder()); - PlotUtils.Cache.clearCache(getBuilder().getUUID()); + if (!getBuilder().setSlot(getBuilder().getFreeSlot(), plot.getID())) return; + if (!plot.setStatus(Status.unfinished)) return; + if (!((Plot) plot).setPlotType(plotType)) return; + if (!plot.setPlotOwner(getBuilder())) return; - plot.getWorld().teleportPlayer(getBuilder().getPlayer()); - LangUtil.getInstance().broadcast(LangPaths.Message.Info.CREATED_NEW_PLOT, getBuilder().getName()); - } + PlotUtils.Cache.clearCache(getBuilder().getUUID()); + plot.getWorld().teleportPlayer(getBuilder().getPlayer()); + LangUtil.getInstance().broadcast(LangPaths.Message.Info.CREATED_NEW_PLOT, getBuilder().getName()); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index ceeb6ac4..647c71b0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -400,7 +400,7 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { if (plot.getPlotOwner() != null) { Cache.clearCache(plot.getPlotOwner().getUUID()); - plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1); + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1)) return; } dPlot.setPlotOwner(null); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 4192f56d..658b5fb8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -78,17 +78,17 @@ public boolean undoReview() { } // remove owner score and remove plot from slot - plot.getPlotOwner().addScore(-plot.getSharedScore()); + if (!plot.getPlotOwner().addScore(-plot.getSharedScore())) return false; if (plot.getPlotOwner().getFreeSlot() != null) { - plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID()); + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID())) return false; } // remove members score and remove plot from slot for (Builder member : plot.getPlotMembers()) { - member.addScore(-plot.getSharedScore()); + if (!member.addScore(-plot.getSharedScore())) return false; if (member.getFreeSlot() != null) { - member.setSlot(member.getFreeSlot(), plot.getID()); + if(!member.setSlot(member.getFreeSlot(), plot.getID())) return false; } } From 9af4b438a5bc03d39985e28afe355bc019f66328 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 7 Apr 2025 03:14:16 +0200 Subject: [PATCH 058/175] fix sql issues and bugs --- .../plotsystem/core/EventListener.java | 29 +++++++-------- .../core/database/DatabaseConnection.java | 35 +++++++++---------- .../database/providers/BuilderProvider.java | 29 ++++++++++----- .../providers/DifficultyProvider.java | 7 ++-- .../core/database/providers/PlotProvider.java | 7 ++-- .../providers/TutorialPlotProvider.java | 8 +++-- .../core/menus/companion/CountryMenu.java | 2 +- .../plotsystem/utils/enums/Continent.java | 12 +++---- 8 files changed, 73 insertions(+), 56 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index be8f1554..b2fa261a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -89,25 +89,26 @@ public class EventListener implements Listener { @EventHandler public void onPlayerJoinEvent(PlayerJoinEvent event) { + Player player = event.getPlayer(); + + // Add Items + Utils.updatePlayerInventorySlots(player); + // User has joined for the first time // Adding user to the database - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - Player player = event.getPlayer(); - - // Add Items - Utils.updatePlayerInventorySlots(player); - // Create builder if it does not exist in database. - boolean successful = DataProvider.BUILDER.addBuilderIfNotExists(player.getUniqueId(), player.getName()); - if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("BUILDER COULD NOT BE CREATED!!", RED)); + // Create builder if it does not exist in database. + boolean successful = DataProvider.BUILDER.addBuilderIfNotExists(player.getUniqueId(), player.getName()); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("BUILDER COULD NOT BE CREATED!!", RED)); - // Check if player has changed their name - Builder builder = Builder.byUUID(player.getUniqueId()); - if (!builder.getName().equals(player.getName())) { - successful = builder.setName(player.getName()); - if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Builder name could not be updated!", RED)); - } + // Check if player has changed their name + Builder builder = Builder.byUUID(player.getUniqueId()); + if (!builder.getName().equals(player.getName())) { + successful = builder.setName(player.getName()); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Builder name could not be updated!", RED)); + } + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { sendNotices(event.getPlayer(), builder); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index 8a69c7aa..f9622218 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -71,7 +71,7 @@ public static void InitializeDatabase() throws ClassNotFoundException, SQLExcept dataSource = new HikariDataSource(config); - createTables(); + //createTables(); } public static Connection getConnection() throws SQLException { @@ -202,28 +202,25 @@ public static List getTables() { static { tables = Arrays.asList( - // FTP Configurations - "CREATE TABLE IF NOT EXISTS `plotsystem_ftp_configurations`" + + // System Info + "CREATE TABLE IF NOT EXISTS system_info" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `address` varchar(255) NOT NULL ," + - " `port` int NOT NULL ," + - " `isSFTP` tinyint NOT NULL DEFAULT 1 ," + - " `username` varchar(255) NOT NULL ," + - " `password` varchar(255) NOT NULL ," + - " `schematics_path` varchar(255) NULL ," + - "PRIMARY KEY (`id`)" + + " system_id INT NOT NULL AUTO_INCREMENT," + + " db_version DOUBLE NOT NULL," + + " current_plot_version DOUBLE NOT NULL," + + " last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + + " description TEXT NULL," + + " PRIMARY KEY (system_id)" + ");", - // Servers - "CREATE TABLE IF NOT EXISTS `plotsystem_servers`" + + // Build Team + "CREATE TABLE IF NOT EXISTS build_team" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `ftp_configuration_id` int NULL ," + - " `name` varchar(45) NOT NULL ," + - "PRIMARY KEY (`id`)," + - "KEY `fkIdx_30` (`ftp_configuration_id`)," + - "CONSTRAINT `FK_29` FOREIGN KEY `fkIdx_30` (`ftp_configuration_id`) REFERENCES `plotsystem_ftp_configurations` (`id`)" + + " build_team_id INT NOT NULL AUTO_INCREMENT," + + " name VARCHAR(255) NOT NULL," + + " api_key VARCHAR(255) NULL UNIQUE," + + " api_create_date DATETIME NULL," + + " PRIMARY KEY (build_team_id)" + ");", // Countries diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 4c865f24..11d02993 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; @@ -33,6 +34,8 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Slot; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import javax.annotation.Nullable; import java.sql.Connection; @@ -71,6 +74,7 @@ public Builder getBuilderByName(String name) { stmt.setString(1, name); try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return null; String uuid = rs.getString(1); if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); } @@ -84,7 +88,7 @@ public boolean addBuilderIfNotExists(UUID uuid, String name) { if (builders.containsKey(uuid)) return true; String selectQuery = "SELECT 1 FROM builder WHERE uuid = ?;"; - String insertQuery = "INSERT INTO builder (uuid, name) VALUES (?, ?);"; + String insertQuery = "INSERT INTO builder (uuid, name, plot_type) VALUES (?, ?, 1);"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement selectStmt = conn.prepareStatement(selectQuery)) { selectStmt.setString(1, uuid.toString()); @@ -164,11 +168,12 @@ public boolean setPlotType(UUID uuid, int plotTypeId) { } public int getCompletedBuildsCount(UUID uuid) { - String query = "SELECT COUNT(*) AS completed_plots FROM plot p INNER JOIN builder_is_plot_member " + - "bipm ON p.plot_id = bipm.plot_id WHERE p.status = 'completed' AND bhp.uuid = ?;"; + String query = "SELECT COUNT(p.plot_id) AS completed_plots FROM plot p INNER JOIN builder_is_plot_member " + + "bipm ON p.plot_id = bipm.plot_id WHERE p.status = 'completed' AND (p.owner_uuid = ? OR bipm.uuid = ?);"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, uuid.toString()); + stmt.setString(2, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) return rs.getInt(1); @@ -256,6 +261,7 @@ public List getReviewersByBuildTeam(int buildTeamId) { String query = "SELECT uuid FROM build_team_has_reviewer WHERE build_team_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, buildTeamId); try (ResultSet rs = stmt.executeQuery()) { stmt.setInt(1, buildTeamId); @@ -279,9 +285,11 @@ public List getReviewersByBuildTeam(int buildTeamId) { * @return provides the leaderboard entry for the player, or null if not found. */ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimeframe sortBy) { + return null; // TODO: fix leaderboard query + /* try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(uuid, sortBy))) { - + stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { return new LeaderboardEntry(rs.getInt(2), rs.getInt(3), rs.getInt(4)); @@ -290,7 +298,7 @@ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimefram } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; + return null;*/ } /** @@ -300,6 +308,8 @@ public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimefram * @return provides a map of player names and their scores, or null if no data is found. */ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { + return null; // TODO: fix leaderboard query + /* try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(null, sortBy))) { @@ -311,7 +321,7 @@ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; + return null;*/ } /** @@ -330,6 +340,7 @@ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { * @return the constructed SQL query as a {@code String}. */ private static String getLeaderboardQuery(@Nullable UUID uuid, LeaderboardTimeframe sortBy) { + // TODO: fix leaderboard query String minimumDate = switch (sortBy) { case DAILY -> "(NOW() - INTERVAL 1 DAY)"; case WEEKLY -> "(NOW() - INTERVAL 1 WEEK)"; @@ -344,9 +355,9 @@ private static String getLeaderboardQuery(@Nullable UUID uuid, LeaderboardTimefr "INNER JOIN plot_review r_sub ON r_sub.plot_id = bhp_sub.plot_id " + (minimumDate != null ? "WHERE r.review_date BETWEEN " + minimumDate + " AND NOW()" : "") + ") " + "AS total_positions" : "") + - " FROM builder_has_plot bhp" + - "INNER JOIN builder b ON b.uuid = bhp.uuid" + - "INNER JOIN plot_review r ON r.plot_id = bhp.plot_id" + + " FROM builder_has_plot bhp " + + "INNER JOIN builder b ON b.uuid = bhp.uuid " + + "INNER JOIN plot_review r ON r.plot_id = bhp.plot_id " + (minimumDate != null ? "WHERE r.review_date BETWEEN " + minimumDate + " AND NOW()" : "") + diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index bc6d6211..c7f4a3df 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -70,11 +70,12 @@ public List getDifficulties() { } public Optional getDifficultyById(String id) { - return cachedDifficulties.stream().filter(d -> d.getID().equals(id)).findAny(); + return cachedDifficulties.stream().filter(d -> d.getID().equalsIgnoreCase(id)).findAny(); } public Optional getDifficultyByEnum(PlotDifficulty difficulty) { - return cachedDifficulties.stream().filter(d -> d.getID().equals(difficulty.name())).findFirst(); + if (difficulty == null) return Optional.empty(); + return cachedDifficulties.stream().filter(d -> d.getID().equalsIgnoreCase(difficulty.name())).findFirst(); } public boolean setMultiplier(String id, double multiplier) { @@ -107,7 +108,7 @@ public boolean builderMeetsRequirements(Builder builder, PlotDifficulty plotDiff Optional cachedDifficulty = getDifficultyByEnum(plotDifficulty); if (cachedDifficulty.isEmpty()) { PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " - + plotDifficulty.name() + " was found!")); + + plotDifficulty.toString() + " was found!")); return false; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index a86a8260..a9fcbbf2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.*; @@ -33,6 +34,8 @@ import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import java.sql.*; import java.time.LocalDate; @@ -136,7 +139,7 @@ public List getPlots(List cities, Status... statuses) { String cityPlaceholders = "?,".repeat(cities.size() - 1) + "?"; String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id IN (" + cityPlaceholders + ")"; - query += statuses.length > 0 ? " AND status IN (?,".repeat(statuses.length - 1) + "?);" : ";"; + query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { int index = 1; @@ -157,7 +160,7 @@ public List getPlots(List cities, Status... statuses) { public List getPlots(Builder builder, Status... statuses) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot LEFT JOIN builder_is_plot_member pm ON " + "plot.plot_id = pm.plot_id WHERE (plot.owner_uuid = ? OR pm.uuid = ?)"; - query += statuses.length > 0 ? "AND plot.status IN (?,".repeat(statuses.length - 1) + "?);" : ";"; + query += statuses.length > 0 ? "AND plot.status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { String builderUUID = builder.getUUID().toString(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index 0a752b5b..fb459b1a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.utils.Utils; import java.sql.Connection; +import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -58,8 +59,11 @@ public Optional getByTutorialId(int tutorialId, String playerUUID) try (ResultSet rs = stmt.executeQuery()) { if (rs.next()) { int plotId = freeTutorialPlotIds.isEmpty() ? 0 : freeTutorialPlotIds.poll(); - TutorialPlot newTutorialPlot = new TutorialPlot(plotId, tutorialId, playerUUID, rs.getInt(1), - rs.getBoolean(2), rs.getDate(3).toLocalDate()); + int stageId = rs.getInt(1); + boolean isComplete = rs.getBoolean(2); + Date lastStageCompleteDate = rs.getDate(3); + TutorialPlot newTutorialPlot = new TutorialPlot(plotId, tutorialId, playerUUID, stageId, + isComplete, lastStageCompleteDate != null ? lastStageCompleteDate.toLocalDate() : null); tutorialPlots.put(newTutorialPlot, plotId); return Optional.of(newTutorialPlot); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index 38fd17bc..c34e1186 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -59,7 +59,7 @@ public class CountryMenu extends AbstractMenu { private List countryProjects; private final Continent selectedContinent; - private PlotDifficulty selectedPlotDifficulty = null; + private PlotDifficulty selectedPlotDifficulty = PlotDifficulty.EASY; CountryMenu(Player player, @NotNull Continent continent) { super(6, LangUtil.getInstance().get(player, continent.langPath) + " → " + LangUtil.getInstance().get(player, LangPaths.MenuTitle.COMPANION_SELECT_COUNTRY), player); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java index 90f3be10..18597f15 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java @@ -42,12 +42,12 @@ import static net.kyori.adventure.text.Component.*; public enum Continent { - EUROPE("europe", LangPaths.Continent.EUROPE), - ASIA("asia", LangPaths.Continent.ASIA), - AFRICA("africa", LangPaths.Continent.AFRICA), - OCEANIA("oceania", LangPaths.Continent.OCEANIA), - SOUTH_AMERICA("south america", LangPaths.Continent.SOUTH_AMERICA), - NORTH_AMERICA("north america", LangPaths.Continent.NORTH_AMERICA); + EUROPE("EU", LangPaths.Continent.EUROPE), + ASIA("AS", LangPaths.Continent.ASIA), + AFRICA("AF", LangPaths.Continent.AFRICA), + OCEANIA("OC", LangPaths.Continent.OCEANIA), + SOUTH_AMERICA("SA", LangPaths.Continent.SOUTH_AMERICA), + NORTH_AMERICA("NA", LangPaths.Continent.NORTH_AMERICA); public final String databaseEnum; public final String langPath; From dd1e631f9d5f14e25ad0a56931a54d0688fc96a0 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 7 Apr 2025 03:23:25 +0200 Subject: [PATCH 059/175] =?UTF-8?q?more=20bug=20squashing=20=F0=9F=AA=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/database/providers/PlotProvider.java | 20 ++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index a9fcbbf2..5dd5a636 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -183,14 +183,28 @@ private Plot extractPlot(ResultSet rs) throws SQLException { int plotId = rs.getInt("plot_id"); CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString("city_project_id")).orElseThrow(); PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString("difficulty_id")).orElseThrow().getDifficulty(); - UUID ownerUUID = UUID.fromString(rs.getString("owner_uuid")); + + String ownerUUIDString = rs.getString("owner_uuid"); + UUID ownerUUID = ownerUUIDString != null ? UUID.fromString(ownerUUIDString) : null; + Status status = Status.valueOf(rs.getString("status")); String outlineBounds = rs.getString("outline_bounds"); - LocalDate lastActivity = rs.getDate("last_activity_date").toLocalDate(); + Date lastActivity = rs.getDate("last_activity_date"); + double version = rs.getDouble("plot_version"); PlotType type = PlotType.byId(rs.getInt("plot_type")); - return new Plot(plotId, cityProject, difficulty, ownerUUID, status, outlineBounds, lastActivity, version, type, getPlotMembers(plotId)); + return new Plot( + plotId, + cityProject, + difficulty, + ownerUUID, + status, + outlineBounds, + lastActivity != null ? lastActivity.toLocalDate() : null, + version, + type, + getPlotMembers(plotId)); } public List getPlotMembers(int plotId) { From a438ad513bb0fcefc97f3409c722f246d4930e3f Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 7 Apr 2025 13:18:17 +0200 Subject: [PATCH 060/175] =?UTF-8?q?=F0=9F=94=A7=20=E2=9C=A8=20Implement=20?= =?UTF-8?q?CIM=20mode=20disable=20config?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #156. --- .../plotsystem/core/menus/PlotTypeMenu.java | 39 ++++++++++++------- .../plotsystem/core/system/Builder.java | 13 +++++-- .../plotsystem/utils/io/ConfigPaths.java | 1 + src/main/resources/config.yml | 3 ++ 4 files changed, 37 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index 250ba603..56389dcc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -27,9 +27,11 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.CustomHeads; @@ -79,15 +81,19 @@ protected void setMenuItemsAsync() { .setEnchanted(builder.getPlotType().getId() == PlotType.LOCAL_INSPIRATION_MODE.getId()) .build()); - getMenu().getSlot(15).setItem( - new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.CITY_INSPIRATION_MODE_BUTTON.getId())) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_CITY_INSPIRATION_MODE), GOLD, BOLD) - .append(text(" [", DARK_GRAY).append(text("BETA", RED).append(text("]", DARK_GRAY))))) // temporary BETA tag - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_CITY_INSPIRATION_MODE), true) - .build()) - .setEnchanted(builder.getPlotType().getId() == PlotType.CITY_INSPIRATION_MODE.getId()) - .build()); + boolean inspirationModeDisabled = PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DISABLE_CITY_INSPIRATION_MODE); // TODO remove or enhance as soon CIM is working again + if (!inspirationModeDisabled) { + getMenu().getSlot(15).setItem( + new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.CITY_INSPIRATION_MODE_BUTTON.getId())) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_CITY_INSPIRATION_MODE), GOLD, BOLD) + .append(text(" [", DARK_GRAY).append(text("BETA", RED).append(text("]", DARK_GRAY))))) // temporary BETA tag + .setLore(new LoreBuilder() + .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_CITY_INSPIRATION_MODE), true) + .build()) + .setEnchanted(builder.getPlotType().getId() == PlotType.CITY_INSPIRATION_MODE.getId()) + .build()); + } + // Set selected glass pane int selectedPlotTypeSlot = 13; @@ -119,12 +125,15 @@ protected void setItemClickEventsAsync() { reloadMenuAsync(); })); - getMenu().getSlot(15).setClickHandler(((clickPlayer, clickInformation) -> { - boolean successful = builder.setPlotType(PlotType.CITY_INSPIRATION_MODE); - if (!successful) return; - getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); - reloadMenuAsync(); - })); + boolean inspirationModeDisabled = PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DISABLE_CITY_INSPIRATION_MODE); // TODO improve or remove when CIM ist working again + if (!inspirationModeDisabled) { + getMenu().getSlot(15).setClickHandler(((clickPlayer, clickInformation) -> { + boolean successful = builder.setPlotType(PlotType.CITY_INSPIRATION_MODE); + if (!successful) return; + getMenuPlayer().playSound(getMenuPlayer().getLocation(), Utils.SoundUtils.DONE_SOUND, 1f, 1f); + reloadMenuAsync(); + })); + } // Set click event for back item getMenu().getSlot(22).setClickHandler((clickPlayer, clickInformation) -> new SettingsMenu(clickPlayer)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index f57968d9..ed2cc509 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -24,10 +24,12 @@ package com.alpsbte.plotsystem.core.system; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.Slot; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import org.bukkit.Bukkit; import org.bukkit.entity.Player; @@ -42,14 +44,17 @@ public class Builder { private int thirdSlot; private int plotType; - public Builder(UUID UUID, String name, int score, int first_slot, int second_slot, int third_slot, int plotType) { + public Builder(UUID UUID, String name, int score, int firstSlot, int secondSlot, int thirdSlot, int plotType) { this.uuid = UUID; this.name = name; this.score = score; - this.firstSlot = first_slot; - this.secondSlot = second_slot; - this.thirdSlot = third_slot; + this.firstSlot = firstSlot; + this.secondSlot = secondSlot; + this.thirdSlot = thirdSlot; this.plotType = plotType; + + boolean inspirationModeDisabled = PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DISABLE_CITY_INSPIRATION_MODE); // TODO remove or improve when CIM is working again + if (inspirationModeDisabled && plotType == 2) this.plotType = 1; } public java.util.UUID getUUID() { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java index f7a14fd9..6f942d7c 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java @@ -36,6 +36,7 @@ public abstract class ConfigPaths { public static final String REJECTED_INACTIVITY_INTERVAL = "rejected-inactivity-interval"; public static final String ENABLE_GROUP_SUPPORT = "enable-group-support"; public static final String UNFINISHED_REMINDER_INTERVAL = "unfinished-reminder-interval"; + public static final String DISABLE_CITY_INSPIRATION_MODE = "disable-city-inspiration-mode"; // Database private static final String DATABASE = "database."; diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 4ead134c..13d9a295 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -43,6 +43,9 @@ enable-group-support: true # Will be repeated every x minutes; It uses the unfinished-plots string, set it to -1 to disable unfinished-reminder-interval: 20 +# Disable the City Inspiration Mode (Beta) CIM completely for new plots (Temporary Config Setting) +disable-city-inspiration-mode: false + # ----------------------------------------------------- # | Supported databases: MariaDB & MySQL # ----------------------------------------------------- From 97a108ee7ff2bb0df5159fb9c9f75faee33528b6 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 7 Apr 2025 16:17:34 +0200 Subject: [PATCH 061/175] update config and squash more bugs! --- .../admin/setup/CMD_Setup_BuildTeam.java | 1 - .../database/providers/BuilderProvider.java | 7 ++--- .../core/database/providers/PlotProvider.java | 16 ++++------ .../core/menus/PlayerPlotsMenu.java | 31 +++++++------------ .../plotsystem/utils/io/ConfigUtil.java | 2 +- src/main/resources/config.yml | 2 +- 6 files changed, 23 insertions(+), 36 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 84507b52..5a7024f1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -30,7 +30,6 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.command.CommandSender; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 11d02993..62e3b575 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; @@ -34,8 +33,6 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Slot; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; import javax.annotation.Nullable; import java.sql.Connection; @@ -136,7 +133,7 @@ public boolean addScore(UUID uuid, int score) { } public boolean setSlot(UUID uuid, int plotID, Slot slot) { - String query = "UPDATE builder b SET " + slot.name().toLowerCase() + " = " + + String query = "UPDATE builder b SET " + slot.name().toLowerCase() + "_slot = " + (plotID > 0 ? "?" : "DEFAULT(first_slot)") + " WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -191,6 +188,7 @@ public Slot getFreeSlot(UUID uuid) { stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return null; for (int i = 1; i <= 3; i++) { if (rs.getString(i) == null) return Slot.values()[i - 1]; } @@ -208,6 +206,7 @@ public Slot getSlot(UUID uuid, int plotId) { stmt.setString(1, uuid.toString()); try (ResultSet rs = stmt.executeQuery()) { + if (!rs.next()) return null; if (rs.getInt(1) == plotId) return Slot.FIRST; if (rs.getInt(2) == plotId) return Slot.SECOND; if (rs.getInt(3) == plotId) return Slot.THIRD; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 5dd5a636..f73c3065 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -24,24 +24,19 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.*; import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.format.NamedTextColor; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; -import java.util.Optional; import java.util.UUID; public class PlotProvider { @@ -59,10 +54,12 @@ public Plot getPlotById(int plotId) { if (!rs.next()) return null; CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString(1)).orElseThrow(); PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString(2)).orElseThrow().getDifficulty(); - UUID ownerUUID = UUID.fromString(rs.getString(3)); + String ownerUUIDString = rs.getString(3); + UUID ownerUUID = ownerUUIDString != null ? UUID.fromString(ownerUUIDString) : null; Status status = Status.valueOf(rs.getString(4)); String outlineBounds = rs.getString(5); - LocalDate lastActivity = rs.getDate(6).toLocalDate(); + Date lastActivityDate = rs.getDate(6); + LocalDate lastActivity = lastActivityDate != null ? lastActivityDate.toLocalDate() : null; double version = rs.getDouble(7); PlotType type = PlotType.byId(rs.getInt(8)); @@ -234,11 +231,10 @@ public byte[] getCompletedSchematic(int plotId) { } private byte[] getSchematic(int plotId, String name) { - String query = "SELECT ? FROM plot WHERE plot_id = ?;"; + String query = "SELECT " + name + " FROM plot WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, name); - stmt.setInt(2, plotId); + stmt.setInt(1, plotId); try (ResultSet rs = stmt.executeQuery()) { if (!rs.next()) return null; return rs.getBytes(1); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 1b1f56d6..a6df3f91 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -26,7 +26,6 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.LoreBuilder; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -43,7 +42,6 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import java.sql.SQLException; import java.util.List; import java.util.Optional; @@ -94,22 +92,17 @@ protected void setMenuItemsAsync() { plotDisplayCount = Math.min(plots.size(), 36); for (int i = 0; i < plotDisplayCount; i++) { Plot plot = plots.get(i); - try { - ItemStack item = switch (plot.getStatus()) { - case unfinished -> BaseItems.PLOT_UNFINISHED.getItem(); - case unreviewed -> BaseItems.PLOT_UNREVIEWED.getItem(); - default -> BaseItems.PLOT_COMPLETED.getItem(); - }; - - getMenu().getSlot(9 + i) - .setItem(new ItemBuilder(item) - .setName(text(plot.getCityProject().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) - .setLore(getLore(plot, getMenuPlayer()).build()) - .build()); - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - getMenu().getSlot(9 + i).setItem(MenuItems.errorItem(getMenuPlayer())); - } + ItemStack item = switch (plot.getStatus()) { + case unfinished -> BaseItems.PLOT_UNFINISHED.getItem(); + case unreviewed -> BaseItems.PLOT_UNREVIEWED.getItem(); + default -> BaseItems.PLOT_COMPLETED.getItem(); + }; + + getMenu().getSlot(9 + i) + .setItem(new ItemBuilder(item) + .setName(text(plot.getCityProject().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) + .setLore(getLore(plot, getMenuPlayer()).build()) + .build()); } } @@ -145,7 +138,7 @@ protected Mask getMask() { * @param p player instance for language system * @return description lore for plot item */ - private LoreBuilder getLore(Plot plot, Player p) throws SQLException { + private LoreBuilder getLore(Plot plot, Player p) { LoreBuilder builder = new LoreBuilder(); if (plot.getPlotMembers().isEmpty()) { // Plot is single player plot diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java index d1830a2e..f3042f6b 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java @@ -44,7 +44,7 @@ private ConfigUtil() {} public static void init() throws ConfigNotImplementedException { if (configUtilInstance == null) { configUtilInstance = new ConfigurationUtil(new ConfigurationUtil.ConfigFile[]{ - new ConfigurationUtil.ConfigFile(Paths.get("config.yml"), 3.0, true), + new ConfigurationUtil.ConfigFile(Paths.get("config.yml"), 4.0, true), new ConfigurationUtil.ConfigFile(Paths.get("commands.yml"), 1.1, false), new ConfigurationUtil.ConfigFile(Paths.get("items.yml"), 1.2, false) }); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 13d9a295..6ae401f6 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -111,4 +111,4 @@ tutorials: # NOTE: Do not change -config-version: 3.0 \ No newline at end of file +config-version: 4.0 \ No newline at end of file From 8236860d7f6a00df5f4a9f6b74f49a05bcca4929 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 7 Apr 2025 16:57:03 +0200 Subject: [PATCH 062/175] fix merge issues --- .../menus/review/ReviewPlotTogglesMenu.java | 18 ++++++++++-------- .../core/system/plot/utils/PlotUtils.java | 2 +- .../core/system/plot/world/CityPlotWorld.java | 3 ++- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 9e1a23c0..2356aabe 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -112,15 +112,17 @@ else if (!criteria.isOptional()) { Component reviewerConfirmationMessage; if (!isRejected) { getMenuPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); - try { - if (!PlotUtils.savePlotAsSchematic(plot)) { - getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); - return; + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + try { + if (!PlotUtils.savePlotAsSchematic(plot)) { + getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); + return; + } + } catch (IOException | WorldEditException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); } - } catch (IOException | WorldEditException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); - } + }); plot.setStatus(Status.completed); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index b9beb555..842364ac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -225,10 +225,10 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException // Copy and write finished plot clipboard to schematic try (Clipboard cb = new BlockArrayClipboard(region)) { cb.setOrigin(BlockVector3.at(plotCenter.x(), cuboidRegion.getMinimumY(), (double) plotCenter.z())); - } ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(Objects.requireNonNull(region.getWorld()), region, cb, region.getMinimumPoint()); Operations.complete(forwardExtentCopy); + } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index 93f39fbc..da342670 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -101,7 +101,7 @@ public int getWorldHeight() throws IOException { clipboard = reader.read(); } if (clipboard != null) { - int plotHeight = clipboard != null ? clipboard.getMinimumPoint().y() : MIN_WORLD_HEIGHT; + int plotHeight = clipboard.getMinimumPoint().y(); /// Minimum building height for a plot (this should be configurable depending on minecraft build limit) /// This is in the case that a plot is created at y level 300 where the max build limit is 318, @@ -118,6 +118,7 @@ public int getWorldHeight() throws IOException { return 0; // throw new IOException("Plot height is out of range."); return plotHeight; } + throw new IOException("A Plot's Outline schematic fails to load, cannot get clipboard."); } /** From 7639306ba7455ef3506f21add5883a9ab47ede3a Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Tue, 8 Apr 2025 13:31:17 +0200 Subject: [PATCH 063/175] merge nested ifs and split sendNotices() method --- .../plotsystem/core/EventListener.java | 36 ++++++++++--------- .../core/system/review/PlotReview.java | 12 +++---- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index b2fa261a..5c629e3a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -108,9 +108,7 @@ public void onPlayerJoinEvent(PlayerJoinEvent event) { if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Builder name could not be updated!", RED)); } - Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { - sendNotices(event.getPlayer(), builder); - }); + Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> sendNotices(event.getPlayer(), builder)); } @EventHandler @@ -268,15 +266,32 @@ private void handleIronTrapdoorClick(@NotNull PlayerInteractEvent event) { } private void sendNotices(@NotNull Player player, Builder builder) { + sendAdminNotices(player); + sendReviewNotices(player, builder); + + // Start or notify the player if he has not completed the beginner tutorial yet (only if required) + if (TutorialPlot.isRequiredAndInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { + if (!player.hasPlayedBefore()) { + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), + () -> player.performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); + } else { + AbstractPlotTutorial.sendTutorialRequiredMessage(player, TutorialCategory.BEGINNER.getId()); + player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); + } + } + } + + private void sendAdminNotices(@NotNull Player player) { // Inform player about update if (player.hasPermission("plotsystem.admin") && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.CHECK_FOR_UPDATES) && PlotSystem.UpdateChecker.updateAvailable()) { player.sendMessage(Utils.ChatUtils.getInfoFormat("There is a new update for the Plot-System available. Check your console for more information!")); player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); } + } + private void sendReviewNotices(@NotNull Player player, Builder builder) { // Informing player about new feedback List notifications = DataProvider.REVIEW.getReviewNotifications(player.getUniqueId()); - if (!notifications.isEmpty()) { PlotUtils.ChatFormatting.sendFeedbackMessage(notifications, player); String subtitleText = " Plot" + (notifications.size() == 1 ? " " : "s ") + (notifications.size() == 1 ? "has" : "have") + " been reviewed!"; // TODO: translate @@ -286,7 +301,6 @@ private void sendNotices(@NotNull Player player, Builder builder) { Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofSeconds(1))) ); } - PlotUtils.informPlayerAboutUnfinishedPlots(player, builder); PlotUtils.startUnfinishedPlotReminderTimer(player); @@ -299,17 +313,5 @@ private void sendNotices(@NotNull Player player, Builder builder) { PlotUtils.ChatFormatting.sendUnreviewedPlotsReminderMessage(unreviewedPlots, player); } } - - - // Start or notify the player if he has not completed the beginner tutorial yet (only if required) - if (TutorialPlot.isRequiredAndInProgress(TutorialCategory.BEGINNER.getId(), player.getUniqueId())) { - if (!player.hasPlayedBefore()) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), - () -> player.performCommand("tutorial " + TutorialCategory.BEGINNER.getId())); - } else { - AbstractPlotTutorial.sendTutorialRequiredMessage(player, TutorialCategory.BEGINNER.getId()); - player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); - } - } } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 658b5fb8..844b6d89 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -79,17 +79,15 @@ public boolean undoReview() { // remove owner score and remove plot from slot if (!plot.getPlotOwner().addScore(-plot.getSharedScore())) return false; - if (plot.getPlotOwner().getFreeSlot() != null) { - if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID())) return false; - } + if (plot.getPlotOwner().getFreeSlot() != null + && !plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID())) + return false; // remove members score and remove plot from slot for (Builder member : plot.getPlotMembers()) { if (!member.addScore(-plot.getSharedScore())) return false; - - if (member.getFreeSlot() != null) { - if(!member.setSlot(member.getFreeSlot(), plot.getID())) return false; - } + if (member.getFreeSlot() != null && !member.setSlot(member.getFreeSlot(), plot.getID())) + return false; } plot.setStatus(Status.unreviewed); From daff115767081eb48c4aff0ef974aa8101836a27 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Fri, 11 Apr 2025 23:06:28 +0200 Subject: [PATCH 064/175] remove unnecessary SQLExceptions --- .../system/plot/generator/AbstractPlotGenerator.java | 11 ++--------- .../system/plot/generator/DefaultPlotGenerator.java | 5 ++--- .../system/plot/generator/TutorialPlotGenerator.java | 3 +-- .../core/system/plot/world/OnePlotWorld.java | 3 +-- 4 files changed, 6 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index fa945698..6f1dc143 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -74,7 +74,6 @@ import java.io.ByteArrayInputStream; import java.io.IOException; -import java.sql.SQLException; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -134,12 +133,7 @@ private AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder build } catch (Exception ex) { exception = ex; } - - try { - this.onComplete(exception != null, false); - } catch (SQLException ex) { - exception = ex; - } + this.onComplete(exception != null, false); if (exception != null) { PlotUtils.Actions.abandonPlot(plot); @@ -252,9 +246,8 @@ protected List getBlockedCommands(FileConfiguration config) { * * @param failed - true if generation has failed * @param unloadWorld - try to unload world after generation - * @throws SQLException - caused by a database exception */ - protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { + protected void onComplete(boolean failed, boolean unloadWorld) { // Unload plot world if it is not needed anymore if (unloadWorld) world.unloadWorld(false); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index a58e6fac..6ada921c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -46,7 +46,6 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; -import java.sql.SQLException; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; @@ -116,7 +115,7 @@ protected boolean init() { protected void createPlotProtection() {} @Override - protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { + protected void onComplete(boolean failed, boolean unloadWorld) { super.onComplete(true, true); } @@ -129,7 +128,7 @@ protected void onException(Throwable ex) { } @Override - protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { + protected void onComplete(boolean failed, boolean unloadWorld) { super.onComplete(failed, false); if (failed) return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java index 9f3504cb..24a1c56d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java @@ -40,7 +40,6 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; -import java.sql.SQLException; import java.util.Objects; import static net.kyori.adventure.text.Component.text; @@ -79,7 +78,7 @@ protected void setBuildRegionPermissions(ProtectedRegion region) { } @Override - protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { + protected void onComplete(boolean failed, boolean unloadWorld) { super.onComplete(failed, false); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index c79fabf9..14bd20bd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -41,7 +41,6 @@ import org.jetbrains.annotations.NotNull; import java.io.IOException; -import java.sql.SQLException; import static net.kyori.adventure.text.Component.text; @@ -80,7 +79,7 @@ protected boolean init() { } @Override - protected void onComplete(boolean failed, boolean unloadWorld) throws SQLException { + protected void onComplete(boolean failed, boolean unloadWorld) { getPlot().getPermissions().clearAllPerms(); super.onComplete(true, false); } From bdc629b7a9445854a58735f33874c8218e0ca5e8 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Fri, 11 Apr 2025 23:08:23 +0200 Subject: [PATCH 065/175] more fixes for tutorial plots --- .../core/system/plot/TutorialPlot.java | 6 ++-- .../plot/generator/AbstractPlotGenerator.java | 4 +-- .../system/tutorial/AbstractPlotTutorial.java | 32 ++++++++++++------- .../system/tutorial/AbstractTutorial.java | 1 + .../core/system/tutorial/PlotTutorial.java | 3 +- .../stage/tasks/PlotSchematicPasteTask.java | 11 ++++++- 6 files changed, 39 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index fec20940..2e457932 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -121,8 +121,8 @@ public Builder getPlotOwner() { @Override public boolean setPlotOwner(@Nullable Builder plotOwner) { - // TODO: Implement - return false; + // Not needed for tutorial plots, as the value is initialized during database entry creation. + return true; } @Override @@ -176,7 +176,7 @@ public byte[] getInitialSchematicBytes() { schematic = Paths.get(PlotUtils.getDefaultSchematicPath(), "tutorials", fileName).toFile(); try { if (!schematic.exists()) FileUtils.copyInputStreamToFile(Objects.requireNonNull(PlotSystem.getPlugin() - .getResource("tutorial/schematics/" + fileName + ".schem.gz")), schematic); + .getResource("tutorial/schematics/" + fileName + ".gz")), schematic); return Files.readAllBytes(schematic.toPath()); } catch (IOException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while copying the schematic file!"), ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 6f1dc143..5b1949b5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -154,7 +154,7 @@ private AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder build /** * Generates plot schematic and outlines */ - protected void generateOutlines() throws IOException, WorldEditException { + protected void generateOutlines() throws IOException { Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); if (plotVersion >= 3 && plotType.hasEnvironment()) { pasteSchematic(airMask, plot.getInitialSchematicBytes(), world, false); @@ -289,7 +289,7 @@ public Builder getBuilder() { * @param world - world to paste in * @param clearArea - clears the plot area with air before pasting */ - public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, PlotWorld world, boolean clearArea) throws IOException, WorldEditException { + public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, PlotWorld world, boolean clearArea) throws IOException { // load world if (!world.loadWorld()) return; World weWorld = new BukkitWorld(world.getBukkitWorld()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index fade50fe..4e1dad5d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -39,7 +39,6 @@ import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.sk89q.worldedit.WorldEditException; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.HoverEvent; @@ -69,8 +68,11 @@ protected AbstractPlotTutorial(Player player, int tutorialId, int stageId) { CompletableFuture.runAsync(() -> { String playerUUID = player.getUniqueId().toString(); Optional plot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID); - if (plot.isEmpty() && DataProvider.TUTORIAL_PLOT.add(tutorialId, playerUUID)) + if (plot.isEmpty() && DataProvider.TUTORIAL_PLOT.add(tutorialId, playerUUID)) { tutorialPlot = DataProvider.TUTORIAL_PLOT.getByTutorialId(tutorialId, playerUUID).orElse(null); + } else { + tutorialPlot = plot.orElse(null); + } // Check if tutorial plot is null if (tutorialPlot == null) { @@ -108,14 +110,10 @@ public void setStage(int stageId) { } @Override - public void onPlotSchematicPaste(UUID playerUUID, int schematicId) { + public void onPlotSchematicPaste(UUID playerUUID, int schematicId) throws IOException { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; - try { - if (plotGenerator != null && tutorialPlot.getWorld().isWorldGenerated() && tutorialPlot.getWorld().isWorldLoaded()) { - plotGenerator.generateOutlines(schematicId); - } - } catch (IOException | WorldEditException ex) { - onException(ex); + if (plotGenerator != null && tutorialPlot.getWorld().isWorldGenerated() && tutorialPlot.getWorld().isWorldLoaded()) { + plotGenerator.generateOutlines(schematicId); } } @@ -137,7 +135,14 @@ protected AbstractStage getStage() throws NoSuchMethodException, InvocationTarge protected void prepareStage(PrepareStageAction action) { Bukkit.getScheduler().runTaskLater(PlotSystem.getPlugin(), () -> { // paste initial schematic outlines of stage - if (isPasteSchematic) onPlotSchematicPaste(getPlayerUUID(), ((AbstractPlotStage) currentStage).getInitSchematicId()); + if (isPasteSchematic) { + try { + onPlotSchematicPaste(getPlayerUUID(), ((AbstractPlotStage) currentStage).getInitSchematicId()); + } catch (IOException ex) { + onException(ex); + return; + } + } isPasteSchematic = false; // Send a new stage unlocked message to the player @@ -163,7 +168,12 @@ public void onSwitchWorld(UUID playerUUID, int tutorialWorldIndex) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; if (tutorialWorldIndex == 1 && (plotGenerator == null || !plotGenerator.getPlot().getWorld().isWorldGenerated())) { plotGenerator = new TutorialPlotGenerator(tutorialPlot, Builder.byUUID(playerUUID)); - onPlotSchematicPaste(playerUUID, ((AbstractPlotStage) currentStage).getInitSchematicId()); + try { + onPlotSchematicPaste(playerUUID, ((AbstractPlotStage) currentStage).getInitSchematicId()); + } catch (IOException ex) { + onException(ex); + return; + } } super.onSwitchWorld(playerUUID, tutorialWorldIndex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java index 74a33cb0..2c006b96 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java @@ -246,6 +246,7 @@ public void onSwitchWorld(UUID playerUUID, int tutorialWorldIndex) { currentWorldIndex = tutorialWorldIndex; TutorialWorld world = worlds.get(tutorialWorldIndex); + if (world == null) return; player.teleport(world.getPlayerSpawnLocation()); if (npc.getNpc() != null) { npc.move(player, world.getNpcSpawnLocation()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java index f6684a56..0dfce561 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.core.system.tutorial; +import java.io.IOException; import java.util.UUID; public interface PlotTutorial extends Tutorial { @@ -34,7 +35,7 @@ public interface PlotTutorial extends Tutorial { * @param playerUUID uuid of the player * @param schematicId The schematic id */ - void onPlotSchematicPaste(UUID playerUUID, int schematicId); + void onPlotSchematicPaste(UUID playerUUID, int schematicId) throws IOException; /** * This method is called when the building and WorldEdit permissions on the plot need to be changed. diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java index 496104c3..118f5983 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java @@ -28,6 +28,8 @@ import com.alpsbte.plotsystem.core.system.tutorial.PlotTutorial; import org.bukkit.entity.Player; +import java.io.IOException; + public class PlotSchematicPasteTask extends AbstractTask { private final int schematicId; @@ -39,7 +41,14 @@ public PlotSchematicPasteTask(Player player, int schematicId) { @Override public void performTask() { PlotTutorial tutorial = (PlotTutorial) AbstractTutorial.getActiveTutorial(player.getUniqueId()); - if (tutorial != null) tutorial.onPlotSchematicPaste(player.getUniqueId(), schematicId); + if (tutorial != null) { + try { + tutorial.onPlotSchematicPaste(player.getUniqueId(), schematicId); + } catch (IOException ex) { + tutorial.onException(ex); + return; + } + } setTaskDone(); } } From 5a0af85c4829e2d342fd750b78066b1bf7763d3d Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 13 Apr 2025 17:04:14 +0200 Subject: [PATCH 066/175] implement Menu logic of ReviewPlotTogglesMenu and ReviewPlotMenu --- .../core/menus/review/ReviewPlotMenu.java | 126 ++++++++---------- .../menus/review/ReviewPlotTogglesMenu.java | 117 +++++++++++++--- .../plotsystem/utils/io/LangPaths.java | 1 + .../plotsystem/utils/items/BaseItems.java | 11 +- .../plotsystem/utils/items/MenuItems.java | 8 +- src/main/resources/items.yml | 16 ++- src/main/resources/lang/de_DE.yml | 1 + src/main/resources/lang/en_GB.yml | 1 + 8 files changed, 190 insertions(+), 91 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index 0caabeba..56b7f2d0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -42,6 +42,7 @@ import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.ipvp.canvas.mask.BinaryMask; @@ -61,73 +62,84 @@ public class ReviewPlotMenu extends AbstractMenu { boolean sentWarning = false; - public ReviewPlotMenu(Player player, Plot plot) { + public ReviewPlotMenu(Player player, Plot plot, ReviewRating rating) { super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); this.plot = plot; - this.rating = new ReviewRating(0, 0, List.of()); + this.rating = rating; + } + + public ReviewPlotMenu(Player player, Plot plot) { + this(player, plot, new ReviewRating(0, 0, List.of())); } @Override protected void setPreviewItems() { - for (int col = 0; col < 6; col++) { - for (int row = 0; row < 2; row++) { - ItemStack item; - switch (col) { - case 0 -> { - item = getZeroPointItem(); - ItemMeta itemMeta = item.getItemMeta(); - Objects.requireNonNull(itemMeta).addEnchant(Enchantment.POWER, 1, true); - item.setItemMeta(itemMeta); - } - case 1 -> item = getOnePointItem(); - case 2 -> item = getTwoPointItem(); - case 3 -> item = getThreePointItem(); - case 4 -> item = getFourPointItem(); - default -> item = getFivePointItem(); - } - getMenu().getSlot(29 + col + (9 * row)).setItem(item); - } - } - getMenu().getSlot(4).setItem(MenuItems.loadingItem(Material.MAP, getMenuPlayer())); - getMenu().getSlot(28).setItem(getAccuracyItem()); - getMenu().getSlot(37).setItem(getBlockPaletteItem()); - - getMenu().getSlot(48).setItem(getSubmitItem()); - getMenu().getSlot(50).setItem(getCancelItem()); + getMenu().getSlot(19).setItem(getAccuracyItem()); + getMenu().getSlot(28).setItem(getBlockPaletteItem()); super.setPreviewItems(); } @Override protected void setMenuItemsAsync() { - // Set back item - getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); - // Set plot information item getMenu().getSlot(4).setItem(ReviewItems.getPlotInfoItem(getMenuPlayer(), plot)); // Set review information item getMenu().getSlot(7).setItem(ReviewItems.getReviewInfoItem(getMenuPlayer())); + + // Set back item + getMenu().getSlot(48).setItem(MenuItems.backMenuItem(getMenuPlayer())); + + // Set next item + getMenu().getSlot(50).setItem(MenuItems.continueMenuItem(getMenuPlayer())); + + // Set point items + for (int row = 0; row < 2; row++) { + int selectedPoints = row == 0 ? rating.getAccuracyPoints() : rating.getBlockPalettePoints(); + for (int col = 0; col < 6; col++) { + ItemStack item; + switch (col) { + case 0 -> item = getZeroPointItem(); + case 1 -> item = getOnePointItem(); + case 2 -> item = getTwoPointItem(); + case 3 -> item = getThreePointItem(); + case 4 -> item = getFourPointItem(); + default -> item = getFivePointItem(); + } + + if (selectedPoints == col) { + ItemMeta itemMeta = item.getItemMeta(); + Objects.requireNonNull(itemMeta).addEnchant(Enchantment.POWER, 1, true); + item.setItemMeta(itemMeta); + item.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } else { + item.removeEnchantment(Enchantment.POWER); + } + + getMenu().getSlot(20 + col + (9 * row)).setItem(item); + } + } } @Override protected void setItemClickEventsAsync() { // Set click event for back item - getMenu().getSlot(1).setClickHandler((clickPlayer, clickInformation) - -> new ReviewMenu(getMenuPlayer())); - - // Set click event for close item - getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) - -> clickPlayer.closeInventory()); + getMenu().getSlot(48).setClickHandler((clickPlayer, clickInformation) -> { + clickPlayer.closeInventory(); + new ReviewMenu(clickPlayer); + }); // Set click event for plot info item - getMenu().getSlot(4).setClickHandler((clickPlayer, clickInformation) - -> new PlotActionsMenu(clickPlayer, plot)); + getMenu().getSlot(4).setClickHandler((clickPlayer, clickInformation) -> { + clickPlayer.closeInventory(); + new PlotActionsMenu(clickPlayer, plot); + }); /* Set click event for submit item */ - getMenu().getSlot(48).setClickHandler((clickPlayer, clickInformation) + getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) -> Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; @@ -159,20 +171,20 @@ protected void setItemClickEventsAsync() { // Set click event for point selection items for (int col = 0; col < 6; col++) { for (int row = 0; row < 2; row++) { - int slot = 29 + col + (9 * row); + int slot = 20 + col + (9 * row); int captureRow = row; // need to assign separate variables so that they can be captured by the lambda int points = col; ItemMeta meta = getMenu().getSlot(slot).getItem(getMenuPlayer()).getItemMeta(); getMenu().getSlot(slot).setClickHandler((clickPlayer, clickInformation) -> { for (int j = 0; j < 6; j++) { - ItemStack previousItem = getMenu().getSlot(29 + j + (9 * captureRow)).getItem(clickPlayer); + ItemStack previousItem = getMenu().getSlot(20 + j + (9 * captureRow)).getItem(clickPlayer); if (previousItem == null || !previousItem.getItemMeta().hasEnchant(Enchantment.POWER)) continue; ItemMeta metaPrevious = previousItem.getItemMeta(); assert metaPrevious != null; metaPrevious.removeEnchant(Enchantment.POWER); previousItem.setItemMeta(metaPrevious); - getMenu().getSlot(29 + j + (9 * captureRow)).setItem(previousItem); + getMenu().getSlot(20 + j + (9 * captureRow)).setItem(previousItem); } assert meta != null; @@ -195,11 +207,11 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) - .pattern("101101101") - .pattern("100000001") - .pattern("100000001") - .pattern("100000001") - .pattern("100000001") + .pattern("111101111") + .pattern("000000000") + .pattern("000000000") + .pattern("000000000") + .pattern("000000000") .pattern("111010111") .build(); } @@ -227,26 +239,6 @@ private ItemStack getBlockPaletteItem() { .build(); } - // --- Button Items --- - private ItemStack getSubmitItem() { - return new ItemBuilder(BaseItems.REVIEW_SUBMIT.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT)) - .color(GREEN) - .decoration(BOLD, true)) - .setLore(new LoreBuilder() - .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_REVIEW), true) - .build()) - .build(); - } - - private ItemStack getCancelItem() { - return new ItemBuilder(BaseItems.REVIEW_CANCEL.getItem()) - .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.CANCEL)) - .color(RED) - .decoration(BOLD, true)) - .build(); - } - // --- Point Items --- private ItemStack getZeroPointItem() { return new ItemBuilder(BaseItems.REVIEW_POINT_ZERO.getItem()) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 2356aabe..a442a6a3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -1,6 +1,7 @@ package com.alpsbte.plotsystem.core.menus.review; import com.alpsbte.alpslib.utils.item.ItemBuilder; +import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; @@ -16,16 +17,25 @@ import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; +import com.google.common.collect.Multimap; import com.sk89q.worldedit.WorldEditException; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Bukkit; import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.attribute.AttributeModifier; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import static net.kyori.adventure.text.Component.empty; @@ -34,6 +44,7 @@ public class ReviewPlotTogglesMenu extends AbstractMenu { private final Plot plot; private final ReviewRating rating; + private List buildTeamCriteria = new ArrayList<>(); public ReviewPlotTogglesMenu(Player player, Plot plot, ReviewRating rating) { super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); @@ -43,25 +54,60 @@ public ReviewPlotTogglesMenu(Player player, Plot plot, ReviewRating rating) { @Override protected void setMenuItemsAsync() { - // Set back item - getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); - // Set plot information item getMenu().getSlot(4).setItem(ReviewItems.getPlotInfoItem(getMenuPlayer(), plot)); // Set review information item getMenu().getSlot(7).setItem(ReviewItems.getReviewInfoItem(getMenuPlayer())); - // Set submit item - getMenu().getSlot(49); + // Set toggle items + buildTeamCriteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(plot.getCityProject().getBuildTeam().getID()); + for (int i = 0; i < Math.min(buildTeamCriteria.size(), 36); i++) { + ToggleCriteria criteria = buildTeamCriteria.get(i); + boolean isChecked = rating.getCheckedToggles().stream() + .anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); + getMenu().getSlot(9 + i).setItem(getToggleItem(criteria, isChecked)); + } - // Set cancel item - getMenu().getSlot(51); + // Set back item + getMenu().getSlot(48).setItem(MenuItems.backMenuItem(getMenuPlayer())); + + // Set submit item + getMenu().getSlot(50).setItem(getSubmitItem()); } @Override protected void setItemClickEventsAsync() { + // Set click event for back item + getMenu().getSlot(48).setClickHandler(((player, clickInformation) -> { + player.closeInventory(); + new ReviewPlotMenu(player, plot, rating); + })); + + // Set click event for submit item + getMenu().getSlot(50).setClickHandler(((player, clickInformation) -> submitReview())); + + // Set click event for toggle items + for (int i = 0; i < Math.min(buildTeamCriteria.size(), 36); i++) { + int finalI = i; + getMenu().getSlot(9 + i).setClickHandler(((player, clickInformation) -> { + ToggleCriteria clickedCriteria = buildTeamCriteria.get(finalI); + List checked = new ArrayList<>(rating.getCheckedToggles()); + + boolean isChecked = checked.stream().anyMatch(t -> t.getCriteriaName().equals(clickedCriteria.getCriteriaName())); + if (isChecked) { + checked.remove(checked.stream().filter(t -> t.getCriteriaName().equals(clickedCriteria.getCriteriaName())).findFirst().orElseThrow()); + } else { + checked.add(clickedCriteria); + } + + rating.setCheckedToggles(checked); + getMenu().getSlot(9 + finalI).setItem(getToggleItem(clickedCriteria, !isChecked)); + getMenu().getSlot(50).setItem(getSubmitItem()); // update submit item + player.playSound(player.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); + })); + } } @Override @@ -69,16 +115,14 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) .pattern("111101111") - .pattern("100000001") - .pattern("100000001") - .pattern("100000001") - .pattern("100000001") + .pattern("000000000") + .pattern("000000000") + .pattern("000000000") + .pattern("000000000") .pattern("111010111") .build(); } - - private void submitReview() { // a plot is rejected if either of the point sliders are 0 boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; @@ -94,7 +138,7 @@ else if (!criteria.isOptional()) { isRejected = true; // a plot is also rejected if any of the required toggles are not checked } } - int checkedPoints = (int) Math.floor(((double)checkedCounter / buildTeamCriteria.size())*10); + int checkedPoints = (int) Math.floor(((double) checkedCounter / buildTeamCriteria.size()) * 10); totalRating += checkedPoints; if (totalRating <= 8) isRejected = true; // a plot is also rejected if the total rating is less than or equal to 8 @@ -117,7 +161,6 @@ else if (!criteria.isOptional()) { if (!PlotUtils.savePlotAsSchematic(plot)) { getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); - return; } } catch (IOException | WorldEditException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); @@ -194,4 +237,48 @@ else if (!criteria.isOptional()) { PlayerFeedbackChatInput.sendChatInputMessage(getMenuPlayer()); }); } + + private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { + ItemStack baseItem = checked + ? BaseItems.REVIEW_TOGGLE_CHECKED.getItem() + : BaseItems.REVIEW_TOGGLE_DISABLED.getItem(); + return new ItemBuilder(baseItem) + .setName(text(criteria.getCriteriaName())) + .setLore(new LoreBuilder() + .addLine("Optional? " + criteria.isOptional()) + .build()) + .build(); + } + + private ItemStack getSubmitItem() { + int totalToggles = buildTeamCriteria.size(); + int checkedToggles = rating.getCheckedToggles().size(); + double togglePercentage = (double) checkedToggles / totalToggles * 100; + int togglePoints = (int) Math.floor(togglePercentage / 10.0); + int totalPoints = rating.getAccuracyPoints() + rating.getBlockPalettePoints() + togglePoints; + + //TODO: translate + String accuracyPointsText = "Accuracy Points"; + String blockPalettePointsText = "Block Palette Points"; + String togglesPointsText = "Toggle Points"; + String totalPointsText = "Total Points"; + + return new ItemBuilder(BaseItems.REVIEW_SUBMIT.getItem()) + .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT), NamedTextColor.GREEN).decoration(TextDecoration.BOLD, true)) + .setLore(new LoreBuilder() + .addLine(text( accuracyPointsText + ": ", NamedTextColor.GRAY) + .append(text(rating.getAccuracyPoints(), NamedTextColor.WHITE))) + .addLine(text( blockPalettePointsText + ": ", NamedTextColor.GRAY) + .append(text(rating.getBlockPalettePoints(), NamedTextColor.WHITE))) + .addLine(text( togglesPointsText + ": ", NamedTextColor.GRAY) + .append(text(togglePoints, NamedTextColor.WHITE)) + .append(text(" (" + checkedToggles + "/" + totalToggles + " → " + String.format("%.02f", togglePercentage) + "%)", NamedTextColor.DARK_GRAY))) + .addLine(text("-----", NamedTextColor.DARK_GRAY)) + .addLine(text(totalPointsText + ": ", NamedTextColor.GRAY) + .append(text(totalPoints, NamedTextColor.GOLD))) + .emptyLine() + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_REVIEW), NamedTextColor.GRAY), true) + .build()) + .build(); + } } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 699f613f..265db6b1 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -97,6 +97,7 @@ private MenuTitle() {} private static final String MENU_TITLES = "menu-title."; public static final String CLOSE = MENU_TITLES + "close"; public static final String BACK = MENU_TITLES + "back"; + public static final String CONTINUE = MENU_TITLES + "continue"; public static final String NEXT_PAGE = MENU_TITLES + "next-page"; public static final String PREVIOUS_PAGE = MENU_TITLES + "previous-page"; public static final String ERROR = MENU_TITLES + "error"; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index a0fd136d..8d2d89b9 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -27,6 +27,7 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; public enum BaseItems { @@ -41,12 +42,12 @@ public enum BaseItems { MENU_ERROR("menu-error"), MENU_CLOSE("menu-close"), + MENU_BACK("menu-back"), + MENU_NEXT("menu-next"), REVIEW_ITEM("review-item"), REVIEW_ACCURACY("review-accuracy"), REVIEW_BLOCK_PALETTE("review-block-palette"), - REVIEW_DETAILING("review-detailing"), - REVIEW_TECHNIQUE("review-technique"), REVIEW_POINT_ZERO("review-point-zero"), REVIEW_POINT_ONE("review-point-one"), REVIEW_POINT_TWO("review-point-two"), @@ -56,7 +57,8 @@ public enum BaseItems { REVIEW_SUBMIT("review-submit"), REVIEW_CANCEL("review-cancel"), REVIEW_INFO_PLOT("review-info-plot"), - + REVIEW_TOGGLE_DISABLED("review-toggle-disabled"), + REVIEW_TOGGLE_CHECKED("review-toggle-checked"), SETTINGS_ITEM("settings-item"), RANDOM_PLOT_ITEM("random-plot-item"); @@ -67,6 +69,9 @@ public enum BaseItems { materialString = materialString == null ? Material.BARRIER.name() : materialString; Object customModelData = ConfigUtil.getInstance().configs[2].get(configPath + ".modelId"); itemStack = Utils.getConfiguredItem(materialString, customModelData); + + itemStack.getItemMeta().setAttributeModifiers(null); + itemStack.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ADDITIONAL_TOOLTIP, ItemFlag.HIDE_ENCHANTS); } public ItemStack getItem() { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java index 6a8087b1..0f7515db 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java @@ -47,11 +47,17 @@ public static ItemStack closeMenuItem(Player player) { } public static ItemStack backMenuItem(Player player) { - return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.BACK_BUTTON.getId())) + return new ItemBuilder(BaseItems.MENU_BACK.getItem()) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.BACK), GOLD, BOLD)) .build(); } + public static ItemStack continueMenuItem(Player player) { + return new ItemBuilder(BaseItems.MENU_NEXT.getItem()) + .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.CONTINUE), GOLD, BOLD)) + .build(); + } + public static ItemStack nextPageItem(Player player) { return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.NEXT_BUTTON.getId())) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.NEXT_PAGE), GOLD, BOLD)) diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml index 0c448b40..db0afaad 100644 --- a/src/main/resources/items.yml +++ b/src/main/resources/items.yml @@ -25,6 +25,12 @@ menu-error: menu-close: material: BARRIER modelId: '' +menu-back: + material: head(9226) + modelId: '' +menu-next: + material: head(9223) + modelId: '' review-item: material: BOOK @@ -35,11 +41,11 @@ review-accuracy: review-block-palette: material: PAINTING modelId: '' -review-detailing: - material: ENDER_EYE +review-toggle-disabled: + material: FIREWORK_STAR modelId: '' -review-technique: - material: WOODEN_AXE +review-toggle-checked: + material: SLIME_BALL modelId: '' review-point-zero: material: LIGHT_GRAY_WOOL @@ -60,7 +66,7 @@ review-point-five: material: LIME_WOOL modelId: '' review-submit: - material: GREEN_CONCRETE + material: FIREWORK_ROCKET modelId: '' review-cancel: material: RED_CONCRETE diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index ad9497b9..5557dca1 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: 'Schließen' back: 'Zurück' + continue: 'Weiter' next-page: 'Nächste Seite' previous-page: 'Vorherige Seite' error: 'Fehler' diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 25c569d0..8ac09125 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: 'Close' back: 'Back' + continue: 'Continue' next-page: 'Next Page' previous-page: 'Previous Page' error: 'Error' From bac56fbc27e97d8aa324739f756a78b5860eae8f Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 13 Apr 2025 17:53:49 +0200 Subject: [PATCH 067/175] show if plot will be rejected in submit item lore and add toggle lore --- .../core/menus/review/ReviewPlotMenu.java | 1 + .../menus/review/ReviewPlotTogglesMenu.java | 31 ++++++++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index 56b7f2d0..bd45a03d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -193,6 +193,7 @@ protected void setItemClickEventsAsync() { ItemStack newItem = getMenu().getSlot(slot).getItem(clickPlayer); newItem.setItemMeta(meta); + newItem.addItemFlags(ItemFlag.HIDE_ENCHANTS); getMenu().getSlot(slot).setItem(newItem); sentWarning = false; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index a442a6a3..4fa20fb5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -22,6 +22,7 @@ import com.google.common.collect.Multimap; import com.sk89q.worldedit.WorldEditException; import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Bukkit; @@ -128,8 +129,6 @@ private void submitReview() { boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); - BuildTeam bt = plot.getCityProject().getBuildTeam(); - List buildTeamCriteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(bt.getID()); int checkedCounter = 0; for (ToggleCriteria criteria : buildTeamCriteria) { boolean checked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); @@ -241,11 +240,16 @@ else if (!criteria.isOptional()) { private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { ItemStack baseItem = checked ? BaseItems.REVIEW_TOGGLE_CHECKED.getItem() - : BaseItems.REVIEW_TOGGLE_DISABLED.getItem(); + : criteria.isOptional() ? BaseItems.REVIEW_TOGGLE_DISABLED.getItem() : new ItemStack(Material.FIRE_CHARGE); + // TODO: translate return new ItemBuilder(baseItem) .setName(text(criteria.getCriteriaName())) .setLore(new LoreBuilder() - .addLine("Optional? " + criteria.isOptional()) + .addLine(criteria.isOptional() + ? text("OPTIONAL", NamedTextColor.GRAY).decoration(TextDecoration.BOLD, true) + : text("REQUIRED", NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) + .emptyLine() + .addLine(text("Click to toggle the criteria", NamedTextColor.GRAY)) .build()) .build(); } @@ -263,9 +267,26 @@ private ItemStack getSubmitItem() { String togglesPointsText = "Toggle Points"; String totalPointsText = "Total Points"; + boolean willReject = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0 || totalPoints <= 8; + for (ToggleCriteria criteria : buildTeamCriteria) { + boolean checked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); + if (!checked && !criteria.isOptional()) { + willReject = true; // a plot is also rejected if any of the required toggles are not checked + } + } + + TextComponent resultNotice; + if (willReject) { + resultNotice = text("Plot will be rejected!", NamedTextColor.YELLOW); + } else { + resultNotice = text("Plot will be accepted", NamedTextColor.GREEN); + } + return new ItemBuilder(BaseItems.REVIEW_SUBMIT.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT), NamedTextColor.GREEN).decoration(TextDecoration.BOLD, true)) .setLore(new LoreBuilder() + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_REVIEW), NamedTextColor.GRAY), true) + .emptyLine() .addLine(text( accuracyPointsText + ": ", NamedTextColor.GRAY) .append(text(rating.getAccuracyPoints(), NamedTextColor.WHITE))) .addLine(text( blockPalettePointsText + ": ", NamedTextColor.GRAY) @@ -277,7 +298,7 @@ private ItemStack getSubmitItem() { .addLine(text(totalPointsText + ": ", NamedTextColor.GRAY) .append(text(totalPoints, NamedTextColor.GOLD))) .emptyLine() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_REVIEW), NamedTextColor.GRAY), true) + .addLine(resultNotice) .build()) .build(); } From 26c43aea2a30e0e5b41f35ae341515c0dc8a2b6d Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 14 Apr 2025 01:06:04 +0200 Subject: [PATCH 068/175] offset entire completed schematic to initialSchem heights and set plot mc version on review --- .../core/database/providers/PlotProvider.java | 14 ++++++++++++++ .../core/database/providers/ReviewProvider.java | 9 ++++++--- .../core/menus/review/ReviewPlotMenu.java | 2 +- .../core/menus/review/ReviewPlotTogglesMenu.java | 2 +- .../alpsbte/plotsystem/core/system/plot/Plot.java | 11 ++--------- .../core/system/plot/utils/PlotUtils.java | 13 +++++++------ .../core/system/plot/world/OnePlotWorld.java | 4 ++-- 7 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index f73c3065..2b21578a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -32,6 +32,7 @@ import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import org.bukkit.Bukkit; import java.sql.*; import java.time.LocalDate; @@ -302,6 +303,19 @@ public boolean setStatus(int plotId, Status status) { return false; } + public boolean setMcVersion(int plotId) { + String query = "UPDATE plot SET mc_version = ? WHERE plot_id = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, Bukkit.getMinecraftVersion()); + stmt.setInt(2, plotId); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + public boolean setPlotMembers(int plotId, List members) { String deleteQuery = "DELETE FROM builder_is_plot_member WHERE plot_id = ?;"; String insertQuery = "INSERT INTO builder_is_plot_member (plot_id, uuid) VALUES (?, ?);"; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 9e2251d8..fcf94d85 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,5 +1,6 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -162,9 +163,11 @@ public boolean updateFeedback(int reviewId, String newFeedback) { } public boolean createReview(Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { - boolean result = false; - String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by, is_rejected) " + - "VALUES (?, ?, ?, ?, ?);"; + boolean result = DataProvider.PLOT.setMcVersion(plot.getID()); + if (!result) return false; + + String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) " + + "VALUES (?, ?, ?, ?);"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plot.getID()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index bd45a03d..8c8d3ff7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -138,7 +138,7 @@ protected void setItemClickEventsAsync() { new PlotActionsMenu(clickPlayer, plot); }); - /* Set click event for submit item */ + // Set click event for submit item getMenu().getSlot(50).setClickHandler((clickPlayer, clickInformation) -> Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 4fa20fb5..b5defd46 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -249,7 +249,7 @@ private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { ? text("OPTIONAL", NamedTextColor.GRAY).decoration(TextDecoration.BOLD, true) : text("REQUIRED", NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) .emptyLine() - .addLine(text("Click to toggle the criteria", NamedTextColor.GRAY)) + .addLine(text("Click to toggle", NamedTextColor.GRAY)) .build()) .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 093f56b0..835f540d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -117,7 +117,7 @@ public List getOutline() { return this.outline; List pointVectors; - pointVectors = getOutlinePoints((outlineBounds.isEmpty() || getVersion() <= 2) ? "" : outlineBounds); + pointVectors = getOutlinePoints(outlineBounds.isEmpty() ? "" : outlineBounds); return pointVectors; } @@ -189,14 +189,7 @@ public byte[] getCompletedSchematic() { @Override public BlockVector3 getCenter() { - try { - if (getVersion() >= 3) { - return super.getCenter(); - } else return BlockVector3.at(PlotWorld.PLOT_SIZE / 2d, this.getWorld().getPlotHeightCentered(), PlotWorld.PLOT_SIZE / 2d); - } catch (IOException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Failed to load schematic file to clipboard!"), ex); - } - return null; + return super.getCenter(); } public List getReviewHistory() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 842364ac..8c456242 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -58,6 +58,7 @@ import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.math.Vector3; +import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Polygonal2DRegion; import com.sk89q.worldguard.WorldGuard; @@ -220,19 +221,19 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException com.sk89q.worldedit.world.World world = new BukkitWorld(plot.getWorld().getBukkitWorld()); Polygonal2DRegion region = new Polygonal2DRegion(world, plotOutlines, cuboidRegion.getMinimumPoint().y(), cuboidRegion.getMaximumPoint().y()); - - // Copy and write finished plot clipboard to schematic + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (Clipboard cb = new BlockArrayClipboard(region)) { cb.setOrigin(BlockVector3.at(plotCenter.x(), cuboidRegion.getMinimumY(), (double) plotCenter.z())); ForwardExtentCopy forwardExtentCopy = new ForwardExtentCopy(Objects.requireNonNull(region.getWorld()), region, cb, region.getMinimumPoint()); Operations.complete(forwardExtentCopy); - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { - writer.write(clipboard); + try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { + double initialY = clipboard.getRegion().getMinimumY(); + double offset = initialY - cuboidRegion.getMinimumY(); + writer.write(cb.transform(new AffineTransform().translate(Vector3.at(0,offset,0)))); + } } // Set Completed Schematic diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index 14bd20bd..94a1a1cb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -126,8 +126,8 @@ public boolean teleportPlayer(@NotNull Player player) { } @Override - public int getPlotHeight() throws IOException { - return getPlot().getVersion() >= 3 ? MIN_WORLD_HEIGHT : getPlotHeightCentered(); + public int getPlotHeight() { + return MIN_WORLD_HEIGHT; } @Override From f7a83bbfef6b9c69d2c7f8227bcb6612e34cc483 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Tue, 15 Apr 2025 15:43:45 +0200 Subject: [PATCH 069/175] Remove CustomHeads.java and add all heads to BaseItems.java --- .../com/alpsbte/plotsystem/PlotSystem.java | 3 -- .../core/menus/PlotActionsMenu.java | 7 ++- .../plotsystem/core/menus/PlotMemberMenu.java | 6 +-- .../plotsystem/core/menus/PlotTypeMenu.java | 7 ++- .../plotsystem/core/menus/SettingsMenu.java | 7 ++- .../core/menus/companion/CompanionMenu.java | 10 ++-- .../core/menus/review/ReviewItems.java | 4 +- .../core/menus/tutorial/TutorialsMenu.java | 4 +- .../com/alpsbte/plotsystem/utils/Utils.java | 5 -- .../plotsystem/utils/items/BaseItems.java | 18 ++++++- .../plotsystem/utils/items/CustomHeads.java | 53 ------------------- .../plotsystem/utils/items/MenuItems.java | 5 +- src/main/resources/items.yml | 40 ++++++++++++++ 13 files changed, 78 insertions(+), 91 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/utils/items/CustomHeads.java diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 810f7af6..0396448d 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -201,9 +201,6 @@ public void onEnable() { Bukkit.getConsoleSender().sendMessage(text("Could not find Protocol-Lib! Consider installing it to avoid issues.", RED)); } - // Cache and register custom heads - Bukkit.getScheduler().runTaskAsynchronously(this, Utils::registerCustomHeads); - // Register tutorials if (getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE)) { AbstractTutorial.registerTutorials(Collections.singletonList(BeginnerTutorial.class)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 981c7971..12a4f4b9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.menus; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; @@ -35,7 +34,7 @@ import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.CustomHeads; +import com.alpsbte.plotsystem.utils.items.BaseItems; import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; @@ -112,7 +111,7 @@ protected void setMenuItemsAsync() { FileConfiguration config = PlotSystem.getPlugin().getConfig(); if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { getMenu().getSlot(22) - .setItem(new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.ADD_BUTTON.getId())) + .setItem(new ItemBuilder(BaseItems.MENU_ADD.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.MANAGE_MEMBERS), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.MANAGE_MEMBERS), true) @@ -122,7 +121,7 @@ protected void setMenuItemsAsync() { .build()); } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { getMenu().getSlot(22) - .setItem(new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.REMOVE_BUTTON.getId())) + .setItem(new ItemBuilder(BaseItems.MENU_REMOVE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.LEAVE_PLOT), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.LEAVE_PLOT), true) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index bc1911f4..76ac91ab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -35,7 +35,7 @@ import com.alpsbte.plotsystem.utils.chat.PlayerInviteeChatInput; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.CustomHeads; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -80,9 +80,9 @@ protected void setPreviewItems() { }); // Set add plot member item - ItemStack whitePlus = AlpsHeadUtils.getCustomHead(CustomHeads.ADD_BUTTON.getId()); + ItemStack addItem = BaseItems.MENU_ADD.getItem(); getMenu().getSlot(16) - .setItem(new ItemBuilder(whitePlus) + .setItem(new ItemBuilder(addItem) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.ADD_MEMBER_TO_PLOT), GOLD, BOLD)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.ADD_MEMBER_TO_PLOT), true) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index 56389dcc..828c0c39 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.menus; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; @@ -34,7 +33,7 @@ import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.CustomHeads; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -64,7 +63,7 @@ protected void setPreviewItems() { protected void setMenuItemsAsync() { // Set plot type items getMenu().getSlot(11).setItem( - new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.FOCUS_MODE_BUTTON.getId())) + new ItemBuilder(BaseItems.PLOT_FOCUS_MODE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_FOCUS_MODE), GOLD, BOLD)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_FOCUS_MODE), true) @@ -84,7 +83,7 @@ protected void setMenuItemsAsync() { boolean inspirationModeDisabled = PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DISABLE_CITY_INSPIRATION_MODE); // TODO remove or enhance as soon CIM is working again if (!inspirationModeDisabled) { getMenu().getSlot(15).setItem( - new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.CITY_INSPIRATION_MODE_BUTTON.getId())) + new ItemBuilder(BaseItems.PLOT_CITY_INSPIRATION_MODE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_CITY_INSPIRATION_MODE), GOLD, BOLD) .append(text(" [", DARK_GRAY).append(text("BETA", RED).append(text("]", DARK_GRAY))))) // temporary BETA tag .setLore(new LoreBuilder() diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java index 707d0878..ad3d4128 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java @@ -24,12 +24,11 @@ package com.alpsbte.plotsystem.core.menus; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.CustomHeads; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -59,7 +58,7 @@ public SettingsMenu(Player player, Consumer onBack) { protected void setMenuItemsAsync() { // Set language item getMenu().getSlot(11).setItem( - new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.GLOBE_HEAD.getId())) + new ItemBuilder(BaseItems.LANGUAGE_ITEM.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_LANGUAGE), GOLD, BOLD)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_LANGUAGE)) @@ -68,7 +67,7 @@ protected void setMenuItemsAsync() { // Set Plot type item getMenu().getSlot(15).setItem( - new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.PLOT_TYPE_BUTTON.getId())) + new ItemBuilder(BaseItems.PLOT_TYPE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_PLOT_TYPE), GOLD, BOLD)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_PLOT_TYPE)) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 764059b9..98395805 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.menus.companion; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; @@ -45,7 +44,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; -import com.alpsbte.plotsystem.utils.items.CustomHeads; import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.TextComponent; import org.bukkit.Material; @@ -139,15 +137,15 @@ public static ItemStack getDifficultyItem(Player player, PlotDifficulty selected if (selectedPlotDifficulty != null) { switch (selectedPlotDifficulty) { case EASY: - item = AlpsHeadUtils.getCustomHead(CustomHeads.GREEN_CONCRETE.getId()); break; + item = BaseItems.DIFFICULTY_EASY.getItem(); break; case MEDIUM: - item = AlpsHeadUtils.getCustomHead(CustomHeads.YELLOW_CONCRETE.getId()); break; + item = BaseItems.DIFFICULTY_MEDIUM.getItem(); break; case HARD: - item = AlpsHeadUtils.getCustomHead(CustomHeads.RED_CONCRETE.getId()); break; + item = BaseItems.DIFFICULTY_HARD.getItem(); break; default: break; } - } else item = AlpsHeadUtils.getCustomHead(CustomHeads.WHITE_CONCRETE.getId()); + } else item = BaseItems.DIFFICULTY_AUTOMATIC.getItem(); Optional difficulty = DataProvider.DIFFICULTY.getDifficultyByEnum(selectedPlotDifficulty); if (difficulty.isEmpty()) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java index fc576588..f2afdcb5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java @@ -1,13 +1,11 @@ package com.alpsbte.plotsystem.core.menus.review; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; -import com.alpsbte.plotsystem.utils.items.CustomHeads; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -19,7 +17,7 @@ public class ReviewItems { public static ItemStack getReviewInfoItem(Player player) { String points = LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_POINTS); - return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.INFO_BUTTON.getId())) + return new ItemBuilder(BaseItems.REVIEW_INFO.getItem()) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.INFORMATION), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLines(true, LangUtil.getInstance().get(player, LangPaths.MenuDescription.INFORMATION)) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index 8ab2dff4..9a7bf4cc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -39,7 +39,7 @@ import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.CustomHeads; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.Component; import org.bukkit.Material; @@ -209,7 +209,7 @@ private static ItemStack getAdvancedTutorialItem(Player player) { } public static ItemStack getTutorialItem(Player player) { - return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.WORKBENCH.getId())) + return new ItemBuilder(BaseItems.TUTORIAL_ITEM.getItem()) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.TUTORIALS), AQUA, BOLD)) .setLore(new LoreBuilder().addLine(LangUtil.getInstance().get(player, LangPaths.MenuDescription.TUTORIALS), true).build()) .build(); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 34f083aa..36b8cdd5 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -36,7 +36,6 @@ import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.alpsbte.plotsystem.utils.items.CustomHeads; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.sk89q.worldedit.math.BlockVector2; import net.kyori.adventure.text.Component; @@ -211,10 +210,6 @@ private ItemUtils() {} } } - public static void registerCustomHeads() { - for (CustomHeads head : CustomHeads.values()) AlpsHeadUtils.registerCustomHead(head.getId()); - } - public static @NotNull Set getLineBetweenPoints(@NotNull BlockVector2 point1, @NotNull BlockVector2 point2, int pointsInLine) { double p1X = point1.x(); double p1Z = point1.z(); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index 8d2d89b9..47e5e409 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -39,11 +39,16 @@ public enum BaseItems { PLOT_UNFINISHED("plot-unfinished"), PLOT_UNREVIEWED("plot-unreviewed"), PLOT_COMPLETED("plot-completed"), + PLOT_TYPE("plot-type"), + PLOT_FOCUS_MODE("plot-focus-mode"), + PLOT_CITY_INSPIRATION_MODE("plot-city-inspiration-mode"), MENU_ERROR("menu-error"), MENU_CLOSE("menu-close"), MENU_BACK("menu-back"), MENU_NEXT("menu-next"), + MENU_ADD("menu-add"), + MENU_REMOVE("menu-remove"), REVIEW_ITEM("review-item"), REVIEW_ACCURACY("review-accuracy"), @@ -56,11 +61,22 @@ public enum BaseItems { REVIEW_POINT_FIVE("review-point-five"), REVIEW_SUBMIT("review-submit"), REVIEW_CANCEL("review-cancel"), + REVIEW_INFO("review-info"), REVIEW_INFO_PLOT("review-info-plot"), REVIEW_TOGGLE_DISABLED("review-toggle-disabled"), REVIEW_TOGGLE_CHECKED("review-toggle-checked"), + SETTINGS_ITEM("settings-item"), - RANDOM_PLOT_ITEM("random-plot-item"); + RANDOM_PLOT_ITEM("random-plot-item"), + + DIFFICULTY_AUTOMATIC("difficulty-automatic"), + DIFFICULTY_EASY("difficulty-easy"), + DIFFICULTY_MEDIUM("difficulty-medium"), + DIFFICULTY_HARD("difficulty-hard"), + + TUTORIAL_ITEM("tutorial-item"), + + LANGUAGE_ITEM("language-item"); final ItemStack itemStack; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/CustomHeads.java b/src/main/java/com/alpsbte/plotsystem/utils/items/CustomHeads.java deleted file mode 100644 index 36fbfc5e..00000000 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/CustomHeads.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.utils.items; - -public enum CustomHeads { - WHITE_CONCRETE("8614"), - GREEN_CONCRETE("8621"), - YELLOW_CONCRETE("8613"), - RED_CONCRETE("8616"), - WORKBENCH("24180"), - ADD_BUTTON("9237"), - REMOVE_BUTTON("9243"), - BACK_BUTTON("9226"), - NEXT_BUTTON("9223"), - PREVIOUS_BUTTON("9226"), - INFO_BUTTON("46488"), - GLOBE_HEAD("49973"), - PLOT_TYPE_BUTTON("4159"), - FOCUS_MODE_BUTTON("38199"), - CITY_INSPIRATION_MODE_BUTTON("38094"); - - final String id; - - CustomHeads(String id) { - this.id = id; - } - - public String getId() { - return id; - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java index 0f7515db..d2dd3f09 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.utils.items; -import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.utils.io.LangPaths; @@ -59,13 +58,13 @@ public static ItemStack continueMenuItem(Player player) { } public static ItemStack nextPageItem(Player player) { - return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.NEXT_BUTTON.getId())) + return new ItemBuilder(BaseItems.MENU_NEXT.getItem()) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.NEXT_PAGE), GOLD, BOLD)) .build(); } public static ItemStack previousPageItem(Player player) { - return new ItemBuilder(AlpsHeadUtils.getCustomHead(CustomHeads.PREVIOUS_BUTTON.getId())) + return new ItemBuilder(BaseItems.MENU_BACK.getItem()) .setName(text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.PREVIOUS_PAGE), GOLD, BOLD)) .build(); } diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml index db0afaad..7d3b0777 100644 --- a/src/main/resources/items.yml +++ b/src/main/resources/items.yml @@ -18,6 +18,15 @@ plot-unreviewed: plot-completed: material: GREEN_WOOL modelId: '' +plot-type: + material: head(4159) + modelId: '' +plot-focus-mode: + material: head(38199) + modelId: '' +plot-city-inspiration-mode: + material: head(38094) + modelId: '' menu-error: material: BARRIER @@ -31,6 +40,12 @@ menu-back: menu-next: material: head(9223) modelId: '' +menu-add: + material: head(9237) + modelId: '' +menu-remove: + material: head(9243) + modelId: '' review-item: material: BOOK @@ -71,6 +86,9 @@ review-submit: review-cancel: material: RED_CONCRETE modelId: '' +review-info: + material: head(46488) + modelId: '' review-info-plot: material: MAP modelId: '' @@ -81,5 +99,27 @@ settings-item: random-plot-item: material: COMPARATOR modelId: '' + +difficulty-automatic: + material: head(8614) + modelId: '' +difficulty-easy: + material: head(8621) + modelId: '' +difficulty-medium: + material: head(8613) + modelId: '' +difficulty-hard: + material: head(8616) + modelId: '' + +tutorial-item: + material: head(24180) + modelId: '' + +language-item: + material: head(49973) + modelId: '' + # NOTE: Do not change config-version: 1.2 \ No newline at end of file From 46892c3f0fa914698d1972d3b5ed7970d14ca28a Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 18 Apr 2025 03:36:34 +0200 Subject: [PATCH 070/175] add translations, add lots of items to items.yml and minor bugs --- .../commands/review/CMD_UndoReview.java | 2 +- .../plotsystem/core/EventListener.java | 15 ++++--- .../core/menus/BuilderUtilitiesMenu.java | 3 +- .../plotsystem/core/menus/FeedbackMenu.java | 7 ++-- .../core/menus/PlayerPlotsMenu.java | 4 +- .../core/menus/PlotActionsMenu.java | 10 ++--- .../core/menus/companion/CityProjectMenu.java | 2 +- .../core/menus/companion/CompanionMenu.java | 34 ++++++++-------- .../core/menus/companion/CountryMenu.java | 2 +- .../core/menus/review/ReviewPlotMenu.java | 7 ---- .../menus/review/ReviewPlotTogglesMenu.java | 29 ++++++-------- .../plotsystem/core/system/plot/Plot.java | 3 -- .../plot/generator/AbstractPlotGenerator.java | 1 - .../core/system/plot/utils/PlotUtils.java | 32 +++++++-------- .../plotsystem/utils/enums/Continent.java | 2 +- .../plotsystem/utils/io/ConfigUtil.java | 2 +- .../plotsystem/utils/io/LangPaths.java | 19 ++++++--- .../alpsbte/plotsystem/utils/io/LangUtil.java | 16 ++++---- .../plotsystem/utils/items/BaseItems.java | 13 +++++- .../plotsystem/utils/items/MenuItems.java | 2 +- src/main/resources/items.yml | 40 +++++++++++++++++-- src/main/resources/lang/de_DE.yml | 7 +--- src/main/resources/lang/en_GB.yml | 30 +++++++++++--- src/main/resources/lang/fr_FR.yml | 8 +--- src/main/resources/lang/ko_KR.yml | 7 +--- src/main/resources/lang/pt_PT.yml | 7 +--- src/main/resources/lang/ru_RU.yml | 7 +--- src/main/resources/lang/zh_CN.yml | 7 +--- src/main/resources/lang/zh_TW.yml | 7 +--- 29 files changed, 178 insertions(+), 147 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index bc26fc76..ac04a569 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -90,7 +90,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Optional review = plot.getLatestReview(); if (review.isEmpty()) { - player.sendMessage(Utils.ChatUtils.getAlertFormat("Review could not be found!")); // TODO: translate text + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.REVIEW_NOT_FOUND))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 5c629e3a..9ebf4e8d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -56,6 +56,7 @@ import com.sk89q.worldguard.protection.regions.RegionQuery; import io.papermc.paper.event.player.AsyncChatEvent; import li.cinnazeyy.langlibs.core.event.LanguageChangeEvent; +import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.title.Title; import org.bukkit.Bukkit; @@ -173,9 +174,9 @@ public void onInventoryClickEvent(@NotNull InventoryClickEvent event) { if (event.getWhoClicked().getGameMode() == GameMode.CREATIVE && (event.getCursor().isSimilar(CompanionMenu.getMenuItem((Player) event.getWhoClicked())) || event.getCursor().isSimilar(ReviewMenu.getMenuItem((Player) event.getWhoClicked())))) { - event.getView().setCursor(ItemStack.empty()); - event.setCancelled(true); - } + event.getView().setCursor(ItemStack.empty()); + event.setCancelled(true); + } } @@ -294,10 +295,14 @@ private void sendReviewNotices(@NotNull Player player, Builder builder) { List notifications = DataProvider.REVIEW.getReviewNotifications(player.getUniqueId()); if (!notifications.isEmpty()) { PlotUtils.ChatFormatting.sendFeedbackMessage(notifications, player); - String subtitleText = " Plot" + (notifications.size() == 1 ? " " : "s ") + (notifications.size() == 1 ? "has" : "have") + " been reviewed!"; // TODO: translate + Component subtitleComp = LangUtil.getInstance().getComponent(player.getUniqueId(), + notifications.size() == 1 + ? LangPaths.Message.Info.PLOTS_REVIEWED_SINGULAR + : LangPaths.Message.Info.PLOTS_REVIEWED_PLURAL, + GREEN, text(notifications.size(), GOLD).decoration(BOLD, true)); player.showTitle(Title.title( empty(), - text(notifications.size(), GOLD).decoration(BOLD, true).append(text(subtitleText, GREEN).decoration(BOLD, true)), + subtitleComp, Title.Times.times(Duration.ofSeconds(1), Duration.ofSeconds(8), Duration.ofSeconds(1))) ); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java index 8f0e74b9..76d8409a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.Component; import org.bukkit.Material; @@ -111,7 +112,7 @@ protected Mask getMask() { * @return Menu item */ public static ItemStack getMenuItem(Player player) { - return new ItemBuilder(Material.GOLDEN_AXE) + return new ItemBuilder(BaseItems.BUILDER_UTILITIES.getItem()) .setName(Component.text(LangUtil.getInstance().get(player, LangPaths.MenuTitle.BUILDER_UTILITIES), AQUA, BOLD)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(player, LangPaths.MenuDescription.BUILDER_UTILITIES), true).build()) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index f1e13a9d..8209e1b3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -31,6 +31,7 @@ import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -66,7 +67,7 @@ protected void setMenuItemsAsync() { plot.getLatestReview().ifPresent(value -> this.review = value); // Set score item - getMenu().getSlot(10).setItem(new ItemBuilder(Material.NETHER_STAR) + getMenu().getSlot(10).setItem(new ItemBuilder(BaseItems.REVIEW_SCORE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE), AQUA, BOLD)) .setLore(new LoreBuilder() .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY).append(text(plot.getTotalScore(), WHITE))) @@ -87,8 +88,8 @@ protected void setMenuItemsAsync() { .build()); // Set feedback text item - String feedbackText = review.getFeedback() == null ? "No Feedback" : review.getFeedback(); // TODO: translate no feedback text - getMenu().getSlot(13).setItem(new ItemBuilder(Material.WRITABLE_BOOK) + String feedbackText = review.getFeedback() == null ? LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.NO_FEEDBACK) : review.getFeedback(); + getMenu().getSlot(13).setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA, BOLD)) .setLore(new LoreBuilder() .addLine(feedbackText.replaceAll("//", " "), true) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index a6df3f91..6b129dd9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -169,7 +169,9 @@ private LoreBuilder getLore(Plot plot, Player p) { ); builder.emptyLine(); builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.FEEDBACK) + ":", GRAY)); - String feedback = review.get().getFeedback() == null ? "No Feedback" : review.get().getFeedback().replaceAll("//", " "); // TODO: translate + String feedback = review.get().getFeedback() == null + ? LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.NO_FEEDBACK) + : review.get().getFeedback().replaceAll("//", " "); builder.addLine(text(feedback, WHITE), true); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 12a4f4b9..bc179ed6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -62,14 +62,14 @@ protected void setMenuItemsAsync() { // Set plot submit or undo submit item if (plot.getStatus().equals(Status.unreviewed)) { getMenu().getSlot(10) - .setItem(new ItemBuilder(Material.FIRE_CHARGE, 1) + .setItem(new ItemBuilder(BaseItems.PLOT_UNDO_SUBMIT.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.UNDO_SUBMIT), RED).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.UNDO_SUBMIT), true).build()) .build()); } else { getMenu().getSlot(10) - .setItem(new ItemBuilder(Material.NAME_TAG, 1) + .setItem(new ItemBuilder(BaseItems.PLOT_SUBMIT.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SUBMIT), GREEN).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SUBMIT_PLOT)).color(GRAY), true) @@ -81,14 +81,14 @@ protected void setMenuItemsAsync() { // Set teleport to plot item getMenu().getSlot(hasFeedback ? 12 : 13) - .setItem(new ItemBuilder(Material.COMPASS, 1) + .setItem(new ItemBuilder(BaseItems.PLOT_TELEPORT.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.TELEPORT), GOLD).decoration(BOLD, true)) .setLore(new LoreBuilder().addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.TELEPORT)).color(GRAY), true).build()) .build()); // Set plot abandon item getMenu().getSlot(hasFeedback ? 14 : 16) - .setItem(new ItemBuilder(Material.BARRIER, 1) + .setItem(new ItemBuilder(BaseItems.PLOT_ABANDON.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.ABANDON), RED).decoration(BOLD, true)) .setLore(new LoreBuilder() .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.ABANDON), true) @@ -100,7 +100,7 @@ protected void setMenuItemsAsync() { // Set plot feedback item if (hasFeedback) { getMenu().getSlot(16) - .setItem(new ItemBuilder(Material.WRITABLE_BOOK) + .setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder().addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.FEEDBACK), true).build()) .build()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index ee01da7d..0a17b88f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -172,7 +172,7 @@ public static List getValidCityProjects(PlotDifficulty selectedPlot protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) - .pattern("101111001") + .pattern("001111001") .pattern("000000000") .pattern("000000000") .pattern("000000000") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 98395805..5b68907e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -46,7 +46,6 @@ import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; import net.kyori.adventure.text.TextComponent; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.Menu; @@ -148,8 +147,8 @@ public static ItemStack getDifficultyItem(Player player, PlotDifficulty selected } else item = BaseItems.DIFFICULTY_AUTOMATIC.getItem(); Optional difficulty = DataProvider.DIFFICULTY.getDifficultyByEnum(selectedPlotDifficulty); - if (difficulty.isEmpty()) { - PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " + selectedPlotDifficulty + " was found!")); + if (difficulty.isEmpty() && selectedPlotDifficulty != null) { + PlotSystem.getPlugin().getComponentLogger().error(text("No database entry for difficulty " + selectedPlotDifficulty.name() + " was found!")); } double scoreMultiplier = difficulty.map(Difficulty::getMultiplier).orElse(0.0); @@ -221,31 +220,34 @@ public static class FooterItem { public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) { String nameText = LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); - TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS), GOLD).decoration(BOLD, true); - TextComponent slotDescriptionComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), GRAY); - - Material itemMaterial = Material.MAP; - ArrayList lore = new LoreBuilder() - .addLines(slotDescriptionComp, - empty(), - statusComp.append(text(": Unassigned", GRAY)).decoration(BOLD, true)) - .build(); + ItemStack baseItem = plot == null ? BaseItems.PLOT_SLOT_EMPTY.getItem() : BaseItems.PLOT_SLOT_FILLED.getItem(); + baseItem.setAmount(1 + slotIndex); + ArrayList lore; - if (plot != null) { - itemMaterial = Material.FILLED_MAP; + if (plot == null) { + TextComponent slotDescriptionComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuDescription.SLOT), GRAY); + lore = new LoreBuilder() + .addLine(slotDescriptionComp) + .build(); + } else { String plotIdText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.ID); String plotCityText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.CITY); String plotDifficultyText = LangUtil.getInstance().get(langPlayer, LangPaths.Plot.DIFFICULTY); + String statusText = LangUtil.getInstance().get(langPlayer, LangPaths.Database.STATUS + "." + plot.getStatus().name() + ".name"); + + TextComponent statusComp = text(LangUtil.getInstance().get(langPlayer, LangPaths.Plot.STATUS) + ": ", GOLD) + .decoration(BOLD, true) + .append(text(statusText, GRAY)); lore = new LoreBuilder() .addLines(text(plotIdText + ": ", GRAY).append(text(plot.getID(), WHITE)), text(plotCityText + ": ", GRAY).append(text(plot.getCityProject().getName(langPlayer), WHITE)), text(plotDifficultyText + ": ", GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), WHITE)), empty(), - statusComp.append(text(": Unassigned", GRAY)).decoration(BOLD, true)) + statusComp) .build(); } - return new ItemBuilder(itemMaterial, 1 + slotIndex) + return new ItemBuilder(baseItem) .setName(text(nameText, GOLD).decoration(BOLD, true)) .setLore(lore) .build(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index e60e24ae..7c9c688b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -143,7 +143,7 @@ public static boolean generateRandomPlot(Player clickPlayer, @NotNull List Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); - boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; - if (totalRating == 0 && !sentWarning) { clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_ABANDONED))); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); sentWarning = true; return; - } else if (isRejected && !sentWarning) { - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_GET_REJECTED))); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.CREATE_PLOT_SOUND, 1, 1); - sentWarning = true; - return; } else if (totalRating == 0) { plot.setStatus(Status.unfinished); Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index b5defd46..9e379f87 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -5,7 +5,6 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; -import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; @@ -19,7 +18,6 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; -import com.google.common.collect.Multimap; import com.sk89q.worldedit.WorldEditException; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; @@ -27,10 +25,7 @@ import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; @@ -238,18 +233,18 @@ else if (!criteria.isOptional()) { } private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { + Player p = getMenuPlayer(); ItemStack baseItem = checked ? BaseItems.REVIEW_TOGGLE_CHECKED.getItem() - : criteria.isOptional() ? BaseItems.REVIEW_TOGGLE_DISABLED.getItem() : new ItemStack(Material.FIRE_CHARGE); - // TODO: translate + : criteria.isOptional() ? BaseItems.REVIEW_TOGGLE_OPTIONAL.getItem() : BaseItems.REVIEW_TOGGLE_REQUIRED.getItem(); return new ItemBuilder(baseItem) .setName(text(criteria.getCriteriaName())) .setLore(new LoreBuilder() .addLine(criteria.isOptional() - ? text("OPTIONAL", NamedTextColor.GRAY).decoration(TextDecoration.BOLD, true) - : text("REQUIRED", NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) + ? text(LangUtil.getInstance().get(p, LangPaths.Note.OPTIONAL), NamedTextColor.GRAY).decoration(TextDecoration.BOLD, true) + : text(LangUtil.getInstance().get(p, LangPaths.Note.REQUIRED), NamedTextColor.GOLD).decoration(TextDecoration.BOLD, true)) .emptyLine() - .addLine(text("Click to toggle", NamedTextColor.GRAY)) + .addLine(text(LangUtil.getInstance().get(p, LangPaths.Note.Action.CLICK_TO_TOGGLE), NamedTextColor.GRAY)) .build()) .build(); } @@ -261,25 +256,25 @@ private ItemStack getSubmitItem() { int togglePoints = (int) Math.floor(togglePercentage / 10.0); int totalPoints = rating.getAccuracyPoints() + rating.getBlockPalettePoints() + togglePoints; - //TODO: translate - String accuracyPointsText = "Accuracy Points"; - String blockPalettePointsText = "Block Palette Points"; - String togglesPointsText = "Toggle Points"; - String totalPointsText = "Total Points"; + String accuracyPointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ACCURACY_POINTS); + String blockPalettePointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.BLOCK_PALETTE_POINTS); + String togglesPointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.TOGGLE_POINTS); + String totalPointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.TOTAL_POINTS); boolean willReject = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0 || totalPoints <= 8; for (ToggleCriteria criteria : buildTeamCriteria) { boolean checked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); if (!checked && !criteria.isOptional()) { willReject = true; // a plot is also rejected if any of the required toggles are not checked + break; } } TextComponent resultNotice; if (willReject) { - resultNotice = text("Plot will be rejected!", NamedTextColor.YELLOW); + resultNotice = text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_BE_REJECTED), NamedTextColor.YELLOW); } else { - resultNotice = text("Plot will be accepted", NamedTextColor.GREEN); + resultNotice = text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_WILL_BE_ACCEPTED), NamedTextColor.GREEN); } return new ItemBuilder(BaseItems.REVIEW_SUBMIT.getItem()) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 835f540d..dc2886f7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -42,15 +42,12 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.io.IOException; import java.time.LocalDate; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; -import static net.kyori.adventure.text.Component.text; - public class Plot extends AbstractPlot { private final CityProject cityProject; private final PlotDifficulty difficulty; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 5b1949b5..a79e0b02 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -40,7 +40,6 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitWorld; import com.sk89q.worldedit.extent.clipboard.Clipboard; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 8c456242..2637eb1c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -308,9 +308,8 @@ public static void checkPlotsForLastActivity() { public static void informPlayerAboutUnfinishedPlots(@NotNull Player player, Builder builder) { try { List plots = Cache.getCachedInProgressPlots(builder); - if (!plots.isEmpty()) { - PlotUtils.ChatFormatting.sendUnfinishedPlotReminderMessage(plots, player); - } + if (plots.isEmpty()) return; + ChatFormatting.sendUnfinishedPlotReminderMessage(plots, player); } catch (Exception ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while trying to inform the player about his unfinished plots!"), ex); } @@ -394,21 +393,20 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { try { CompletableFuture.runAsync(() -> { - if (plot.getPlotType() != PlotType.TUTORIAL) { - Plot dPlot = (Plot) plot; - DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getID()); - for (Builder builder : dPlot.getPlotMembers()) dPlot.removePlotMember(builder); - - if (plot.getPlotOwner() != null) { - Cache.clearCache(plot.getPlotOwner().getUUID()); - if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1)) return; - } - - dPlot.setPlotOwner(null); - dPlot.setLastActivity(true); - dPlot.setStatus(Status.unclaimed); - dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); + if (plot.getPlotType() == PlotType.TUTORIAL) return; + Plot dPlot = (Plot) plot; + DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getID()); + for (Builder builder : dPlot.getPlotMembers()) dPlot.removePlotMember(builder); + + if (plot.getPlotOwner() != null) { + Cache.clearCache(plot.getPlotOwner().getUUID()); + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1)) return; } + + dPlot.setPlotOwner(null); + dPlot.setLastActivity(true); + dPlot.setStatus(Status.unclaimed); + dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); }).join(); } catch (CompletionException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!"), ex); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java index 18597f15..fc8ce00e 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java @@ -54,7 +54,7 @@ public enum Continent { Continent(String databaseEnum, String langPath) { this.databaseEnum = databaseEnum; - // although LangPath.Continent keys match the enum name, you cannot get the value without reflection + // you cannot get the value from the database enum without reflection this.langPath = langPath; } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java index f3042f6b..8ac7d3be 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java @@ -46,7 +46,7 @@ public static void init() throws ConfigNotImplementedException { configUtilInstance = new ConfigurationUtil(new ConfigurationUtil.ConfigFile[]{ new ConfigurationUtil.ConfigFile(Paths.get("config.yml"), 4.0, true), new ConfigurationUtil.ConfigFile(Paths.get("commands.yml"), 1.1, false), - new ConfigurationUtil.ConfigFile(Paths.get("items.yml"), 1.2, false) + new ConfigurationUtil.ConfigFile(Paths.get("items.yml"), 1.3, false) }); } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 265db6b1..340b4499 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -190,6 +190,11 @@ private Review() {} public static final String FEEDBACK = REVIEW_PREFIX + "feedback"; public static final String REVIEWER = REVIEW_PREFIX + "reviewer"; public static final String PLAYER_LANGUAGE = REVIEW_PREFIX + "player-language"; + public static final String NO_FEEDBACK = "no-feedback"; + public static final String ACCURACY_POINTS = "accuracy-points"; + public static final String BLOCK_PALETTE_POINTS = "block-palette-points"; + public static final String TOGGLE_POINTS = "toggle-points"; + public static final String TOTAL_POINTS = "total-points"; public static final class Criteria { private Criteria() {} @@ -199,10 +204,6 @@ private Criteria() {} public static final String ACCURACY_DESC = CRITERIA_PREFIX + "accuracy-desc"; public static final String BLOCK_PALETTE = CRITERIA_PREFIX + "block-palette"; public static final String BLOCK_PALETTE_DESC = CRITERIA_PREFIX + "block-palette-desc"; - public static final String DETAILING = CRITERIA_PREFIX + "detailing"; - public static final String DETAILING_DESC = CRITERIA_PREFIX + "detailing-desc"; - public static final String TECHNIQUE = CRITERIA_PREFIX + "technique"; - public static final String TECHNIQUE_DESC = CRITERIA_PREFIX + "technique-desc"; } } @@ -214,6 +215,8 @@ private Note() {} public static final String WONT_BE_ABLE_CONTINUE_BUILDING = NOTES + "wont-be-able-continue-building"; public static final String SCORE_WILL_BE_SPLIT = NOTES + "score-will-be-split"; public static final String PLAYER_HAS_TO_BE_ONLINE = NOTES + "player-has-to-be-online"; + public static final String OPTIONAL = NOTES + "optional"; + public static final String REQUIRED = NOTES + "required"; public static final class Action { private Action() {} @@ -240,6 +243,7 @@ private Action() {} public static final String CLICK_TO_PLAY_WITH_FRIENDS = ACTION_PREFIX + "click-to-play-with-friends"; public static final String TUTORIAL_SHOW_STAGES = ACTION_PREFIX + "tutorial-show-stages"; public static final String CLICK_TO_OPEN_PLOTS_MENUE = ACTION_PREFIX + "click-to-open-plots-menu"; + public static final String CLICK_TO_TOGGLE = ACTION_PREFIX + "click-to-toggle"; } } @@ -271,7 +275,10 @@ private Info() {} public static final String REMOVED_PLOT_MEMBER = INFO_PREFIX + "removed-plot-member"; public static final String LEFT_PLOT = INFO_PREFIX + "left-plot"; public static final String PLOT_WILL_GET_ABANDONED = INFO_PREFIX + "plot-will-get-abandoned-warning"; - public static final String PLOT_WILL_GET_REJECTED = INFO_PREFIX + "plot-will-get-rejected-warning"; + public static final String PLOT_WILL_BE_REJECTED = INFO_PREFIX + "plot-will-be-rejected"; + public static final String PLOT_WILL_BE_ACCEPTED = INFO_PREFIX + "plot-will-be-accepted"; + public static final String PLOTS_REVIEWED_SINGULAR = INFO_PREFIX + "plots-reviewed-singular"; + public static final String PLOTS_REVIEWED_PLURAL = INFO_PREFIX + "plots-reviewed-plural"; public static final String SAVING_PLOT = INFO_PREFIX + "saving-plot"; public static final String CREATING_PLOT = INFO_PREFIX + "creating-plot"; public static final String CREATED_NEW_PLOT = INFO_PREFIX + "created-new-plot"; @@ -326,6 +333,7 @@ private Error() {} public static final String CHAT_INPUT_EXPIRED = ERROR_PREFIX + "chat-input-expired"; public static final String TUTORIAL_DISABLED = ERROR_PREFIX + "tutorial-disabled"; public static final String TUTORIAL_ALREADY_RUNNING = ERROR_PREFIX + "tutorial-already-running"; + public static final String REVIEW_NOT_FOUND = ERROR_PREFIX + "review-not-found"; } } @@ -420,5 +428,6 @@ private Database() {} public static final String CITY_PROJECT = DATABASE_PREFIX + "city-project"; public static final String COUNTRY = DATABASE_PREFIX + "country"; public static final String DIFFICULTY = DATABASE_PREFIX + "difficulty"; + public static final String STATUS = DATABASE_PREFIX + "status"; } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java index a8ca94d2..b2d16235 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java @@ -39,14 +39,14 @@ public class LangUtil extends LanguageUtil { public static void init() { if (langUtilInstance != null) return; LangLibAPI.register(PlotSystem.getPlugin(), new LanguageFile[]{ - new LanguageFile(Language.en_GB, 2.4), - new LanguageFile(Language.de_DE, 2.4, "de_AT", "de_CH"), - new LanguageFile(Language.fr_FR, 2.4, "fr_CA"), - new LanguageFile(Language.pt_PT, 2.4, "pt_BR"), - new LanguageFile(Language.ko_KR, 2.4), - new LanguageFile(Language.ru_RU, 2.4, "ba_RU", "tt_RU"), - new LanguageFile(Language.zh_CN, 2.4), - new LanguageFile(Language.zh_TW, 2.4, "zh_HK"), + new LanguageFile(Language.en_GB, 2.5), + new LanguageFile(Language.de_DE, 2.5, "de_AT", "de_CH"), + new LanguageFile(Language.fr_FR, 2.5, "fr_CA"), + new LanguageFile(Language.pt_PT, 2.5, "pt_BR"), + new LanguageFile(Language.ko_KR, 2.5), + new LanguageFile(Language.ru_RU, 2.5, "ba_RU", "tt_RU"), + new LanguageFile(Language.zh_CN, 2.5), + new LanguageFile(Language.zh_TW, 2.5, "zh_HK"), }); langUtilInstance = new LangUtil(); } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index 47e5e409..aa9d1bbe 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -42,6 +42,12 @@ public enum BaseItems { PLOT_TYPE("plot-type"), PLOT_FOCUS_MODE("plot-focus-mode"), PLOT_CITY_INSPIRATION_MODE("plot-city-inspiration-mode"), + PLOT_SLOT_EMPTY("plot-slot-empty"), + PLOT_SLOT_FILLED("plot-slot-filled"), + PLOT_SUBMIT("plot-submit"), + PLOT_UNDO_SUBMIT("plot-undo-submit"), + PLOT_ABANDON("plot-abandon"), + PLOT_TELEPORT("plot-teleport"), MENU_ERROR("menu-error"), MENU_CLOSE("menu-close"), @@ -63,9 +69,14 @@ public enum BaseItems { REVIEW_CANCEL("review-cancel"), REVIEW_INFO("review-info"), REVIEW_INFO_PLOT("review-info-plot"), - REVIEW_TOGGLE_DISABLED("review-toggle-disabled"), + REVIEW_TOGGLE_OPTIONAL("review-toggle-optional"), + REVIEW_TOGGLE_REQUIRED("review-toggle-required"), REVIEW_TOGGLE_CHECKED("review-toggle-checked"), + REVIEW_FEEDBACK("review-feedback"), + REVIEW_SCORE("review-score"), + BUILDER_UTILITIES("builder-utilities"), + FILTER_ITEM("filter-item"), SETTINGS_ITEM("settings-item"), RANDOM_PLOT_ITEM("random-plot-item"), diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java index d2dd3f09..63deab45 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java @@ -91,7 +91,7 @@ public static ItemStack loadingItem(ItemStack itemStack, Player player) { } public static ItemStack filterItem(Player langPlayer) { - return new ItemBuilder(Material.HOPPER, 1) + return new ItemBuilder(BaseItems.FILTER_ITEM.getItem()) .setName(text(LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.FILTER_BY_COUNTRY), GOLD, BOLD)) .build(); } diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml index 7d3b0777..96bf7fad 100644 --- a/src/main/resources/items.yml +++ b/src/main/resources/items.yml @@ -27,6 +27,25 @@ plot-focus-mode: plot-city-inspiration-mode: material: head(38094) modelId: '' +plot-slot-empty: + material: MAP + modelId: '' +plot-slot-filled: + material: MAP_FILLED + modelId: '' +plot-submit: + material: NAME_TAG + modelId: '' +plot-undo-submit: + material: FIRE_CHARGE + modelId: '' +plot-abandon: + material: BARRIER + modelId: '' +plot-teleport: + material: COMPASS + modelId: '' + menu-error: material: BARRIER @@ -56,9 +75,12 @@ review-accuracy: review-block-palette: material: PAINTING modelId: '' -review-toggle-disabled: +review-toggle-optional: material: FIREWORK_STAR modelId: '' +review-toggle-required: + material: FIRE_CHARGE + modelId: '' review-toggle-checked: material: SLIME_BALL modelId: '' @@ -92,12 +114,24 @@ review-info: review-info-plot: material: MAP modelId: '' +review-feedback: + material: WRITABLE_BOOK + modelId: '' +review-score: + material: NETHER_STAR + modelId: '' +builder-utilities: + material: GOLDEN_AXE + modelId: '' +filter-item: + material: HOPPER + modelId: '' settings-item: material: COMPARATOR modelId: '' random-plot-item: - material: COMPARATOR + material: MAGMA_CREAM modelId: '' difficulty-automatic: @@ -122,4 +156,4 @@ language-item: modelId: '' # NOTE: Do not change -config-version: 1.2 \ No newline at end of file +config-version: 1.3 \ No newline at end of file diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index 5557dca1..3a4d56cf 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -163,10 +163,6 @@ review: accuracy-desc: "Wie akkurat ist das Gebäude?%newline%%newline%- Sieht aus wie in RL%newline%- Korrekte Umrisse%newline%- Korrekte Höhen%newline%- Ist vollständig" block-palette: "Block-Palette" block-palette-desc: "Wie viele und wie kreativ werden verschiedene Blöcke verwendet?%newline%%newline%- Wahl der Blockfarben/Texturen%newline%- Randomisierte Blöcke" - detailing: "Detaillierung" - detailing-desc: "Wie viele Details hat das Gebäude?%newline%%newline%- Dachdetails%newline%- Details an den Fassaden%newline%- Köpfe und Banner" - technique: "Technik" - technique-desc: "Welche Bautechniken wurden verwendet und wie kreativ sind sie?%newline%%newline%- World-Edit%newline%- Spezialblöcke" #----------------------------------------------------- #| Notes #----------------------------------------------------- @@ -223,7 +219,6 @@ message: removed-plot-member: "§a§6{0}§a wurde vom Plot entfernt §6#{1}§a!" left-plot: "§aVerlasse Plot §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lWARNING: §cDieser Plot wird automatisch aufgelassen werden!" - plot-will-get-rejected-warning: "§c§lWARNING: §cDieser Plot wird abgelehnt werden!" saving-plot: "§aSpeichere Plot..." creating-plot: "§aErstelle neuen Plot..." created-new-plot: "§aEin neuer Plot§a wurde für §6{0}§a erstellt!" @@ -414,4 +409,4 @@ database: hard: name: 'Hard' #NOTE: Do not change -config-version: 2.4 +config-version: 2.5 diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 8ac09125..344c4fe4 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -158,15 +158,16 @@ review: feedback: "Feedback" reviewer: "Reviewer" player-language: "Player Language" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "Accuracy" accuracy-desc: "How accurate is the building?%newline%%newline%- Looks like in RL%newline%- Correct outlines%newline%- Correct height%newline%- Is completed" block-palette: "Block Palette" block-palette-desc: "How many different blocks are used and how creative are they?%newline%%newline%- Choice of blocks colours/textures%newline%- Random blocks" - detailing: "Detailing" - detailing-desc: "How much detail does the building have?%newline%%newline%- Roof details%newline%- Details on the facades%newline%- Heads and Banners" - technique: "Technique" - technique-desc: "What building techniques have been used and how creative are they?%newline%%newline%- World-Edit%newline%- Special Blocks" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -176,6 +177,8 @@ note: wont-be-able-continue-building: "You wont be able to continue building on this plot!" score-will-be-split: "Score will be split between all members when reviewed!" player-has-to-be-online: "The player has to be online!" + optional: "Optional" + required: "Required" action: read: 'Read' read-more: 'Read More' @@ -199,6 +202,7 @@ note: click-to-play-with-friends: "§7Want to play with your friends? §6Click Here..." tutorial-show-stages: 'Show Stages' click-to-open-plots-menu: 'Click to open the plots menu...' + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -223,7 +227,10 @@ message: removed-plot-member: "§aRemoved §6{0}§a from plot §6#{1}§a!" left-plot: "§aLeft plot §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lWARNING: §cThis plot will automatically get abandoned!" - plot-will-get-rejected-warning: "§c§lWARNING: §cThis plot will get rejected!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§aSaving plot..." creating-plot: "§aCreating new plot..." created-new-plot: "§aCreated new plot§a for §6{0}§a!" @@ -271,6 +278,7 @@ message: chat-input-expired: "The chat input has expired." tutorial-disabled: 'Tutorials are disabled on this server.' tutorial-already-running: "You already have a tutorial running! Complete it before starting a new one." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Daily" @@ -413,5 +421,15 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + # NOTE: Do not change -config-version: 2.4 +config-version: 2.5 diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index 9b1b3a06..55c6fc7b 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -162,10 +162,6 @@ review: accuracy-desc: "Quelle est la précision du bâtiment?%newline%%newline%- Ressemble à RL%newline%- Contours corrects%newline%- Hauteur correcte%newline%- Est terminé" block-palette: "palette de blocs" block-palette-desc: "Combien de blocs différents sont utilisés et à quel point sont-ils créatifs?%newline%%newline%- Choix des couleurs/textures des blocs%newline%- Blocs aléatoires" - detailing: "Détail" - detailing-desc: "Combien de détails le bâtiment a-t-il?%newline%%newline%- Détails du toit%newline%- Détails sur les façades%newline%- Têtes et bannières" - technique: "Technique" - technique-desc: "Quelles techniques de construction ont été utilisées et à quel point sont-elles créatives?%newline%%newline%- World-Edit%newline%- Blocs spéciaux" #----------------------------------------------------- #| Notes #----------------------------------------------------- @@ -222,7 +218,7 @@ message: removed-plot-member: "§aSupprimé §6{0}§a du tracé §6#{1}§a!" left-plot: "§aTracé de gauche §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lATTENTION: §cCette parcelle sera automatiquement abandonnée!" - plot-will-get-rejected-warning: "§c§lATTENTION: §cCette parcelle sera rejetée!" + saving-plot: "§aEnregistrement de l'intrigue..." creating-plot: "§aCréation d'un nouveau tracé..." created-new-plot: "§aCréé un nouveau tracé§a pour §6{0}§a!" @@ -413,4 +409,4 @@ database: hard: name: 'Hard' #NOTE: Do not change -config-version: 2.4 \ No newline at end of file +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index c33c6716..c4dde658 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -162,10 +162,6 @@ review: accuracy-desc: "얼마나 정확하게 건축되었나요?%newline%%newline%- 현실과의 유사성%newline%- 올바른 외곽선%newline%- 올바른 높이%newline%- 완성도" block-palette: "블록 선정" block-palette-desc: "사용된 블록이 얼마나 다양하고 창의적인가요?%newline%%newline%- 사용된 블록의 색깔/질감%newline%- 블록의 무작위성" - detailing: "디테일" - detailing-desc: "건물의 디테일이 얼마나 잘 구현되어있나요?%newline%%newline%- 지붕 디테일%newline%- 건물 정면 디테일%newline%- 머리와 현수막의 사용" - technique: "기법" - technique-desc: "사용된 건축 기법들은 무엇이고 얼마나 창의적인가요?%newline%%newline%- 월드에딧%newline%- 특수 블록" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -222,7 +218,6 @@ message: removed-plot-member: "§6{0}§a님을 플롯 §6#{1}§a에서 제외하였습니다!" left-plot: "§a플롯 §6#{0}§a을 나갔습니다!" plot-will-get-abandoned-warning: "§c§l경고: §c이 플롯은 자동으로 버려질 것입니다!" - plot-will-get-rejected-warning: "§c§l경고: §c이 플롯은 거절될 것입니다!" saving-plot: "§a플롯 저장 중..." creating-plot: "§a새로운 플롯 생성 중..." created-new-plot: "§6{0}§a님의 플롯을 생성하였습니다!" @@ -413,4 +408,4 @@ database: hard: name: 'Hard' # NOTE: Do not change -config-version: 2.4 +config-version: 2.5 diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index 2df30762..1eeab53b 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -162,10 +162,6 @@ review: accuracy-desc: "Quão precisa é a construção?%newline%%newline%- Pare como na vida real%newline%- MArcação correta%newline%- Altura correta%newline%- Completa" block-palette: "Paleta de Blocos" block-palette-desc: "Quantos blocos diferentes são usados e quão criativos eles são?%newline%%newline%- Escolha de cores/texturas de blocos%newline%- Blocos aleatórios" - detailing: "Detalhamento" - detailing-desc: "Quão detalhada é a construção?%newline%%newline%- Detalhes do telhado%newline%- Detalhes na Fachada%newline%- Cabeças e estandartes" - technique: "Técnica" - technique-desc: "Quais técnicas de construção foram utilizadas e quão criativas elas são?%newline%%newline%- World-Edit%newline%- Blocos especiais" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -222,7 +218,6 @@ message: removed-plot-member: "§aRemovido §6{0}§a do terreno §6#{1}§a!" left-plot: "§aDeixou o terreno §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lAVISO: §cEsse terreno vai ser abandonado automaticamente!" - plot-will-get-rejected-warning: "§c§lAVISO: §cEsse terreno vai ser rejeitado!" saving-plot: "§aSalvando terreno..." creating-plot: "§aCriando um novo terreno..." created-new-plot: "§aCriou novo terreno para §6{0}§a!" @@ -413,4 +408,4 @@ database: hard: name: 'Hard' # NOTE: Do not change -config-version: 2.4 +config-version: 2.5 diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index bc5ae528..eb4c3191 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -162,10 +162,6 @@ review: accuracy-desc: "Насколько точно исполнено здание?%newline%%newline%- Выглядит как в настоящей жизни%newline%- Правильные контуры%newline%- Правильная высота%newline%- Полностью завершен" block-palette: "Палитра Блоков" block-palette-desc: "Сколько различных блоков использовано и насколько они креативны??%newline%%newline%- Выбор цвета/текстуры блоков%newline%- Случайные блоки’" - detailing: "Детализация" - detailing-desc: "Насколько детализировано здание?%newline%%newline%- Детали крыши%newline%- Детали фасада%newline%- Головы и Баннеры" - technique: "Техника" - technique-desc: "Какие строительные техники были применены и насколько они креативны?%newline%%newline%- World-Edit%newline%- Специальные Блоки" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -222,7 +218,6 @@ message: removed-plot-member: "§6{0}§a §aудалён из участка§6#{1}§a!" left-plot: "§aПокинул участок §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lВНИМАНИЕ: §cЭтот участок будет автоматически сброшен!" - plot-will-get-rejected-warning: "§c§lВНИМАНИЕ: §cЭтот участок будет отклонён!!" saving-plot: "§aСохранение участка..." creating-plot: "§aСоздание нового участка..." created-new-plot: "§aСоздан новый участок§a для §6{0}§a!" @@ -413,4 +408,4 @@ database: hard: name: 'Hard' # NOTE: Do not change -config-version: 2.4 +config-version: 2.5 diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 56cf984a..9aae80ee 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -163,10 +163,6 @@ review: accuracy-desc: "建筑的精确度如何? %newline%%newline%- 看起来像在真实世界%newline%- 正确的轮廓%newline%- 正确的高度%newline%- 完成了" block-palette: "方块用色" block-palette-desc: "使用了多少个不同的方块,它们的创意如何? %newline%%newline%- 方块颜色/材质的选择%newline%- 随机方块" - detailing: "细节" - detailing-desc: "建筑有多少细节? %newline%%newline%- 屋顶细节%newline%- 外墙上的细节%newline%- 头颅和旗帜" - technique: "技巧" - technique-desc: "使用了什么建筑技巧,它们的创意如何? %newline%%newline%- World-Edit%newline%- 特殊方块" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -223,7 +219,6 @@ message: removed-plot-member: "§a从建地 §6#{1}§a 移除 §6{0}§a! " left-plot: "§a剩余建地 §6#{0}§a! " plot-will-get-abandoned-warning: "§c§l警告: §c此建地将自动废弃! " - plot-will-get-rejected-warning: "§c§l警告: §c此建地将被驳回! " saving-plot: "§a储存建地..." creating-plot: "§a创建新建地..." created-new-plot: "§a创建新建地§a 为 §6{0}§a! " @@ -414,4 +409,4 @@ database: hard: name: 'Hard' # NOTE: Do not change -config-version: 2.4 +config-version: 2.5 diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index 3043f779..fc7fb51c 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -162,10 +162,6 @@ review: accuracy-desc: "建築的精確度如何?%newline%%newline%- 看起來像在真實世界%newline%- 正確的輪廓%newline%- 正確的高度%newline%- 完成了" block-palette: "方塊用色" block-palette-desc: "使用了多少個不同的方塊,它們的創意如何?%newline%%newline%- 方塊顏色/紋理的選擇%newline%- 隨機方塊" - detailing: "細節" - detailing-desc: "建築有多少細節?%newline%%newline%- 屋頂細節%newline%- 立面上的細節%newline%- 頭顱和旗幟" - technique: "技巧" - technique-desc: "使用了什麼建築技巧,它們的創意如何?%newline%%newline%- World-Edit%newline%- 特殊方塊" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -222,7 +218,6 @@ message: removed-plot-member: "§a將§6{0}§a從建地§6#{1}§a中移除!" left-plot: "§a離開建地§6#{0}§a!" plot-will-get-abandoned-warning: "§c§l警告:§c此建地將自動被廢棄!" - plot-will-get-rejected-warning: "§c§l警告:§c此建地將被否決!" saving-plot: "§a儲存建地..." creating-plot: "§a建立新建地..." created-new-plot: "§a為§6{0}§a建立了新建地§a!" @@ -413,4 +408,4 @@ database: hard: name: 'Hard' # NOTE: Do not change -config-version: 2.4 +config-version: 2.5 From 5ec230482af6667bccddb05c41e59ff485718437 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 19 Apr 2025 16:08:49 +0200 Subject: [PATCH 071/175] fix invalid lang file, wrong item in items.yml and add TileDrops and MobLoot gamerules --- .../core/system/plot/generator/PlotWorldGenerator.java | 2 ++ src/main/resources/items.yml | 2 +- src/main/resources/lang/fr_FR.yml | 1 - 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java index 15e10d5f..2b4079d0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java @@ -98,6 +98,8 @@ protected void configureWorld() { bukkitWorld.setGameRule(GameRule.KEEP_INVENTORY, true); bukkitWorld.setGameRule(GameRule.DO_MOB_SPAWNING, false); bukkitWorld.setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false); + bukkitWorld.setGameRule(GameRule.DO_TILE_DROPS, false); + bukkitWorld.setGameRule(GameRule.DO_MOB_LOOT, false); // Configure multiverse world mvWorld.setAllowFlight(true); diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml index 96bf7fad..2ca7ca3b 100644 --- a/src/main/resources/items.yml +++ b/src/main/resources/items.yml @@ -31,7 +31,7 @@ plot-slot-empty: material: MAP modelId: '' plot-slot-filled: - material: MAP_FILLED + material: FILLED_MAP modelId: '' plot-submit: material: NAME_TAG diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index 55c6fc7b..82e9ee13 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -218,7 +218,6 @@ message: removed-plot-member: "§aSupprimé §6{0}§a du tracé §6#{1}§a!" left-plot: "§aTracé de gauche §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lATTENTION: §cCette parcelle sera automatiquement abandonnée!" - saving-plot: "§aEnregistrement de l'intrigue..." creating-plot: "§aCréation d'un nouveau tracé..." created-new-plot: "§aCréé un nouveau tracé§a pour §6{0}§a!" From c97d1bf049ca550e51278e1ffb2551e9a6d818fd Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 19 Apr 2025 16:35:04 +0200 Subject: [PATCH 072/175] close menu before generating random plot --- .../plotsystem/core/menus/companion/CityProjectMenu.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 0a17b88f..b2d05d89 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -140,6 +140,8 @@ public static boolean generateRandomPlot(Player player, @NotNull List Date: Sat, 19 Apr 2025 16:44:33 +0200 Subject: [PATCH 073/175] remove # in front of player name at undid-review --- .../core/menus/companion/CityProjectMenu.java | 21 ++++++++----------- src/main/resources/lang/de_DE.yml | 2 +- src/main/resources/lang/en_GB.yml | 2 +- src/main/resources/lang/fr_FR.yml | 2 +- src/main/resources/lang/pt_PT.yml | 2 +- src/main/resources/lang/ru_RU.yml | 2 +- src/main/resources/lang/zh_CN.yml | 2 +- src/main/resources/lang/zh_TW.yml | 2 +- 8 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index b2d05d89..0192396f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -153,18 +153,15 @@ public static boolean generateRandomPlot(Player player, @NotNull List getValidCityProjects(PlotDifficulty selectedPlotDifficulty, Player player, Country country) { return DataProvider.CITY_PROJECT.getByCountryCode(country.getCode(), true).stream().filter(test -> { - if (test instanceof CityProject project) { - var pd = selectedPlotDifficulty; - try { - if (pd == null) pd = Plot.getPlotDifficultyForBuilder(project, Builder.byUUID(player.getUniqueId())).get(); - if (pd == null) pd = PlotDifficulty.EASY; - - return project.isVisible() && !DataProvider.PLOT.getPlots(project, pd, Status.unclaimed).isEmpty(); - } catch (ExecutionException | InterruptedException e) { - sqlError(player, e); - } - } else { - return false; + if (!(test instanceof CityProject project)) return false; + var pd = selectedPlotDifficulty; + try { + if (pd == null) pd = Plot.getPlotDifficultyForBuilder(project, Builder.byUUID(player.getUniqueId())).get(); + if (pd == null) pd = PlotDifficulty.EASY; + + return project.isVisible() && !DataProvider.PLOT.getPlots(project, pd, Status.unclaimed).isEmpty(); + } catch (ExecutionException | InterruptedException e) { + sqlError(player, e); } return false; }).toList(); diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index 3a4d56cf..c3688210 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -207,7 +207,7 @@ message: plot-marked-as-reviewed: "§aPlot §6#{0}§a von §6{1}§a wurde als geprüft markiert!" plot-rejected: "§aPlot §6#{0}§a von §6{1}§a wurde abgelehnt!" undid-submission: "§aDie Einreichung des Plots §6#{0}§a wurde rückgängig gemacht!" - undid-review: "§aDie Bewertung des Plots §6#{0}§a von §6#{1}§a wurde rückgängig gemacht!" + undid-review: "§aDie Bewertung des Plots §6#{0}§a von §6{1}§a wurde rückgängig gemacht!" reviewed-plot: "§aDein Plot §6#{0}§a wurde bewertet!" unreviewed-plot: "§aEs gibt §6{0}§a unbewerteten Plot!" unreviewed-plots: "§aEs gibt §6{0}§a unbewertete Plots!" diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 344c4fe4..1a31bca9 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -215,7 +215,7 @@ message: plot-marked-as-reviewed: "§aPlot §6#{0}§a by §6{1}§a has been marked as reviewed!" plot-rejected: "§aPlot §6#{0}§a by §6{1}§a has been rejected!" undid-submission: "§aUndid submission of plot §6#{0}§a!" - undid-review: "§aUndid review of plot §6#{0}§a by §6#{1}§a!" + undid-review: "§aUndid review of plot §6#{0}§a by §6{1}§a!" reviewed-plot: "§aYour plot §6#{0}§a has been reviewed!" unreviewed-plot: "§aThere is §6{0}§a unreviewed plot!" unreviewed-plots: "§aThere are §6{0}§a unreviewed plots!" diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index 82e9ee13..aed69477 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -206,7 +206,7 @@ message: plot-marked-as-reviewed: "§aLe terrain §6#{0}§a par §6{1}§a a été marqué comme révisé!" plot-rejected: "§aLe tracé §6#{0}§a par §6{1}§a a été rejeté!" undid-submission: "§aUndid soumission du complot §6#{0}§a!" - undid-review: "§aChangement les commentaires de la parcelle§6#{0}§a par §6#{1}§a!" + undid-review: "§aChangement les commentaires de la parcelle§6#{0}§a par §6{1}§a!" reviewed-plot: "§aVotre parcelle §6#{0}§a a été revue!" unreviewed-plot: "§aIl y a §6{0}§a un complot non révisé!" unreviewed-plots: "§aIl y a §6{0}§a des parcelles non revues!" diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index 1eeab53b..f830043e 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -206,7 +206,7 @@ message: plot-marked-as-reviewed: "§aTerreno §6#{0}§a por §6{1}§a foi marcado como avaliado!" plot-rejected: "§aTerreno §6#{0}§a por §6{1}§a foi rejeitado!Envie feedback usando §6/sendFeedback §a!" undid-submission: "§aEnvio do Terreno Desfeito §6#{0}§a!" - undid-review: "§aAvaliação do Terreno Desfeita §6#{0}§a por §6#{1}§a!" + undid-review: "§aAvaliação do Terreno Desfeita §6#{0}§a por §6{1}§a!" reviewed-plot: "§aSeu terreno §6#{0}§a foi avaliado!" unreviewed-plot: "§aExiste um §6{0}§a terreno não avaliado!" unreviewed-plots: "§aExistem §6{0}§a terrenos não avaliados!" diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index eb4c3191..c84b0727 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -206,7 +206,7 @@ message: plot-marked-as-reviewed: "§aУчасток §6#{0}§a построенный §6{1}§aбыл помечена как оценённый!!" plot-rejected: "§aУчасток §6#{0}§a построенный §6{1}§a был отклонен!" undid-submission: "§aОтмена отправки участка §6#{0}§a!" - undid-review: "§aОтмена оценки участка §6#{0}§a построенным §6#{1}§a!" + undid-review: "§aОтмена оценки участка §6#{0}§a построенным §6{1}§a!" reviewed-plot: "§aВаш участок §6#{0}§a был оценён!" unreviewed-plot: "§aЕсть §6{0}§a неоценённый участок!" unreviewed-plots: "§aЕсть §6{0}§a неоценённые участки!!" diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 9aae80ee..2a2819ec 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -207,7 +207,7 @@ message: plot-marked-as-reviewed: "§a §6{1}§a 的建地 §6#{0}§a 已标记供审核! " plot-rejected: "§a §6{1}§a 的建地 §6#{0}§a 已被驳回!" undid-submission: "§a尚未提交的建地 §6#{0}§a! " - undid-review: "§a尚未审核的建地 §6#{0}§a by §6#{1}§a! " + undid-review: "§a尚未审核的建地 §6#{0}§a by §6{1}§a! " reviewed-plot: "§a你的建地 §6#{0}§a 已被审核! " unreviewed-plot: "§a有 §6{0}§a 处尚未审核的建地! " unreviewed-plots: "§a有 §6{0}§a 处尚未审核的建地! " diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index fc7fb51c..3b41d8c2 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -206,7 +206,7 @@ message: plot-marked-as-reviewed: "§a§6{1}§a的建地§6#{0}§a已標記供審核!" plot-rejected: "§a§6{1}§a的建地§6#{0}§a已被否決!" undid-submission: "§a撤回了建地§6#{0}§a的提交!" - undid-review: "§a撤回了對§6#{1}§a建地§6#{0}§a的審核!" + undid-review: "§a撤回了對§6{1}§a建地§6#{0}§a的審核!" reviewed-plot: "§a你的建地§6#{0}§a已被審核!" unreviewed-plot: "§a有§6{0}§a處尚未審核的建地!" unreviewed-plots: "§a有§6{0}§a處尚未審核的建地!" From aebab69a08561f59933e257b32e5b1080e0c8ae7 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 19 Apr 2025 17:09:16 +0200 Subject: [PATCH 074/175] fix wrong uuid compare --- .../plotsystem/core/database/providers/BuildTeamProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 9b44dbf0..91db667b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -179,7 +179,7 @@ public boolean removeReviewer(int id, String reviewerUUID) { public List getReviewerCities(Builder builder) { List buildTeams = BUILD_TEAMS.stream().filter(b - -> b.getReviewers().stream().anyMatch(r -> r.getUUID() == builder.getUUID())).toList(); + -> b.getReviewers().stream().anyMatch(r -> r.getUUID().equals(builder.getUUID()))).toList(); List cities = new ArrayList<>(); for (BuildTeam buildTeam : buildTeams) { From 835280a96ac311de584f76df01dab08a924f2aba Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 19 Apr 2025 17:40:41 +0200 Subject: [PATCH 075/175] reduce complexity of submitReview() method by extracting code into separate methods --- .../menus/review/ReviewPlotTogglesMenu.java | 115 +++++++++--------- .../core/system/plot/utils/PlotUtils.java | 3 +- 2 files changed, 58 insertions(+), 60 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 9e379f87..b9375246 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -149,66 +149,10 @@ else if (!criteria.isOptional()) { Component reviewerConfirmationMessage; if (!isRejected) { - getMenuPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - try { - if (!PlotUtils.savePlotAsSchematic(plot)) { - getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); - } - } catch (IOException | WorldEditException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); - } - }); - - plot.setStatus(Status.completed); - - // Remove Plot from Owner - if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(plot), -1)) return; - - if (plot.getPlotMembers().isEmpty()) { - // Plot was made alone - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); - - // Builder gets 100% of score - if (!plot.getPlotOwner().addScore(totalRating)) return; - } else { - // Plot was made in a group - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), sb.toString())); - - // Score gets split between all participants - if (!plot.getPlotOwner().addScore(plot.getSharedScore())) return; - - for (Builder builder : plot.getPlotMembers()) { - // Score gets split between all participants - if (!builder.addScore(plot.getSharedScore())) return; - - // Remove Slot from Member - if (!builder.setSlot(builder.getSlot(plot), -1)) return; - } - } + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), getParticipantsString())); + if(!acceptPlot(totalRating)) return; } else { - if (!plot.getPlotMembers().isEmpty()) { - // Plot was made alone - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), plot.getPlotOwner().getName())); - } else { - // Plot was made in a group - StringBuilder sb = new StringBuilder(); - - for (int i = 0; i < plot.getPlotMembers().size(); i++) { - sb.append(i == plot.getPlotMembers().size() - 1 ? - plot.getPlotMembers().get(i).getName() : - plot.getPlotMembers().get(i).getName() + ", "); - } - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), sb.toString())); - } - + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), getParticipantsString())); PlotUtils.Actions.undoSubmit(plot); } @@ -232,6 +176,59 @@ else if (!criteria.isOptional()) { }); } + private String getParticipantsString() { + if (plot.getPlotMembers().isEmpty()) { + return plot.getPlotOwner().getName(); + } else { + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < plot.getPlotMembers().size(); i++) { + sb.append(i == plot.getPlotMembers().size() - 1 ? + plot.getPlotMembers().get(i).getName() : + plot.getPlotMembers().get(i).getName() + ", "); + } + return sb.toString(); + } + } + + private boolean acceptPlot(int totalRating) { + getMenuPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + try { + if (!PlotUtils.savePlotAsSchematic(plot)) { + getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); + PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); + } + } catch (IOException | WorldEditException ex) { + PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); + } + }); + + plot.setStatus(Status.completed); + + // Remove Plot from Owner + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(plot), -1)) return false; + + if (plot.getPlotMembers().isEmpty()) { + // Plot was made alone + // Builder gets 100% of score + return plot.getPlotOwner().addScore(totalRating); + } else { + // Plot was made in a group + // Score gets split between all participants + if (!plot.getPlotOwner().addScore(plot.getSharedScore())) return false; + + for (Builder builder : plot.getPlotMembers()) { + // Score gets split between all participants + if (!builder.addScore(plot.getSharedScore())) return false; + + // Remove Slot from Member + if (!builder.setSlot(builder.getSlot(plot), -1)) return false; + } + } + return true; + } + private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { Player p = getMenuPlayer(); ItemStack baseItem = checked diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 2637eb1c..8cf77cfc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -237,7 +237,8 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException } // Set Completed Schematic - DataProvider.PLOT.setCompletedSchematic(plot.getID(), outputStream.toByteArray()); + boolean successful = DataProvider.PLOT.setCompletedSchematic(plot.getID(), outputStream.toByteArray()); + if (!successful) return false; // If plot was created in a void world, copy the result to the city world if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE && plot.getVersion() >= 3) { From 197461a727b4da5ba409abff8a10dea0b092d9b0 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 19 Apr 2025 22:12:42 +0200 Subject: [PATCH 076/175] add plot version legacy threshold and prevent loading or modifying legacy plots --- .../commands/plot/CMD_Plot_Abandon.java | 10 ++++++-- .../commands/plot/CMD_Plot_Members.java | 6 +++++ .../commands/plot/CMD_Plot_Submit.java | 9 +++++-- .../commands/plot/CMD_Plot_Teleport.java | 24 ++++++++++++------- .../commands/plot/CMD_Plot_UndoSubmit.java | 9 +++++++ .../commands/review/CMD_EditFeedback.java | 6 +++++ .../commands/review/CMD_UndoReview.java | 6 +++++ .../core/menus/PlayerPlotsMenu.java | 16 ++++++++++--- .../core/system/plot/AbstractPlot.java | 3 ++- .../core/system/plot/utils/PlotUtils.java | 6 ++--- .../plotsystem/utils/io/LangPaths.java | 3 +++ src/main/resources/lang/en_GB.yml | 3 +++ 12 files changed, 82 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java index 8c302eb1..1cb48d46 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java @@ -36,6 +36,7 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -75,12 +76,17 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); return; } + if (!Utils.isOwnerOrReviewer(sender, player, plot)) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); + return; + } if (plot.getStatus() != Status.unfinished) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_ABANDON_UNFINISHED_PLOTS))); return; } - if (!Utils.isOwnerOrReviewer(sender, player, plot)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); + + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java index 84570334..0c752761 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java @@ -35,6 +35,8 @@ import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -83,6 +85,10 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("You don't have permission to manage this plot's members!")); return; } + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); + return; + } new PlotMemberMenu(plot, player); }); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java index e105f143..e93a3284 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java @@ -36,6 +36,7 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -56,7 +57,7 @@ public CMD_Plot_Submit(BaseCommand baseCommand) { @Override public void onCommand(CommandSender sender, String[] args) { Player player = getPlayer(sender); - if (getPlayer(sender) == null) { + if (player == null) { Bukkit.getConsoleSender().sendMessage(text("This command can only be used as a player!", NamedTextColor.RED)); return; } @@ -65,7 +66,7 @@ public void onCommand(CommandSender sender, String[] args) { Plot plot; if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - } else if (player != null && PlotUtils.isPlotWorld(player.getWorld())) { + } else if (PlotUtils.isPlotWorld(player.getWorld())) { AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished); if (!(p instanceof Plot)) { sendInfo(sender); @@ -85,6 +86,10 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); return; } + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); + return; + } if (plot.getStatus() != Status.unfinished) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_SUBMIT_UNFINISHED_PLOTS))); return; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index a14c4146..d14cc257 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -31,11 +31,13 @@ import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; @@ -68,18 +70,24 @@ public void onCommand(CommandSender sender, String[] args) { CompletableFuture.runAsync(() -> { Plot plot = DataProvider.PLOT.getPlotById(plotID); + if (plot != null && plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_LOAD_LEGACY_PLOT))); + return; + } + if (plot == null || plot.getStatus() == Status.unclaimed) { - if (sender.hasPermission("plotsystem.admin") && plot != null) { - Builder builder = Builder.byUUID(player.getUniqueId()); - if (builder == null) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - return; - } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new DefaultPlotGenerator(plot, builder)); + if (!sender.hasPermission("plotsystem.admin") || plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } + + Builder builder = Builder.byUUID(player.getUniqueId()); + if (builder == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); return; } - sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new DefaultPlotGenerator(plot, builder)); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java index 17150862..b4a6bebc 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java @@ -36,6 +36,7 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -78,6 +79,14 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); return; } + if (!Utils.isOwnerOrReviewer(sender, player, plot)) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.PLAYER_IS_NOT_ALLOWED))); + return; + } + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); + return; + } if (plot.getStatus() != Status.unreviewed) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(langUtil.get(sender, LangPaths.Message.Error.CAN_ONLY_UNDO_SUBMISSIONS_UNREVIEWED_PLOTS))); return; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index 396156e4..33006f9e 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; @@ -69,6 +70,11 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); + return; + } + if (!plot.isReviewed() && !plot.isRejected()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_EITHER_UNCLAIMED_OR_UNREVIEWED))); return; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index ac04a569..b111ce4b 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.Utils; @@ -75,6 +76,11 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); + return; + } + Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 6b129dd9..1ee82d2b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -28,9 +28,11 @@ import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.core.system.review.PlotReview; +import com.alpsbte.plotsystem.core.system.review.ReviewRating; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; @@ -111,7 +113,10 @@ protected void setItemClickEventsAsync() { // Add click event for player plot items for (int i = 0; i < plotDisplayCount; i++) { int itemSlot = i; - getMenu().getSlot(9 + i).setClickHandler((clickPlayer, clickInformation) -> new PlotActionsMenu(clickPlayer, plots.get(itemSlot))); + getMenu().getSlot(9 + i).setClickHandler((clickPlayer, clickInformation) -> { + if (plots.get(itemSlot).getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) return; + new PlotActionsMenu(clickPlayer, plots.get(itemSlot)); + }); } // Set click event for back item @@ -158,13 +163,14 @@ private LoreBuilder getLore(Plot plot, Player p) { Optional review = plot.getLatestReview(); if (review.isPresent()) { + ReviewRating rating = review.get().getRating(); builder.emptyLine(); builder.addLines( text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.get().getRating().getAccuracyPoints())) + .append(Utils.ItemUtils.getColoredPointsComponent(rating.getAccuracyPoints())) .append(text("/", DARK_GRAY)).append(text("5", GREEN)), text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.BLOCK_PALETTE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.get().getRating().getBlockPalettePoints())) + .append(Utils.ItemUtils.getColoredPointsComponent(rating.getBlockPalettePoints())) .append(text("/", DARK_GRAY)).append(text("5", GREEN)) ); builder.emptyLine(); @@ -180,6 +186,10 @@ private LoreBuilder getLore(Plot plot, Player p) { builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.STATUS) + ": ", GRAY) .append(text(plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), WHITE))); + + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Note.LEGACY), RED).decoration(BOLD, true)); + } return builder; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 78f6703e..a8ea7b8f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -55,8 +55,9 @@ import static net.kyori.adventure.text.Component.text; public abstract class AbstractPlot { - public static final double PLOT_VERSION = 3; + public static final double PLOT_VERSION = 4; public static final ClipboardFormat CLIPBOARD_FORMAT = BuiltInClipboardFormat.FAST_V2; + public static final double LEGACY_VERSION_THRESHOLD = 3; private final int ID; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 8cf77cfc..df3ab800 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -164,7 +164,7 @@ public static boolean isPlayerOnPlot(@NotNull AbstractPlot plot, Player player) if (clipboard == null) return null; // No longer supported! - if (plot.getVersion() < 3) return null; + if (plot.getVersion() < 4) return null; return new CuboidRegion( clipboard.getMinimumPoint().withY(plot.getWorld().getPlotHeight()), @@ -196,7 +196,7 @@ public static boolean isPlotWorld(World world) { } public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException, WorldEditException { - if (plot.getVersion() < 3) { + if (plot.getVersion() < 4) { PlotSystem.getPlugin().getComponentLogger().error(text("Saving schematics of legacy plots is no longer allowed!")); return false; } @@ -241,7 +241,7 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException if (!successful) return false; // If plot was created in a void world, copy the result to the city world - if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE && plot.getVersion() >= 3) { + if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE) { AbstractPlotGenerator.pasteSchematic(null, outputStream.toByteArray(), new CityPlotWorld(plot), false); } return true; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 340b4499..4be835dd 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -217,6 +217,7 @@ private Note() {} public static final String PLAYER_HAS_TO_BE_ONLINE = NOTES + "player-has-to-be-online"; public static final String OPTIONAL = NOTES + "optional"; public static final String REQUIRED = NOTES + "required"; + public static final String LEGACY = NOTES + "legacy"; public static final class Action { private Action() {} @@ -309,6 +310,8 @@ private Error() {} public static final String CANNOT_UNDO_REVIEW = ERROR_PREFIX + "cannot-undo-review"; public static final String CANNOT_SEND_FEEDBACK = ERROR_PREFIX + "cannot-send-feedback"; public static final String CANNOT_REVIEW_OWN_PLOT = ERROR_PREFIX + "cannot-review-own-plot"; + public static final String CANNOT_MODIFY_LEGACY_PLOT = ERROR_PREFIX + "cannot-modify-legacy-plot"; + public static final String CANNOT_LOAD_LEGACY_PLOT = ERROR_PREFIX + "cannot-load-legacy-plot"; public static final String PLAYER_HAS_NO_PERMISSIONS = ERROR_PREFIX + "player-has-no-permissions"; public static final String PLAYER_HAS_NO_INVITATIONS = ERROR_PREFIX + "player-has-no-invitations"; diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 1a31bca9..6acf7f08 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -179,6 +179,7 @@ note: player-has-to-be-online: "The player has to be online!" optional: "Optional" required: "Required" + legacy: "LEGACY" action: read: 'Read' read-more: 'Read More' @@ -256,6 +257,8 @@ message: cannot-undo-review: "You cannot undo a review that you have not reviewed yourself!" cannot-send-feedback: "You cannot send feedback to a plot that you have not reviewed yourself!" cannot-review-own-plot: "You cannot review your own plot!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "You do not have permission to do this!" player-has-no-invitations: "You have no invitations!" player-is-not-allowed: "You are not allowed to do this!" From 89c5945914f1a38572045d9a3c40ea245a39ff5e Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 24 Apr 2025 04:02:10 +0200 Subject: [PATCH 077/175] extract rating logic to ReviewRating, add isChecked to review-toggle relation and fix lang issue --- .../database/providers/ReviewProvider.java | 52 +++++++++++----- .../core/menus/review/ReviewPlotMenu.java | 4 +- .../menus/review/ReviewPlotTogglesMenu.java | 45 +++----------- .../core/system/review/ReviewRating.java | 61 +++++++++++++++++-- .../plotsystem/utils/io/LangPaths.java | 10 +-- 5 files changed, 110 insertions(+), 62 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index fcf94d85..795eeff4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -81,8 +81,8 @@ public Optional getReview(int reviewId) { String ratingString = rs.getString(2); int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - List checkedCriteria = getCheckedToggleCriteria(reviewId); - ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); + HashMap toggleCriteria = getReviewToggleCriteria(reviewId); + ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } @@ -109,8 +109,8 @@ public Optional getLatestReview(int plotId) { String ratingString = rs.getString(2); int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - List checkedCriteria = getCheckedToggleCriteria(reviewId); - ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); + HashMap toggleCriteria = getReviewToggleCriteria(reviewId); + ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } @@ -137,8 +137,8 @@ public List getPlotReviewHistory(int plotId) { String ratingString = rs.getString(2); int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - List checkedCriteria = getCheckedToggleCriteria(reviewId); - ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, checkedCriteria); + HashMap toggleCriteria = getReviewToggleCriteria(reviewId); + ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); reviews.add(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } @@ -166,6 +166,7 @@ public boolean createReview(Plot plot, ReviewRating rating, int score, UUID revi boolean result = DataProvider.PLOT.setMcVersion(plot.getID()); if (!result) return false; + // Create Review String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) " + "VALUES (?, ?, ?, ?);"; try (Connection conn = DatabaseConnection.getConnection(); @@ -181,9 +182,15 @@ public boolean createReview(Plot plot, ReviewRating rating, int score, UUID revi if (!result) return false; - // create feedback notifications PlotReview review = plot.getLatestReview().orElseThrow(); + HashMap allToggles = rating.getAllToggles(); + for (ToggleCriteria criteria : allToggles.keySet()) { + if (!addReviewToggleCriteria(review.getReviewId(), criteria, allToggles.get(criteria))) + return false; + } + + // create feedback notifications createReviewNotification(review.getReviewId(), plot.getPlotOwner().getUUID()); for (Builder builder : plot.getPlotMembers()) { createReviewNotification(review.getReviewId(), builder.getUUID()); @@ -239,17 +246,21 @@ public Optional getToggleCriteria(String criteriaName) { return cachedToggleCriteria.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst(); } - public List getCheckedToggleCriteria(int reviewId) { - List toggleCriteriaList = new ArrayList<>(); - String query = "SELECT criteria_name FROM review_contains_toggle_criteria WHERE review_id = ?;"; + public List getBuildTeamToggleCriteria(int buildTeamId) { + return cachedBuildTeamToggleCriteria.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); + } + + public HashMap getReviewToggleCriteria(int reviewId) { + HashMap toggleCriteriaList = new HashMap<>(); + String query = "SELECT is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, reviewId); try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - toggleCriteriaList.add(getToggleCriteria(rs.getString(1)).orElseThrow()); - } + if (!rs.next()) return toggleCriteriaList; + boolean isChecked = rs.getBoolean(1); + toggleCriteriaList.put(getToggleCriteria(rs.getString(1)).orElseThrow(), isChecked); } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -257,8 +268,19 @@ public List getCheckedToggleCriteria(int reviewId) { return toggleCriteriaList; } - public List getBuildTeamToggleCriteria(int buildTeamId) { - return cachedBuildTeamToggleCriteria.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); + public boolean addReviewToggleCriteria(int reviewId, ToggleCriteria toggle, boolean isChecked) { + String query = "INSERT INTO review_contains_toggle_criteria (review_id, criteria_name, is_checked) " + + "VALUES (?, ?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, reviewId); + stmt.setString(2, toggle.getCriteriaName()); + stmt.setBoolean(3, isChecked); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; } public boolean removeCheckedToggleCriteria(int reviewId) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index 28f49e8f..ceb0538e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -27,6 +27,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; import com.alpsbte.plotsystem.core.menus.ReviewMenu; @@ -69,7 +70,8 @@ public ReviewPlotMenu(Player player, Plot plot, ReviewRating rating) { } public ReviewPlotMenu(Player player, Plot plot) { - this(player, plot, new ReviewRating(0, 0, List.of())); + this(player, plot, + new ReviewRating(0, 0, List.of(), DataProvider.REVIEW.getBuildTeamToggleCriteria(plot.getCityProject().getBuildTeam().getID()))); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index b9375246..35509eb4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -88,16 +88,9 @@ protected void setItemClickEventsAsync() { int finalI = i; getMenu().getSlot(9 + i).setClickHandler(((player, clickInformation) -> { ToggleCriteria clickedCriteria = buildTeamCriteria.get(finalI); - List checked = new ArrayList<>(rating.getCheckedToggles()); + boolean isChecked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(clickedCriteria.getCriteriaName())); + rating.setToggleCriteria(clickedCriteria, !isChecked); - boolean isChecked = checked.stream().anyMatch(t -> t.getCriteriaName().equals(clickedCriteria.getCriteriaName())); - if (isChecked) { - checked.remove(checked.stream().filter(t -> t.getCriteriaName().equals(clickedCriteria.getCriteriaName())).findFirst().orElseThrow()); - } else { - checked.add(clickedCriteria); - } - - rating.setCheckedToggles(checked); getMenu().getSlot(9 + finalI).setItem(getToggleItem(clickedCriteria, !isChecked)); getMenu().getSlot(50).setItem(getSubmitItem()); // update submit item @@ -120,22 +113,8 @@ protected Mask getMask() { } private void submitReview() { - // a plot is rejected if either of the point sliders are 0 - boolean isRejected = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0; - - int totalRating = rating.getAccuracyPoints() + rating.getBlockPalettePoints(); - int checkedCounter = 0; - for (ToggleCriteria criteria : buildTeamCriteria) { - boolean checked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); - if (checked) checkedCounter++; - else if (!criteria.isOptional()) { - isRejected = true; // a plot is also rejected if any of the required toggles are not checked - } - } - int checkedPoints = (int) Math.floor(((double) checkedCounter / buildTeamCriteria.size()) * 10); - totalRating += checkedPoints; - - if (totalRating <= 8) isRejected = true; // a plot is also rejected if the total rating is less than or equal to 8 + boolean isRejected = rating.isRejected(); + int totalRating = rating.getTotalRating(); double scoreMultiplier = DataProvider.DIFFICULTY.getDifficultyByEnum(plot.getDifficulty()).orElseThrow().getMultiplier(); double totalRatingWithMultiplier = totalRating * scoreMultiplier; @@ -156,14 +135,13 @@ else if (!criteria.isOptional()) { PlotUtils.Actions.undoSubmit(plot); } - boolean finalIsRejected = isRejected; Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { for (Player player : plot.getWorld().getBukkitWorld().getPlayers()) { player.teleport(Utils.getSpawnLocation()); } // Delete plot world after reviewing - if (!finalIsRejected && plot.getPlotType().hasOnePlotPerWorld()) + if (!isRejected && plot.getPlotType().hasOnePlotPerWorld()) plot.getWorld().deleteWorld(); getMenuPlayer().sendMessage(reviewerConfirmationMessage); @@ -250,22 +228,15 @@ private ItemStack getSubmitItem() { int totalToggles = buildTeamCriteria.size(); int checkedToggles = rating.getCheckedToggles().size(); double togglePercentage = (double) checkedToggles / totalToggles * 100; - int togglePoints = (int) Math.floor(togglePercentage / 10.0); - int totalPoints = rating.getAccuracyPoints() + rating.getBlockPalettePoints() + togglePoints; + int togglePoints = rating.getTogglePoints(); + int totalPoints = rating.getTotalRating(); String accuracyPointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ACCURACY_POINTS); String blockPalettePointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.BLOCK_PALETTE_POINTS); String togglesPointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.TOGGLE_POINTS); String totalPointsText = LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.TOTAL_POINTS); - boolean willReject = rating.getAccuracyPoints() == 0 || rating.getBlockPalettePoints() == 0 || totalPoints <= 8; - for (ToggleCriteria criteria : buildTeamCriteria) { - boolean checked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); - if (!checked && !criteria.isOptional()) { - willReject = true; // a plot is also rejected if any of the required toggles are not checked - break; - } - } + boolean willReject = rating.isRejected(); TextComponent resultNotice; if (willReject) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java index 60488bfb..7014a00a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java @@ -1,16 +1,35 @@ package com.alpsbte.plotsystem.core.system.review; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; public class ReviewRating { private int accuracyPoints; private int blockPalettePoints; - private List checkedToggles; + private final List checkedToggles; + private final List uncheckedToggles; - public ReviewRating(int accuracyPoints, int blockPalettePoints, List checkedToggles) { + public ReviewRating(int accuracyPoints, int blockPalettePoints, List checkedToggles, List uncheckedToggles) { this.accuracyPoints = accuracyPoints; this.blockPalettePoints = blockPalettePoints; this.checkedToggles = checkedToggles; + this.uncheckedToggles = uncheckedToggles; + } + + public ReviewRating(int accuracyPoints, int blockPalettePoints, HashMap toggles) { + this.accuracyPoints = accuracyPoints; + this.blockPalettePoints = blockPalettePoints; + + List checkedToggles = new ArrayList<>(); + List uncheckedToggles = new ArrayList<>(); + for (ToggleCriteria criteria : toggles.keySet()) { + if (toggles.get(criteria)) checkedToggles.add(criteria); + else uncheckedToggles.add(criteria); + } + + this.checkedToggles = checkedToggles; + this.uncheckedToggles = uncheckedToggles; } public int getAccuracyPoints() { @@ -32,9 +51,43 @@ public void setBlockPalettePoints(int points) { public List getCheckedToggles() { return checkedToggles; } + public HashMap getAllToggles() { + HashMap allToggles = new HashMap<>(); + for (ToggleCriteria checked : checkedToggles) allToggles.put(checked, true); + for (ToggleCriteria unchecked : uncheckedToggles) allToggles.put(unchecked, false); - public void setCheckedToggles(List checkedToggles) { - this.checkedToggles = checkedToggles; + return allToggles; + } + + public void setToggleCriteria(ToggleCriteria criteria, boolean isToggled) { + if (isToggled) { + checkedToggles.add(criteria); + uncheckedToggles.remove(criteria); + } else { + uncheckedToggles.add(criteria); + checkedToggles.remove(criteria); + } + } + + public int getTogglePoints() { + return (int) Math.floor(((double) checkedToggles.size() / (checkedToggles.size() + uncheckedToggles.size())) * 10); + } + + public int getTotalRating() { + return accuracyPoints + blockPalettePoints + getTogglePoints(); + } + + public boolean isRejected() { + // a plot is rejected if either of the point sliders are 0 + if (accuracyPoints == 0 || blockPalettePoints == 0) return true; + + for (ToggleCriteria unchecked : uncheckedToggles) { + // a plot is also rejected if any of the required toggles are not checked + if (!unchecked.isOptional()) return true; + } + + // a plot is also rejected if the total rating is less than or equal to 8 + return getTotalRating() <= 8; } public String getRatingDatabaseString() { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 4be835dd..5c8b6089 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -190,11 +190,11 @@ private Review() {} public static final String FEEDBACK = REVIEW_PREFIX + "feedback"; public static final String REVIEWER = REVIEW_PREFIX + "reviewer"; public static final String PLAYER_LANGUAGE = REVIEW_PREFIX + "player-language"; - public static final String NO_FEEDBACK = "no-feedback"; - public static final String ACCURACY_POINTS = "accuracy-points"; - public static final String BLOCK_PALETTE_POINTS = "block-palette-points"; - public static final String TOGGLE_POINTS = "toggle-points"; - public static final String TOTAL_POINTS = "total-points"; + public static final String NO_FEEDBACK = REVIEW_PREFIX + "no-feedback"; + public static final String ACCURACY_POINTS = REVIEW_PREFIX + "accuracy-points"; + public static final String BLOCK_PALETTE_POINTS = REVIEW_PREFIX + "block-palette-points"; + public static final String TOGGLE_POINTS = REVIEW_PREFIX + "toggle-points"; + public static final String TOTAL_POINTS = REVIEW_PREFIX + "total-points"; public static final class Criteria { private Criteria() {} From 902a1f20134a07d25b75579dcbc2c590f3f97174 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 24 Apr 2025 04:13:14 +0200 Subject: [PATCH 078/175] move ReviewMenu.java to review package --- .../com/alpsbte/plotsystem/commands/review/CMD_Review.java | 2 +- src/main/java/com/alpsbte/plotsystem/core/EventListener.java | 2 +- .../plotsystem/core/menus/{ => review}/ReviewMenu.java | 4 +++- .../alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java | 1 - src/main/java/com/alpsbte/plotsystem/utils/Utils.java | 2 +- 5 files changed, 6 insertions(+), 5 deletions(-) rename src/main/java/com/alpsbte/plotsystem/core/menus/{ => review}/ReviewMenu.java (98%) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 76a67423..95af1414 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -28,7 +28,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.menus.ReviewMenu; +import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.menus.review.ReviewPlotMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 9ebf4e8d..cf6fb85e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -26,7 +26,7 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.menus.ReviewMenu; +import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java similarity index 98% rename from src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java rename to src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index 30ef55bb..f60f8b85 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -22,11 +22,13 @@ * SOFTWARE. */ -package com.alpsbte.plotsystem.core.menus; +package com.alpsbte.plotsystem.core.menus.review; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.menus.AbstractPaginatedMenu; +import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.Plot; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index ceb0538e..a3ff2ae2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -30,7 +30,6 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; -import com.alpsbte.plotsystem.core.menus.ReviewMenu; import com.alpsbte.plotsystem.core.system.review.ReviewRating; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 36b8cdd5..985623c0 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -28,7 +28,7 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.menus.ReviewMenu; +import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.chat.ChatInput; From 7fe59cf357443cb8f02ddd11fdea91fe6bc0625f Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 24 Apr 2025 15:37:30 +0200 Subject: [PATCH 079/175] display toggle criteria in feedback menu and translate criteria --- .../database/providers/ReviewProvider.java | 9 ++-- .../plotsystem/core/menus/FeedbackMenu.java | 49 +++++++++++++++++-- .../core/menus/PlayerPlotsMenu.java | 9 +++- .../menus/review/ReviewPlotTogglesMenu.java | 2 +- .../core/system/review/ReviewRating.java | 22 ++++----- .../core/system/review/ToggleCriteria.java | 8 +++ .../com/alpsbte/plotsystem/utils/Utils.java | 6 ++- .../plotsystem/utils/io/LangPaths.java | 3 ++ src/main/resources/lang/en_GB.yml | 11 +++++ 9 files changed, 95 insertions(+), 24 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 795eeff4..24cc6980 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -252,15 +252,16 @@ public List getBuildTeamToggleCriteria(int buildTeamId) { public HashMap getReviewToggleCriteria(int reviewId) { HashMap toggleCriteriaList = new HashMap<>(); - String query = "SELECT is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; + String query = "SELECT criteria_name, is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, reviewId); try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return toggleCriteriaList; - boolean isChecked = rs.getBoolean(1); - toggleCriteriaList.put(getToggleCriteria(rs.getString(1)).orElseThrow(), isChecked); + while (rs.next()) { + boolean isChecked = rs.getBoolean(2); + toggleCriteriaList.put(getToggleCriteria(rs.getString(1)).orElseThrow(), isChecked); + } } } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 8209e1b3..73d882fb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.review.PlotReview; +import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; @@ -37,6 +38,7 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.Material; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; @@ -73,13 +75,17 @@ protected void setMenuItemsAsync() { .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY).append(text(plot.getTotalScore(), WHITE))) .emptyLine() .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getAccuracyPoints()) + .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getAccuracyPoints(), 5) .append(text("/", DARK_GRAY)) .append(text("5", GREEN)))) .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.BLOCK_PALETTE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getBlockPalettePoints())) + .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getBlockPalettePoints(), 5)) .append(text("/", DARK_GRAY)) .append(text("5", GREEN))) + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.TOGGLE_POINTS) + ": ", GRAY) + .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getTogglePoints(), 10)) + .append(text("/", DARK_GRAY)) + .append(text("10", GREEN))) .emptyLine() .addLine(plot.isRejected() ? text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.REJECTED), RED, BOLD) @@ -87,9 +93,12 @@ protected void setMenuItemsAsync() { .build()) .build()); + // Set toggles item + getMenu().getSlot(12).setItem(getTogglesItem()); + // Set feedback text item String feedbackText = review.getFeedback() == null ? LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.NO_FEEDBACK) : review.getFeedback(); - getMenu().getSlot(13).setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) + getMenu().getSlot(14).setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA, BOLD)) .setLore(new LoreBuilder() .addLine(feedbackText.replaceAll("//", " "), true) @@ -115,4 +124,36 @@ protected Mask getMask() { .pattern("111111111") .build(); } -} + + private ItemStack getTogglesItem() { + ItemBuilder itemBuilder = new ItemBuilder(BaseItems.REVIEW_TOGGLE_CHECKED.getItem()) + .setName(text("Toggle Criteria", AQUA, BOLD)); + + + int totalCheckCriteriaCount = review.getRating().getAllToggles().size(); + int checkedCount = review.getRating().getCheckedToggles().size(); + LoreBuilder loreBuilder = new LoreBuilder() + .addLine(text(checkedCount + "/" + totalCheckCriteriaCount, GRAY)); + + if (!review.getRating().getUncheckedToggles().isEmpty()) { + loreBuilder.emptyLine(); + loreBuilder.addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.CRITERIA_NOT_FULFILLED) + ":", RED, BOLD)); + for (ToggleCriteria unchecked : review.getRating().getUncheckedToggles()) { + loreBuilder.addLine(text("• ", DARK_GRAY).append(text(unchecked.getDisplayName(getMenuPlayer()), GRAY) + .append(unchecked.isOptional() + ? empty() + : text(" - ").append(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.REQUIRED), GOLD))))); + } + } + + if (!review.getRating().getCheckedToggles().isEmpty()) { + loreBuilder.emptyLine(); + loreBuilder.addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Note.CRITERIA_FULFILLED) + ":", GREEN, BOLD)); + for (ToggleCriteria unchecked : review.getRating().getCheckedToggles()) { + loreBuilder.addLine(text("• ", DARK_GRAY).append(text(unchecked.getDisplayName(getMenuPlayer()), GRAY))); + } + } + + return itemBuilder.setLore(loreBuilder.build()).build(); + } +} \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 1ee82d2b..7b657d6f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -167,12 +167,17 @@ private LoreBuilder getLore(Plot plot, Player p) { builder.emptyLine(); builder.addLines( text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(rating.getAccuracyPoints())) + .append(Utils.ItemUtils.getColoredPointsComponent(rating.getAccuracyPoints(), 5)) .append(text("/", DARK_GRAY)).append(text("5", GREEN)), text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.BLOCK_PALETTE) + ": ", GRAY) - .append(Utils.ItemUtils.getColoredPointsComponent(rating.getBlockPalettePoints())) + .append(Utils.ItemUtils.getColoredPointsComponent(rating.getBlockPalettePoints(), 5)) .append(text("/", DARK_GRAY)).append(text("5", GREEN)) ); + if (plot.getVersion() > AbstractPlot.LEGACY_VERSION_THRESHOLD) { + builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.TOGGLE_POINTS) + ": ", GRAY) + .append(Utils.ItemUtils.getColoredPointsComponent(rating.getTogglePoints(), 10)) + .append(text("/", DARK_GRAY)).append(text("10", GREEN))); + } builder.emptyLine(); builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.FEEDBACK) + ":", GRAY)); String feedback = review.get().getFeedback() == null diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 35509eb4..6590ca76 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -213,7 +213,7 @@ private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { ? BaseItems.REVIEW_TOGGLE_CHECKED.getItem() : criteria.isOptional() ? BaseItems.REVIEW_TOGGLE_OPTIONAL.getItem() : BaseItems.REVIEW_TOGGLE_REQUIRED.getItem(); return new ItemBuilder(baseItem) - .setName(text(criteria.getCriteriaName())) + .setName(text(criteria.getDisplayName(p))) .setLore(new LoreBuilder() .addLine(criteria.isOptional() ? text(LangUtil.getInstance().get(p, LangPaths.Note.OPTIONAL), NamedTextColor.GRAY).decoration(TextDecoration.BOLD, true) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java index 7014a00a..1807984a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java @@ -7,29 +7,24 @@ public class ReviewRating { private int accuracyPoints; private int blockPalettePoints; - private final List checkedToggles; - private final List uncheckedToggles; + private final List checkedToggles = new ArrayList<>(); + private final List uncheckedToggles = new ArrayList<>(); public ReviewRating(int accuracyPoints, int blockPalettePoints, List checkedToggles, List uncheckedToggles) { this.accuracyPoints = accuracyPoints; this.blockPalettePoints = blockPalettePoints; - this.checkedToggles = checkedToggles; - this.uncheckedToggles = uncheckedToggles; + this.checkedToggles.addAll(checkedToggles); + this.uncheckedToggles.addAll(uncheckedToggles); } public ReviewRating(int accuracyPoints, int blockPalettePoints, HashMap toggles) { this.accuracyPoints = accuracyPoints; this.blockPalettePoints = blockPalettePoints; - List checkedToggles = new ArrayList<>(); - List uncheckedToggles = new ArrayList<>(); for (ToggleCriteria criteria : toggles.keySet()) { - if (toggles.get(criteria)) checkedToggles.add(criteria); - else uncheckedToggles.add(criteria); + if (toggles.get(criteria)) this.checkedToggles.add(criteria); + else this.uncheckedToggles.add(criteria); } - - this.checkedToggles = checkedToggles; - this.uncheckedToggles = uncheckedToggles; } public int getAccuracyPoints() { @@ -51,6 +46,11 @@ public void setBlockPalettePoints(int points) { public List getCheckedToggles() { return checkedToggles; } + + public List getUncheckedToggles() { + return uncheckedToggles; + } + public HashMap getAllToggles() { HashMap allToggles = new HashMap<>(); for (ToggleCriteria checked : checkedToggles) allToggles.put(checked, true); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java index 56e02bd5..f48f5d3c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java @@ -1,5 +1,9 @@ package com.alpsbte.plotsystem.core.system.review; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import org.bukkit.entity.Player; + public class ToggleCriteria { private final String criteriaName; private final boolean isOptional; @@ -13,6 +17,10 @@ public String getCriteriaName() { return criteriaName; } + public String getDisplayName(Player player) { + return LangUtil.getInstance().get(player, LangPaths.Database.TOGGLE_CRITERIA + "." + criteriaName); + } + public boolean isOptional() { return isOptional; } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 985623c0..1831cc76 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -117,6 +117,7 @@ public static ItemStack getConfiguredItem(String material, Object customModelDat public static class SoundUtils { private SoundUtils() {} + public static final Sound TELEPORT_SOUND = Sound.ENTITY_ENDERMAN_TELEPORT; public static final Sound ERROR_SOUND = Sound.ENTITY_ITEM_BREAK; public static final Sound CREATE_PLOT_SOUND = Sound.ENTITY_EXPERIENCE_ORB_PICKUP; @@ -130,6 +131,7 @@ private SoundUtils() {} public static class ChatUtils { private ChatUtils() {} + public static void setChatFormat(String infoPrefix, String alertPrefix) { ChatUtils.infoPrefix = AlpsUtils.deserialize(infoPrefix); ChatUtils.alertPrefix = AlpsUtils.deserialize(alertPrefix); @@ -190,8 +192,8 @@ private ItemUtils() {} @Contract(pure = true) public static @NotNull String getActionFormat(String action) {return "§8§l> §c" + action;} - public static @NotNull Component getColoredPointsComponent(int points) { - return switch (points) { + public static @NotNull Component getColoredPointsComponent(int points, int maxPoints) { + return switch ((int) ((double) points / maxPoints * 5)) { case 0 -> text(points, GRAY); case 1 -> text(points, DARK_RED); case 2 -> text(points, GOLD); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 5c8b6089..86eb5a66 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -217,6 +217,8 @@ private Note() {} public static final String PLAYER_HAS_TO_BE_ONLINE = NOTES + "player-has-to-be-online"; public static final String OPTIONAL = NOTES + "optional"; public static final String REQUIRED = NOTES + "required"; + public static final String CRITERIA_FULFILLED = NOTES + "criteria-fulfilled"; + public static final String CRITERIA_NOT_FULFILLED = NOTES + "criteria-not-fulfilled"; public static final String LEGACY = NOTES + "legacy"; public static final class Action { @@ -432,5 +434,6 @@ private Database() {} public static final String COUNTRY = DATABASE_PREFIX + "country"; public static final String DIFFICULTY = DATABASE_PREFIX + "difficulty"; public static final String STATUS = DATABASE_PREFIX + "status"; + public static final String TOGGLE_CRITERIA = DATABASE_PREFIX + "toggle-criteria"; } } \ No newline at end of file diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 6acf7f08..07c2b7e0 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -179,6 +179,8 @@ note: player-has-to-be-online: "The player has to be online!" optional: "Optional" required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" legacy: "LEGACY" action: read: 'Read' @@ -433,6 +435,15 @@ database: name: 'Unreviewed' completed: name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' # NOTE: Do not change config-version: 2.5 From f04eee704d5230372a7c6a026277079250ee081b Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 24 Apr 2025 23:00:39 +0200 Subject: [PATCH 080/175] fix slot items always returning same references --- .../core/menus/companion/CityProjectMenu.java | 10 ++++------ .../core/menus/companion/CompanionMenu.java | 20 +++---------------- .../core/menus/companion/ContinentMenu.java | 10 ++++------ .../core/menus/companion/CountryMenu.java | 10 ++++------ .../core/menus/companion/FooterItem.java | 18 +++++++++++++++++ .../plotsystem/utils/items/BaseItems.java | 2 +- 6 files changed, 34 insertions(+), 36 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 0192396f..8937b437 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -68,9 +68,8 @@ protected void setPreviewItems() { getMenu().getSlot(0).setItem(MenuItems.getRandomItem(getMenuPlayer())); // Set random selection item getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); - for (Map.Entry entry : CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())).entrySet()) { - getMenu().getSlot(entry.getKey()).setItem(entry.getValue().item); - } + Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); // Set loading item for plots difficulty item getMenu().getSlot(6).setItem(CompanionMenu.getDifficultyItem(getMenuPlayer(), selectedPlotDifficulty)); @@ -115,9 +114,8 @@ protected void setItemClickEventsAsync() { clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); }); - for (Map.Entry entry : CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())).entrySet()) { - getMenu().getSlot(entry.getKey()).setClickHandler(entry.getValue().clickHandler); - } + Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); // Set click event for plots difficulty item getMenu().getSlot(6).setClickHandler(((clickPlayer, clickInformation) -> { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 5b68907e..fae7e8d4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -117,7 +117,8 @@ public static void open(Player player) { final int i_ = i; Plot plot = builder.getSlot(Slot.values()[i]); - items.put(startingSlot + 1 + i, new FooterItem(getPlotMenuItem(plot, Slot.values()[i].ordinal(), player), (clickPlayer, clickInformation) -> { + ItemStack slotItem = getPlotMenuItem(plot, i, player); + items.put(startingSlot + 1 + i, new FooterItem(slotItem, (clickPlayer, clickInformation) -> { if (plot == null) return; new PlotActionsMenu(clickPlayer, builder.getSlot(Slot.values()[i_])); })); @@ -203,24 +204,9 @@ public static void clickEventTutorialItem(Menu menu) { }); } - public static class FooterItem { - public final ItemStack item; - public final org.ipvp.canvas.slot.Slot.ClickHandler clickHandler; - - FooterItem(ItemStack item, org.ipvp.canvas.slot.Slot.ClickHandler clickHandler) { - this.item = item; - this.clickHandler = clickHandler; - } - - FooterItem(ItemStack item) { - this.item = item; - this.clickHandler = null; - } - } - public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPlayer) { String nameText = LangUtil.getInstance().get(langPlayer, LangPaths.MenuTitle.SLOT).toUpperCase() + " " + (slotIndex + 1); - ItemStack baseItem = plot == null ? BaseItems.PLOT_SLOT_EMPTY.getItem() : BaseItems.PLOT_SLOT_FILLED.getItem(); + ItemStack baseItem = plot == null ? BaseItems.PLOT_SLOT_EMPTY.getItem().clone() : BaseItems.PLOT_SLOT_FILLED.getItem().clone(); baseItem.setAmount(1 + slotIndex); ArrayList lore; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java index 4ff59fd1..79cf57e4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java @@ -60,9 +60,8 @@ public class ContinentMenu extends AbstractMenu { protected void setPreviewItems() { getMenu().getSlot(0).setItem(MenuItems.getRandomItem(getMenuPlayer())); // Set random selection item - for (Map.Entry entry : CompanionMenu.getFooterItems(9 * 4, getMenuPlayer(), ContinentMenu::new).entrySet()) { - getMenu().getSlot(entry.getKey()).setItem(entry.getValue().item); - } + Map footerItems = CompanionMenu.getFooterItems(9 * 4, getMenuPlayer(), ContinentMenu::new); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); super.setPreviewItems(); } @@ -92,9 +91,8 @@ protected void setItemClickEventsAsync() { getMenu().getSlot(continent.getKey()).setClickHandler((clickPlayer, clickInfo) -> new CountryMenu(clickPlayer, continent.getValue())); } - for (Map.Entry entry : CompanionMenu.getFooterItems(9 * 4, getMenuPlayer(), ContinentMenu::new).entrySet()) { - getMenu().getSlot(entry.getKey()).setClickHandler(entry.getValue().clickHandler); - } + Map footerItems = CompanionMenu.getFooterItems(9 * 4, getMenuPlayer(), ContinentMenu::new); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index 7c9c688b..67234fed 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -82,9 +82,8 @@ protected void setPreviewItems() { getMenu().getSlot(7).setItem(PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE) ? TutorialsMenu.getTutorialItem(getMenuPlayer()) : new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()); - for (Map.Entry entry : CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)).entrySet()) { - getMenu().getSlot(entry.getKey()).setItem(entry.getValue().item); - } + Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); super.setPreviewItems(); } @@ -125,9 +124,8 @@ protected void setItemClickEventsAsync() { getMenu().getSlot(startingSlot + i).setClickHandler((clickPlayer, clickInformation) -> new CityProjectMenu(clickPlayer, country, selectedPlotDifficulty)); } - for (Map.Entry entry : CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)).entrySet()) { - getMenu().getSlot(entry.getKey()).setClickHandler(entry.getValue().clickHandler); - } + Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); } public static boolean generateRandomPlot(Player clickPlayer, @NotNull List countryProjects, PlotDifficulty selectedPlotDifficulty) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java new file mode 100644 index 00000000..f1d93330 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java @@ -0,0 +1,18 @@ +package com.alpsbte.plotsystem.core.menus.companion; + +import org.bukkit.inventory.ItemStack; + +public class FooterItem { + public final ItemStack item; + public final org.ipvp.canvas.slot.Slot.ClickHandler clickHandler; + + FooterItem(ItemStack item, org.ipvp.canvas.slot.Slot.ClickHandler clickHandler) { + this.item = item; + this.clickHandler = clickHandler; + } + + FooterItem(ItemStack item) { + this.item = item; + this.clickHandler = null; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index aa9d1bbe..10f9ace0 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -102,6 +102,6 @@ public enum BaseItems { } public ItemStack getItem() { - return itemStack; + return itemStack.clone(); } } From c0011e9817c97b76ccfff69cc3a0fb2528d1e1aa Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 25 Apr 2025 01:32:42 +0200 Subject: [PATCH 081/175] add back the spaces on plot links --- .../plotsystem/core/system/plot/utils/PlotUtils.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index df3ab800..353fe135 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -532,9 +532,9 @@ public static void sendLinkMessages(AbstractPlot plot, Player player) { String shortLinkGoogleMaps = null; String shortLinkGoogleEarth = null; String shortLinkOSM = null; - String googleMaps = "Google Maps"; - String googleEarthWeb = "Google Earth Web"; - String openStreetMap = "Open Street Map"; + String googleMaps = " Google Maps "; + String googleEarthWeb = " Google Earth Web "; + String openStreetMap = " Open Street Map "; try { if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.SHORTLINK_ENABLE)) { shortLinkGoogleMaps = ShortLink.generateShortLink(plot.getGoogleMapsLink()); From d7f64450a0eaa908318934b5023a220a0a272d29 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 25 Apr 2025 01:38:00 +0200 Subject: [PATCH 082/175] update plugin version to 5.0.0 --- pom.xml | 2 +- src/main/java/com/alpsbte/plotsystem/PlotSystem.java | 2 +- src/main/resources/plugin.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pom.xml b/pom.xml index 30bf61a9..920bf04a 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ com.alpsbte PlotSystem - 4.1.3 + 5.0.0 diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 0396448d..2f63bf3f 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -74,7 +74,7 @@ import static net.kyori.adventure.text.format.NamedTextColor.*; public class PlotSystem extends JavaPlugin { - private static final String VERSION = "4.1.3"; + private static final String VERSION = "5.0.0"; private static PlotSystem plugin; private CommandManager commandManager; diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 0e8923cf..5a5f48fd 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ main: com.alpsbte.plotsystem.PlotSystem -version: 4.1.3 +version: 5.0.0 api-version: "1.21" name: Plot-System author: R3tuxn & Cinnazeyy From 3b363664324477f82ef8fee94efbf7c3e16a0e13 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 25 Apr 2025 13:48:10 +0200 Subject: [PATCH 083/175] update createTables() method in DatabaseConnection.java to the new database --- .../core/database/DatabaseConnection.java | 326 +++++++++--------- 1 file changed, 169 insertions(+), 157 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index f9622218..0da0633a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -71,7 +71,7 @@ public static void InitializeDatabase() throws ClassNotFoundException, SQLExcept dataSource = new HikariDataSource(config); - //createTables(); + createTables(); } public static Connection getConnection() throws SQLException { @@ -114,15 +114,18 @@ private static void createTables() { Objects.requireNonNull(con).prepareStatement(table).executeUpdate(); } - try (ResultSet rs = con.prepareStatement("SELECT COUNT(id) FROM plotsystem_difficulties").executeQuery()) { + try (ResultSet rs = con.prepareStatement("SELECT COUNT(difficulty_id) FROM plot_difficulty").executeQuery()) { if (rs.next()) { if (rs.getInt(1) == 0) { - con.prepareStatement("INSERT INTO plotsystem_difficulties (id, name) VALUES (1, 'EASY')").executeUpdate(); - con.prepareStatement("INSERT INTO plotsystem_difficulties (id, name, multiplier) VALUES (2, 'MEDIUM', 1.5)").executeUpdate(); - con.prepareStatement("INSERT INTO plotsystem_difficulties (id, name, multiplier) VALUES (3, 'HARD', 2)").executeUpdate(); + con.prepareStatement("INSERT INTO plot_difficulty (difficulty_id, multiplier)" + + "VALUES ('EASY', 1.0)," + + " ('MEDIUM', 1.5)," + + " ('HARD', 2);").executeUpdate(); } } } + + } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while creating á database table"), ex); } @@ -223,182 +226,191 @@ public static List getTables() { " PRIMARY KEY (build_team_id)" + ");", + // Server + "CREATE TABLE IF NOT EXISTS server" + + "(" + + " build_team_id INT NOT NULL," + + " server_name VARCHAR(255) NOT NULL UNIQUE," + + " PRIMARY KEY (build_team_id, server_name)," + + " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + + " ON DELETE RESTRICT ON UPDATE CASCADE" + + ");", + // Countries - "CREATE TABLE IF NOT EXISTS `plotsystem_countries`" + + "CREATE TABLE IF NOT EXISTS country" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `server_id` int NOT NULL ," + - " `name` varchar(45) NOT NULL ," + - " `head_id` varchar(10) NULL ," + - "PRIMARY KEY (`id`)," + - "KEY `fkIdx_38` (`server_id`)," + - "CONSTRAINT `FK_37` FOREIGN KEY `fkIdx_38` (`server_id`) REFERENCES `plotsystem_servers` (`id`)" + + " country_code VARCHAR(2) NOT NULL," + + " continent ENUM ('EU','AS','AF','OC','SA','NA') NOT NULL," + + " material VARCHAR(255) NOT NULL," + + " custom_model_data VARCHAR(255) NULL," + + " PRIMARY KEY (country_code)" + ");", - "ALTER TABLE plotsystem_countries ADD COLUMN IF NOT EXISTS `continent` enum('europe', 'asia', 'africa', 'oceania', 'south america', 'north america') NOT NULL;", // City Projects - "CREATE TABLE IF NOT EXISTS `plotsystem_city_projects`" + + "CREATE TABLE IF NOT EXISTS city_project" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `country_id` int NOT NULL ," + - " `name` varchar(45) NOT NULL ," + - " `description` varchar(255) NOT NULL ," + - " `visible` tinyint DEFAULT 0 ," + - "PRIMARY KEY (`id`)," + - "KEY `fkIdx_44` (`country_id`)," + - "CONSTRAINT `FK_43` FOREIGN KEY `fkIdx_44` (`country_id`) REFERENCES `plotsystem_countries` (`id`)" + + " city_project_id VARCHAR(255) NOT NULL," + + " build_team_id INT NOT NULL," + + " country_code VARCHAR(2) NOT NULL," + + " server_name VARCHAR(255) NOT NULL," + + " is_visible BOOLEAN NOT NULL DEFAULT 1," + + " PRIMARY KEY (city_project_id)," + + " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + + " ON DELETE RESTRICT ON UPDATE CASCADE," + + " FOREIGN KEY (country_code) REFERENCES country (country_code)" + + " ON DELETE RESTRICT ON UPDATE CASCADE," + + " FOREIGN KEY (server_name) REFERENCES server (server_name)" + + " ON DELETE RESTRICT ON UPDATE CASCADE" + ");", // Builders - "CREATE TABLE IF NOT EXISTS `plotsystem_builders`" + + "CREATE TABLE IF NOT EXISTS builder" + + "(" + + " uuid VARCHAR(36) NOT NULL," + + " name VARCHAR(255) NOT NULL UNIQUE," + + " score INT NOT NULL DEFAULT 0," + + " first_slot INT NULL," + + " second_slot INT NULL," + + " third_slot INT NULL," + + " plot_type INT NOT NULL," + + " PRIMARY KEY (uuid)" + + ");", + + // Difficulty + "CREATE TABLE IF NOT EXISTS plot_difficulty" + + "(" + + " difficulty_id VARCHAR(255) NOT NULL," + + " multiplier DECIMAL(4, 2) DEFAULT 1.00," + + " score_requirement INT NOT NULL DEFAULT 0," + + " PRIMARY KEY (difficulty_id)," + + " CHECK ( multiplier > 0 )," + + " CHECK ( score_requirement >= 0 )" + + ");", + + // Plot + "CREATE TABLE IF NOT EXISTS plot" + "(" + - " `uuid` varchar(36) NOT NULL COLLATE 'utf8mb4_general_ci'," + - " `name` varchar(16) NOT NULL ," + - " `score` int DEFAULT 0 ," + - " `completed_plots` int DEFAULT 0 ," + - " `first_slot` int NULL ," + - " `second_slot` int NULL ," + - " `third_slot` int NULL ," + - "PRIMARY KEY (`uuid`)" + + " plot_id INT NOT NULL AUTO_INCREMENT," + + " city_project_id VARCHAR(255) NOT NULL," + + " difficulty_id VARCHAR(255) NOT NULL," + + " owner_uuid VARCHAR(36) NULL," + + " status ENUM ('unclaimed','unfinished','unreviewed','completed') NOT NULL DEFAULT 'unclaimed'," + + " outline_bounds TEXT NOT NULL," + + " initial_schematic MEDIUMBLOB NOT NULL," + + " complete_schematic MEDIUMBLOB NULL," + + " last_activity_date DATETIME NULL," + + " is_pasted BOOLEAN NOT NULL DEFAULT 0," + + " mc_version VARCHAR(8) NULL," + + " plot_version DOUBLE NOT NULL," + + " plot_type INT NOT NULL," + + " created_by VARCHAR(36) NOT NULL," + + " create_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + + " PRIMARY KEY (plot_id)," + + " FOREIGN KEY (city_project_id) REFERENCES city_project (city_project_id)" + + " ON DELETE RESTRICT ON UPDATE CASCADE," + + " FOREIGN KEY (difficulty_id) REFERENCES plot_difficulty (difficulty_id)" + + " ON DELETE RESTRICT ON UPDATE CASCADE," + + " FOREIGN KEY (owner_uuid) REFERENCES builder (uuid)" + + " ON DELETE RESTRICT ON UPDATE CASCADE" + ");", - "ALTER TABLE plotsystem_builders ADD COLUMN IF NOT EXISTS lang varchar(5) NULL;", - "ALTER TABLE plotsystem_builders ADD COLUMN IF NOT EXISTS setting_plot_type int DEFAULT 1;", - // Reviews - "CREATE TABLE IF NOT EXISTS `plotsystem_reviews`" + + // Tutorial + "CREATE TABLE IF NOT EXISTS tutorial" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `reviewer_uuid` varchar(36) NOT NULL COLLATE 'utf8mb4_general_ci'," + - " `rating` varchar(45) NOT NULL ," + - " `feedback` varchar(420) NOT NULL ," + - " `review_date` datetime NOT NULL ," + - " `sent` tinyint DEFAULT 0 ," + - "PRIMARY KEY (`id`)," + - "KEY `fkIdx_73` (`reviewer_uuid`)," + - "CONSTRAINT `FK_72` FOREIGN KEY `fkIdx_73` (`reviewer_uuid`) REFERENCES `plotsystem_builders` (`uuid`)" + + " tutorial_id INT NOT NULL," + + " uuid VARCHAR(36) NOT NULL," + + " stage_id INT NOT NULL DEFAULT 0," + + " is_complete BOOLEAN NOT NULL DEFAULT 0," + + " first_stage_start_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + + " last_stage_complete_date DATETIME NULL," + + " PRIMARY KEY (tutorial_id, uuid)" + ");", - // Difficulties - "CREATE TABLE IF NOT EXISTS `plotsystem_difficulties`" + + // Review + "CREATE TABLE IF NOT EXISTS plot_review" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `name` varchar(45) NOT NULL ," + - " `multiplier` double DEFAULT 1 ," + - " `score_requirment` int DEFAULT 0 ," + - "PRIMARY KEY (`id`)" + + " review_id INT NOT NULL AUTO_INCREMENT," + + " plot_id INT NOT NULL," + + " rating VARCHAR(7) NOT NULL," + + " score INT NOT NULL DEFAULT 0," + + " feedback VARCHAR(256) NULL," + + " reviewed_by VARCHAR(36) NOT NULL," + + " review_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + + " score int NOT NULL," + + " split_score int NULL," + + " PRIMARY KEY (review_id)," + + " FOREIGN KEY (plot_id) REFERENCES plot (plot_id)" + + " ON DELETE CASCADE ON UPDATE CASCADE" + ");", - // Plots - "CREATE TABLE IF NOT EXISTS `plotsystem_plots`" + + // Toggle Criteria + "CREATE TABLE IF NOT EXISTS review_toggle_criteria" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `city_project_id` int NOT NULL ," + - " `difficulty_id` int NOT NULL ," + - " `review_id` int NULL ," + - " `owner_uuid` varchar(36) NULL COLLATE 'utf8mb4_general_ci'," + - " `member_uuids` varchar(110) NULL ," + - " `status` enum ('unclaimed', 'unfinished', 'unreviewed', 'completed') NOT NULL DEFAULT 'unclaimed' ," + - " `mc_coordinates` varchar(255) NOT NULL ," + - " `score` int NULL ," + - " `last_activity` datetime NULL ," + - " `create_date` datetime NOT NULL ," + - " `create_player` varchar(36) NOT NULL ," + - " `pasted` tinyint DEFAULT 0 ," + - "PRIMARY KEY (`id`)," + - "KEY `fkIdx_57` (`city_project_id`)," + - "CONSTRAINT `FK_56` FOREIGN KEY `fkIdx_57` (`city_project_id`) REFERENCES `plotsystem_city_projects` (`id`)," + - "KEY `fkIdx_60` (`owner_uuid`)," + - "CONSTRAINT `FK_59` FOREIGN KEY `fkIdx_60` (`owner_uuid`) REFERENCES `plotsystem_builders` (`uuid`)," + - "KEY `fkIdx_70` (`review_id`)," + - "CONSTRAINT `FK_69` FOREIGN KEY `fkIdx_70` (`review_id`) REFERENCES `plotsystem_reviews` (`id`)," + - "KEY `fkIdx_82` (`difficulty_id`)," + - "CONSTRAINT `FK_81` FOREIGN KEY `fkIdx_82` (`difficulty_id`) REFERENCES `plotsystem_difficulties` (`id`)" + + " criteria_name VARCHAR(255) NOT NULL," + + " is_optional BOOLEAN NOT NULL," + + " PRIMARY KEY (criteria_name)" + ");", - "ALTER TABLE plotsystem_plots ADD COLUMN IF NOT EXISTS outline longtext NULL DEFAULT NULL;", - "ALTER TABLE plotsystem_plots ADD COLUMN IF NOT EXISTS type int NOT NULL DEFAULT 1;", - "ALTER TABLE plotsystem_plots ADD COLUMN IF NOT EXISTS version DOUBLE NULL DEFAULT NULL;", - // API Keys - "CREATE TABLE IF NOT EXISTS `plotsystem_api_keys`" + + // Build team uses toggle criteria + "CREATE TABLE IF NOT EXISTS build_team_uses_toggle_criteria" + "(" + - " `id` int NOT NULL AUTO_INCREMENT ," + - " `api_key` varchar(32) NOT NULL ," + - " `created_at` timestamp NOT NULL DEFAULT current_timestamp()," + - "PRIMARY KEY (`id`)" + + " build_team_id INT NOT NULL," + + " criteria_name VARCHAR(255) NOT NULL," + + " PRIMARY KEY (build_team_id, criteria_name)," + + " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + + " ON DELETE CASCADE ON UPDATE CASCADE," + + " FOREIGN KEY (criteria_name) REFERENCES review_toggle_criteria (criteria_name)" + + " ON DELETE CASCADE ON UPDATE CASCADE" + ");", - // Build-Teams - "CREATE TABLE IF NOT EXISTS `plotsystem_buildteams` (" + - "`id` INT(11) NOT NULL AUTO_INCREMENT," + - "`name` VARCHAR(45) NOT NULL COLLATE 'utf8mb4_general_ci'," + - "`api_key_id` INT(11) NULL DEFAULT NULL," + - "PRIMARY KEY (`id`) USING BTREE," + - "KEY `FK_132` (`api_key_id`)," + - "CONSTRAINT `FK_130` FOREIGN KEY `FK_132` (`api_key_id`) REFERENCES `plotsystem_api_keys` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT" + - ")" + - "COLLATE='utf8mb4_general_ci'" + - "ENGINE=InnoDB" + - ";", - - // Build-Team has Countries - "CREATE TABLE IF NOT EXISTS `plotsystem_buildteam_has_countries` (" + - "`id` INT(11) NOT NULL AUTO_INCREMENT," + - "`country_id` INT(11) NOT NULL," + - "`buildteam_id` INT(11) NOT NULL," + - "PRIMARY KEY (`id`) USING BTREE," + - "KEY `FK_115` (`buildteam_id`)," + - "KEY `FK_118` (`country_id`)," + - "CONSTRAINT `FK_113` FOREIGN KEY `FK_115` (`buildteam_id`) REFERENCES `plotsystem_buildteams` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT," + - "CONSTRAINT `FK_116` FOREIGN KEY `FK_118` (`country_id`) REFERENCES `plotsystem_countries` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT" + - ")" + - "COLLATE='utf8mb4_general_ci'" + - "ENGINE=InnoDB" + - ";", - - // Builder Is Reviewer - "CREATE TABLE IF NOT EXISTS `plotsystem_builder_is_reviewer` (" + - "`id` INT(11) NOT NULL AUTO_INCREMENT," + - "`builder_uuid` VARCHAR(36) NOT NULL COLLATE 'utf8mb4_general_ci'," + - "`buildteam_id` INT(11) NOT NULL," + - "PRIMARY KEY (`id`) USING BTREE," + - "INDEX `FK_138` (`builder_uuid`) USING BTREE," + - "INDEX `FK_141` (`buildteam_id`) USING BTREE," + - "CONSTRAINT `FK_136` FOREIGN KEY (`builder_uuid`) REFERENCES `plotsystem_builders` (`uuid`) ON UPDATE RESTRICT ON DELETE RESTRICT," + - "CONSTRAINT `FK_139` FOREIGN KEY (`buildteam_id`) REFERENCES `plotsystem_buildteams` (`id`) ON UPDATE RESTRICT ON DELETE RESTRICT" + - ")" + - "COLLATE='utf8mb4_general_ci'" + - "ENGINE=InnoDB" + - ";", - - // Payouts - "CREATE TABLE IF NOT EXISTS `plotsystem_payouts` (" + - "`id` INT(11) NOT NULL AUTO_INCREMENT," + - "`timeframe` ENUM('DAILY','WEEKLY','MONTHLY','YEARLY') NOT NULL COLLATE 'utf8mb4_general_ci'," + - "`position` INT(11) NOT NULL COMMENT 'position on the leaderboard for this timeframe'," + - "`payout_amount` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_general_ci'," + - "PRIMARY KEY (`id`) USING BTREE" + - ")" + - "COLLATE='utf8mb4_general_ci'" + - "ENGINE=InnoDB" + - ";", - - // Tutorial Plots - "CREATE TABLE IF NOT EXISTS `plotsystem_plots_tutorial` (" + - "`id` INT(11) NOT NULL AUTO_INCREMENT," + - "`player_uuid` VARCHAR(36) NOT NULL COLLATE 'utf8mb4_general_ci'," + - "`tutorial_id` INT(11) NOT NULL," + - "`stage_id` INT(11) NOT NULL DEFAULT '0'," + - "`is_completed` TINYINT(4) NOT NULL DEFAULT '0'," + - "`create_date` DATETIME NOT NULL DEFAULT current_timestamp()," + - "`last_stage_complete_date` DATETIME NULL DEFAULT NULL," + - "`complete_date` DATETIME NULL DEFAULT NULL," + - "PRIMARY KEY (`id`) USING BTREE," + - "INDEX `FK_142` (`player_uuid`) USING BTREE," + - "CONSTRAINT `FK_12` FOREIGN KEY (`player_uuid`) REFERENCES `plotsystem_builders` (`uuid`) ON UPDATE RESTRICT ON DELETE RESTRICT" + - ")" + - "COLLATE='utf8mb4_general_ci'" + - "ENGINE=InnoDB" + - ";" + // Review contains toggle criteria + "CREATE TABLE IF NOT EXISTS review_contains_toggle_criteria" + + "(" + + " review_id INT NOT NULL," + + " criteria_name VARCHAR(255) NOT NULL," + + " is_checked BOOLEAN NOT NULL," + + " PRIMARY KEY (review_id, criteria_name)," + + " FOREIGN KEY (review_id) REFERENCES plot_review (review_id)" + + " ON DELETE CASCADE ON UPDATE CASCADE," + + " FOREIGN KEY (criteria_name) REFERENCES review_toggle_criteria (criteria_name)" + + " ON DELETE CASCADE ON UPDATE CASCADE" + + ");", + + // Build team has reviewer + "CREATE TABLE IF NOT EXISTS build_team_has_reviewer" + + "(" + + " build_team_id INT NOT NULL," + + " uuid VARCHAR(36) NOT NULL," + + " PRIMARY KEY (build_team_id, uuid)," + + " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + + " ON DELETE CASCADE ON UPDATE CASCADE," + + " FOREIGN KEY (uuid) REFERENCES builder (uuid)" + + " ON DELETE CASCADE ON UPDATE CASCADE" + + ");", + + // Builder is plot member + "CREATE TABLE IF NOT EXISTS builder_is_plot_member" + + "(" + + " plot_id INT NOT NULL," + + " uuid VARCHAR(36) NOT NULL," + + " PRIMARY KEY (plot_id, uuid)," + + " FOREIGN KEY (plot_id) REFERENCES plot (plot_id)" + + " ON DELETE CASCADE ON UPDATE CASCADE," + + " FOREIGN KEY (uuid) REFERENCES builder (uuid)" + + " ON DELETE CASCADE ON UPDATE CASCADE" + + ");", + + // Builder has review notification + "CREATE TABLE IF NOT EXISTS builder_has_review_notification" + + "(" + + " review_id INT NOT NULL," + + " uuid VARCHAR(36) NOT NULL," + + " PRIMARY KEY (review_id, uuid)," + + " FOREIGN KEY (review_id) REFERENCES plot_review (review_id)" + + " ON DELETE CASCADE ON UPDATE CASCADE," + + " FOREIGN KEY (uuid) REFERENCES builder (uuid)" + + " ON DELETE CASCADE ON UPDATE CASCADE" + + ");" ); } } From 57e360402e2057346a047419fa988796554665b4 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 26 Apr 2025 01:03:28 +0200 Subject: [PATCH 084/175] remove air mask for one plot worlds --- .../system/plot/generator/AbstractPlotGenerator.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index a79e0b02..9900a3e9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -154,10 +154,12 @@ private AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder build * Generates plot schematic and outlines */ protected void generateOutlines() throws IOException { - Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); if (plotVersion >= 3 && plotType.hasEnvironment()) { - pasteSchematic(airMask, plot.getInitialSchematicBytes(), world, false); - } else pasteSchematic(airMask, PlotUtils.getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true); + pasteSchematic(null, plot.getInitialSchematicBytes(), world, false); + } else { + Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); + pasteSchematic(airMask, PlotUtils.getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true); + } } From 0a54535e12feea667ce38de8bddfe2f3dc396e4a Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 26 Apr 2025 01:05:28 +0200 Subject: [PATCH 085/175] add timestamp for last completed tutorial stage --- .../core/database/providers/TutorialPlotProvider.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index fb459b1a..4f7bfc5f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -28,12 +28,10 @@ import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.utils.Utils; -import java.sql.Connection; +import java.sql.*; import java.sql.Date; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; import java.time.LocalDate; +import java.time.LocalDateTime; import java.util.*; public class TutorialPlotProvider { @@ -111,7 +109,7 @@ public boolean setComplete(int tutorialId, String playerUUID) { try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setBoolean(1, true); - stmt.setObject(2, LocalDate.now()); + stmt.setObject(2, Timestamp.valueOf(LocalDateTime.now())); stmt.setInt(3, tutorialId); stmt.setString(4, playerUUID); return stmt.executeUpdate() > 0; From cf010fca2145da8e9e5648c294097d56cbb0d3db Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 26 Apr 2025 01:05:51 +0200 Subject: [PATCH 086/175] update tutorial schematics to new format --- .../resources/tutorial/schematics/0-0.schem.gz | Bin 0 -> 3188 bytes .../tutorial/schematics/0-0.schematic.gz | Bin 1444 -> 0 bytes .../resources/tutorial/schematics/0-1.schem.gz | Bin 0 -> 3188 bytes .../tutorial/schematics/0-1.schematic.gz | Bin 1442 -> 0 bytes .../resources/tutorial/schematics/0-2.schem.gz | Bin 0 -> 3188 bytes .../tutorial/schematics/0-2.schematic.gz | Bin 1449 -> 0 bytes .../resources/tutorial/schematics/0-3.schem.gz | Bin 0 -> 3406 bytes .../tutorial/schematics/0-3.schematic.gz | Bin 1795 -> 0 bytes .../resources/tutorial/schematics/0-4.schem.gz | Bin 0 -> 3549 bytes .../tutorial/schematics/0-4.schematic.gz | Bin 1991 -> 0 bytes .../resources/tutorial/schematics/0-5.schem.gz | Bin 0 -> 4236 bytes .../tutorial/schematics/0-5.schematic.gz | Bin 2682 -> 0 bytes .../resources/tutorial/schematics/0-6.schem.gz | Bin 0 -> 4477 bytes .../tutorial/schematics/0-6.schematic.gz | Bin 2738 -> 0 bytes .../resources/tutorial/schematics/0-7.schem.gz | Bin 0 -> 4866 bytes .../tutorial/schematics/0-7.schematic.gz | Bin 3099 -> 0 bytes .../tutorial/schematics/0-env.schematic.gz | Bin 3942 -> 0 bytes 17 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/main/resources/tutorial/schematics/0-0.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-0.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-1.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-1.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-2.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-2.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-3.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-3.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-4.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-4.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-5.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-5.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-6.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-6.schematic.gz create mode 100644 src/main/resources/tutorial/schematics/0-7.schem.gz delete mode 100644 src/main/resources/tutorial/schematics/0-7.schematic.gz delete mode 100644 src/main/resources/tutorial/schematics/0-env.schematic.gz diff --git a/src/main/resources/tutorial/schematics/0-0.schem.gz b/src/main/resources/tutorial/schematics/0-0.schem.gz new file mode 100644 index 0000000000000000000000000000000000000000..78364ddf01998e6982ab3aede04e453852192d82 GIT binary patch literal 3188 zcmeH}`#Tek9>@7A(Y~Q?9ll*$=Du>trD8}ZObkORmLj?4Hl~?Tq8&-(HjGIwxnyE) zZAK;2+)@^~F08R;bElch>3q*WaGvL!=Q+Qe&kye(-p}*-Jn!fI`sJgTA|dkEh|S|J zMI475={k9may{^BhS{qdqNJN02PBX(zv}_il@cU+RU|H^xi*2VO9=jrKD2S~{tPzr{BC)hmG4)<8ks)jNv9AhNq)+HL{U24}`D8F>;h zONXdiF_aiIhJg&uvGuLrDT*_ztZw2TE5j#ol_oUJ=+7*5Z}Z_W1bP zsesnB-OXjE-VSX=H;$ve$xtWSIydfwO;U2RDPZ-dSy{>k-FDLp{H!-y$Bf6ZFKQDQ z`|--SWfv^jvFsNr_mB75pcAr*4f^ZvT|AqG^1oRqb8Rz zoqUt5$|w!1qE;HCICJWq-ICwF!PLZydm=2nAtj|1kxyz@?mw5Q<^=nBIC)P0VMh~B zDGz9Mt2?xc2y~acNV$Z_H&szgZD74Bl_-;Z=&%Uq=+o;E>oUprF*@HtOL``b^WpkN zGovyDgAduI0HSRfecO3VE#5fL1C%0OhWTSB!c-3yPSC1(*_&`kIx5m`^Jzzf>DJNx z!w{Q3(v$wCyxwMufZ4`d9$@V<)3#<&)!c}MpRq6eJvi1&B@-PUjuZ#>XUBOnz zgZ~ER8mh(;uiED$n*8Np0Y&1W#3(DMkK=PvvYHPZ`2H|HSOU=sW9FYDab56q?n3ufXx}*N9K<%=I z+c6>S3?aZl9T*R!6FyyMI27*2sTQ8(Vr@WZAV*nGti~bK97rF^Oz)jU(B1|wuFHxh z^|x~a(kdaytLK1AtDO9gT{-5!kuqh7zVI>buuWA+vKt)MpLnAixY7xEo;G)Tdj)3r zq&&xGcwP&gsXHxJ}Dtb^!kHBTu#)*6OIU6#eYI%kE-->)ME;H_FoiN+!djz1Q#w zMKM5M6^p%vF~B2eFiZuWvD{FqTCkazwI$?x*``!o`<>|)wVITr>c)`r!g?!&NHwcC zQ!2_!iQWh4RsI;g6ZQ?(NY?#Do;8_uT%IiBXn@zTo4%uW33noBP+PXtN0F{6;I57* zwG{nfrBH8RYA|H}*)`wkAox%KtUkA(Qd8*#VMUB}@6RWe8lS@1k1Z-IOI$B;=8j0E z1=C3K%u{}OHkuJ#M4iS^>k)au2*CEpgs}}H3;-h#*Zgh?-xkAWEq1xB zbUw;=x8Z)T>+NIr(&*MsG^H`$?9=c39D_mHx&5P-Vs%1$Av2Q30MPj+^>O~j`1Rxz z)>i;z9384#nr~bd;V_2ey*bEx7Ll4lCIaFeEmZ_%r+~l*H}c!LYeJgQ1GMtnaaWJXJLIK z`bX8}XF=a9_#bXK>3qcXb!HkFGGKJEV1J(PE%fCp7E(;(SDH#oOpxEv~PMz zL1(JK{0{`jOs}6bC+VaXBj5v#-ZiOesy72^hG#m6{#H$>cdvomA?K4B z7y07EGtGA=P6w3Aqd+qnU_w%4NCyFF>MkFxEA75qqq2|XR0SDB>euQq?mEpJC5H5* z`kXx<7{{r+tPvF|WI$z;N5BovHXe4?I%6&+R1GfFyKnkbH`!%36M@B%-lrcoZsG?e z-=!V9MMJYIP4ShK+|cFa_BKI#_-PM8L7R)~$Bj_m#656=VZ5GjOU{P>T~!%{%lv5h!mCK5W z$ib&LNzjm#4hbd+*5o>!17I>8{4sJ`s`K-TAko zqQ6qyOW&#GOYHv-^926d|NqJVYL_4CB=4O%eEzLh;G42N8j>K(1lim1uq&@ETey=c z{|>HuZoKeJ}q#6&C~-FWMRHMd#G!Dk)_>QrhJ{8WsMDo%@xv#D8fvs zlrcqF`?QFirg_*{XNS!;&Q*$;wHUFs-4E9v(fgOzudnBMy}?)4ulj$Qkz*-N2kh7W zlfoS2{aEYXU-Syf`>tbssPmQ`TXwkQ-?XdE%=d)cHi%dAR%0g}AA|Z9&SJ0<3Jxw7 zj?5R^cBmimO>Eas(t9S8=GAg*qIy_yK=)Q8niw~wMmcptPBVAKar#1;VQ`rQ-b5@T zbRflqOE3`^?B@I7=+fEP^l+d|KJz{dnl0uaub-*$8hrruM$7xw8gPvMwMhV|hv@pD z4R5%6DQ}Qsb|I`wuw*=<&-JwR27qj*ACPHto17@FqrLiNuy80`V`w8L{%X+tx)3L&UTwKpuSSnPMQ_Z|go( zxqAkSsHhsKhTkqut~>>+Qozn-L0R5hl(ZfU7t5)U01k2CGfe@IDv=7MUbgssJ4_() zlu=3)rss-R@NG}5>xHYC?|iWniHJ4EB0v6X)tScBh&^8>JueVQ^*y^r5bZ z+8w~jm?kz`hzU7TO*nCpa!B^4Y(ETta&k{gpj9a;!V1*#(qru>Tw$HJ-UcB%!u}}1rz@5xkPXstG^_hdrvzPH(rCR~VR(xukw=snFubqV@EAHi0O-_AL z{Kd|4hl!jylX5Y)$9?HNtZj6+HyJWKZkgXYHC}NyL8}t}+GE(b70gd2Uw}qooC`O- zTo^1)3?A>+xt1Vb6bK2&~OwPa&M z4pj<#(K+^j9aF@6#4C-h$&i$n==VBXR=hbQa7$1U?Zbug8zEP;J`WL1gmX21Pw(5N z4f8c++UV=nZMps)TlCY@_}9*9IH_qi9=*R#nlu6>51o4YCQSN}MDmGKOFbi@VFy*! zLCKYYsDj1m-$yt*8#D6Cl~;bcGicSQPGm%*wOV#-w1E-X-W=@(Z8{vON*79REp|bv zSmo#RB>nOF&dnljArXF#ga7#2$)~PY^Mnun2JZe1>)s^Ho^&a2Azrd`dzv z0>F01yZrcB{4Pk4A8ZEe!OvcrTgfr5OifK`-!At8$>uLHdOB4H57v&QbLoaCfWUx@1qspup%bJ8 z6e*g7mQY3!BZ34X80mswNC+(y2?*Jl*?(Zq**#}p_C9J#{}tu7Hx8JY#rrEUr*I70I!WQ*1wgi<5++m zrYD`?-Le(p<*v(aqSL3V{I7^;J{|3&ExwyesI4US6p#EgVVgJP*P(dwdlz$85Ok$E zp;g4`*rJr}lugzm#WC%3uy~?-LY!!Kr{e=NL30`-SS|UuGg}|OBEYO`+4jXZ(Uzj< zyD39Woy?M=!!pq2E{f57(ry4freRwc+~z1y<~9^YJx`j4c8u2{4e8^-%?oiWugzA` zqu{!z-|hb(O+=5~KKa^XDdk{W41MC^O+fo*Daem9a$$oVQ7`BsOl*hK+l9QaX7BB3 zMvQPByS}&;u!^QEMD47z3sK1JFR@=!l&@Wx1bZh?hR5WZuKUE%5<)_s^f!t!V*OAB9?C`^ZJX4ml3&2;woT z9&`M%-Po7uewU-pcrY4}y$-__Yj=?qW=}`mP7e6LFE=SSD^-}aQ_|u{A?EPmb?6)& zb#ODfQZ`P#opC+k{@WdiPJ@Ix4hkovBX$i7JCr%7u^?`CsAY_8PDpxnz`>+#e{Rpa zD{@(Hw>Rr`<+{wq1Xl>VsuVwHE8;%4D%?FUx`$$sKIuk_E_qxbB8k2C=CVE#`_{OH zC74ez8q8i5-iL@ck$?9pjtacSwb$~~HS0Qr4({iGdVPKUtHrfaA0MWIBa?mT!kgLQ0e+r-FkunTZk+K=TdO<^ZrSKPSy!igk0v)&m32xyfS6=%}L-r zy*imG&^>QE+83OA!I*LbRFGTVNFWEgi~y%}844dWno_Kzs;ZIsZJoj(=i8mMrR3H}(rmc-qDdV~j6>#!nN* zftUsBKwpk{TWdzdH~5K`QR8FO*tM<~Mrjjy*-mGB+^=eYIcqY&`coeoDm8UtC+=)r z=vR9}ak6^NDd?&IAyTlX2pbxD+_kL?3CHj7A)MucMz>y5Gso{UV+EP}XFaBLBq$J? z!vb6kObUWKZ?u)m2izE#e^?1|x5QLBQn#Qum*V&0p7LL!$@YaZLoclag@-~0ttE&1 z65A^WiA|NW4=OOeHY2NAeT8=n((b^1avcj5%Z{xo(06RlsL*!R1hgCPqbR?Y zNF`?j($>)rmlpu={9_B&MT&Pe157or0Qkck%y6NpPAz z!BcJWI=c;lMcq=D0kYl(#-uv+%j0gro{)*=srNo|W*~j+IDjBU?rQI%O?MKdyk4O* zd63boi@1Iy=vTY=XS%8=VxwK@JAYWDam6pQ8F6BPkp?bdaZ9=0qnWLH$e7v>H4Pe@ z&j7B5^6vf50Qi?xDh4by4QGh`>u1ik-5pE252#P8yOyCIHa@m?uGS07k?P;3zM)O! z8&ZPpd74KuYjB?c<*zS=z->-SOd=~FeFLQjSM({|GS!JAl!#|!!*Sn>CL5WL@f}V~ z=%a0ob2Fz*JN5i_R2)f?hfDP`�wz=i~N;^FUw=*+*0A5%NlizN6U%CiV^4X~e1J zcL8RjD>9gzJNHjV)jU5EBdw*jyPS?O)ViMbKxh;XV%UU#L?>|x460tAiwCk~!Sl{>}{p4CZ7(?G2@1bZ<@_52fGD@d57QwvI zl_G~N9np6%;NpC@_~=XnQxHGU*8xhFM%x!-o2B<6oK%b`8O4`K&mOxxgkXAnk+`)d z`Byib72i4dH}2ic3*GN8O@?}Usl;u($zdgOYkt%Jna-q&91#v}8T@vY`J^05P)W0G zT3g1OHn|PU>U=j%HuW}J_QZg!CcF9RJZ+gx)jt|?oEh^I}22&kK(F7_f#V-1- z{1z*W=$gh$lRhvjh--Pw9Cgrd~NInM*VGFCAye6d85Hdw4V_ z;2UG_!As-I<3T)eUUrerAyV?UzG1%53u2zFT`A$0R1ADKEo8lQV`~V{4f^ZbcrtU{ z^Jjv8zI;z-_Og2?xN)-V>``euvm5xNo*7lbxuN1R*<^_DOh~5@AtOfp+-2Qe^1Vc!L4wMmn33t3VD^)_(zxK*mSLERLuam*Mi zR`D&D7#!*Pz0r9Ao|#u`r5H&i!DqtIk+GzcQyo#{8rhZH_6|M*Y4ws zr;|NQ`IAEm)!EYK1~@!y?U2h;Oz0N_VscEdr8AWKtpB~OA^ zofqLi$OR_O>J+e}s#dWErcKO5*I7OBS@>a{1KnfTz5n{?{%5)@dX@0!agm7sYVTiJ z?q=-PFG@)Lhk1hkzw*D`<-3=Xch4TOc;yrP2WdZ0Qo}OwNI-(?wHC|f`H7T&2iINy zg|MQX?gg5SQbQ}ZaJ1fU-(TFt_GC+6CaGl~*kklNW;@d1Z*pRLEOF5-7Jr)m1ORq< AA^-pY literal 0 HcmV?d00001 diff --git a/src/main/resources/tutorial/schematics/0-1.schematic.gz b/src/main/resources/tutorial/schematics/0-1.schematic.gz deleted file mode 100644 index e8a88bdb70e3b7415d2bd4f2a8ad26e952ce9c1d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1442 zcmd6m>sQhT0ESx^TWPwEQB9eYm)6D56wNNmG1}3Nw6erx0!~Xz{AoJ#k_k3FWyUlw z6G1f163H7WYB!_WlL%z+36+d1uz=>773ea?BG7efAe&F5%epH2e* zu+wTPi7rA0Wfn%XQ8!%pdB?A}`_}fYbv+S*?kxz~nWyX?0pD;;2DN_0EkRmPX*y&@ zEDr$uM}ph93ZsTaaE5!R7Zn)X$E+UobM&^69*$8f^f=5PB-eEw^y-o$JG7VbcmRFK zD!vQS2kd#*jxn|6J`nx$-VMJo)|%ErTIg#ZIPSP@u6|!CcF4=Vyc$TRmOlcD@ut9G zd@fYb2|3`WM%qQiq@V37mZ@idbiY2#4lKbrNM-|iL*srSVrndh#OMDAXy}GEG|=94 zlx?wPi^F__*`Iddy#p&$f8Pax(-`?4hmP%y{1ecneoyhAk<|u!2%(bLicjKePvi^X zsexrM86jt=i#YaM{PZ9PUob}K)Z{V-2uIJ;VgANwUKREUir%>{e=;M{ln&|;V(((% zwHmLF;Jic$M^nSa&W~>8dJ@2ov4yERVmjh4mLEW%Hb>SKDt%2*;s*H{>LtU=gA=G2 z$qvA$x#ZQunzpFDEpJ<+;v-a3oLgJ-gZu%4p31|=u`%zZ*`wL_x*E)+|JV8g>OIq) zY@{y>`6k`!*y&IrNoP{6))}S*%ff3ZAL=xrv$tNS?P)wFoAPWrFWV*5=TU|0v6KXO zc=9WnQ%~P~EwGzCHc}m-r^e+uKZBuKL(1=Zq00*@8I1`n2k+3AR(zO-t4A~rR-qvJ zGJUmjeOvwJ5ERO%)#0ZXu(Hh$5ihLzds5!iZ9bEtjn2%b$4HYwq)k`6TWLj$rUBXs z(6sMpWkbT5CLeRvqa0~(;JKSQGwocF#mTGMw&>`VnMD+nKVBT;S3U>YR1dL+M6xmyK|7%Y<=cF_YLwx#pEK^llRy_w%+q2F__l)?xM)&7z|i)-o?2_ z=Oe#=!^prNH!ax~9geqAqMG|-`Zwg;Y<{*K87Thm7;VfE(M;|hnxIlo=w{MKWUvHEgzt7OhYi!nBZX2UFua|t zVmgZBgzbW`%Qd!_QHZmP8wKOHJ!?faOwE3KcQp^I0|D^VkPHy=mK!R*NiNFlk|-+b z7w$MtLR-w}tI09l`eLC~BE{N?UN*Db;jdd+_XXJg8R14yJv87WiI}$ZA&aeO_DH(7 zk|-ElKD9KjA!{<|0_6j7o%xOG$(2b32Ea`y6z1yV7HPV+W|B48!it(SuS(KNpC=hD tVx(@2Z=6sukX&Dc0A4zKfgcAaW}ORzH|Hd6|HLuu=*1ne8z-$_^Dl41cgX+% diff --git a/src/main/resources/tutorial/schematics/0-2.schem.gz b/src/main/resources/tutorial/schematics/0-2.schem.gz new file mode 100644 index 0000000000000000000000000000000000000000..8acd9b89829d35f9da4ffaaa1b76f5a02d682e8d GIT binary patch literal 3188 zcmeHJX;%`60&Sa?$#hc6OifMPD>AomElX2z$uJpnE6X)^5i%5;!f}*B1JsZ(B@Iop z6buoUDJ7Q_awRe}w`VA5ic93en=|hZymQ_==Y4ti!~J&ex#!+5R|~s)%iq{8E`Y?U zcdE6s8$N=(Yk{cR4t;v3zSZtp$VrtO56^Df@rU$`c6|A3r~A$t7tL+C#}jd%wPBqH z5_i!mXHW+OK>sX>U_CuQx^itaIBotQFMCeuJ$rMQgQ#0_lD4Cz^;aAKPToI4HaQ{e zToYKj33g^`27!XDR~?%fU8>|G{b367jTrei>i~-C@_bO!Z85WTqWQZl*a7tODsNT( z1DWp22wooMNUm~Kh3`Rx8L#=#7I}_L#&b&bL~lYG9OTQOU~~ogr%u7V>gon!IKA#W z`n!xyr5xMRNOCq6GWo>lB~N zVUwqRTw{rt8$HNbCNu3@(*h^lcVJb?Dvm$9Hs(8vR)T2bFk4BT`FBnWFpUf zPwldWjHH!+_gKoCd$Kl8d%C*n#p+00THYXUhBf((yok+2@oG`nmKMR1)!F@vNRklM z=pQ$}KSw7E=4TqTO#YzF7i^!MUqhZdez39~+1fPSe5+*DazoOy(z7wc9^+!EMh(Hj zmj$DkXP}vM0Q+>;$8G1Yq1oU2hC7{yMiyD zc2y;61)TQYWe;$;`oh6+0*x6fwCDF*ah8N;X=IPloPMjhdbqpgQ9I!Kx(k;H8Lb<& zOQDnHnXVIQ>->VukR!3Oa<_E6AT6*l93!G7zC5{*AO72smZ$Iqdo@=%WEYXuS4Oj= zi2AJ@rmLFZO+=TD$GmkoF!!D;!s}IEp6|P$TiHfm28ww}k2q~zK1#la)l~0r5gI$f z8z&tv*_yf+Ur zvGe2AUh@Y`W5ivwr^L7<0vYK^2%miVFkd4dP-6b()t+XPKz%TRd*rC;D_)tco_*MK zmYwI$@BsCA~ZzDt$rKok0r2{bWu5! zt}D0184Nm9G5WJ%9qLc5Ph+lKDBYz^gLIvQ35_(JNSHHBsX5mza+jy*<6hS*ebrsP zZzBY5!v|wWi()<_2l6+X%o_|cg2kg(-Tfy)mxzhNV=OY>nDt!S_Uamzfj-6Jk{oFhv(%*

VAA@+bBJONP`n-)cxh?zv&vJ|4GO~PIAp4&~Wq-PD)9~_*q?cGDT+oD& z2MvZg!+sz5#81*8Mq@7AQ|y95b5hJ+zBA=jp2;T1+)14FAw26<#S@*}rrMcA_or=4 z<|@L!pb!2fqfOdHp7~1qNkUZt0gXqL79FXSTjMJD0tHPO23YAu)!M+^(ElX;p`N1S z$|Uv`ide!+^C!$nnDq=G${FQtmAtw35MEuSb)-z3QHpI-U|2S7V1WK!j;ByOwO#Z# z!+tve*79na-7|ebs0`EAPrGTa<-du!QIHMn6q^NI(x_{d0%vZs=l zd63@Ig;#Kabh_B1`9|jS>y)-MKlI!G#K*gc2m2Oe^3&0?4q20c|_U_u_LmRE&)O?+7b%kWZ*(Tw%+)&ul4@5M3k z*V(rCqsyk!_oRHM!!G#XnZ2E4TFfQGL=sF>G4ebZIJ)IZ;65LXQJEee0R-I<2i!Ef z8S^t*oI!lB;{aToaYHO}k%;g_nx5X+fI;cxC@o#5=XsQ6Dr~S<^%CC4+a^^rJEb1{ z8FyY%b(qkQ?F6i(E(?OLQ7vk9l`wHk8id zw~jE|;e~xk`6-yA$g0Y)+X^Ono8NMhEKRQ9NHQxlxcx$6e|)AWkF?u^HF+jd%eo!R zg@iU1UbciCV}w?Vdmj(`#D;InJ$gxvg$hAGHqUzD8q{uXhrg`uR(83#UDGOu@%nL) zUyf$7z}+K0CCPz8f}(HbTiAfb5h3n@wF>cW6hytk)^JZL5=y07`~!Luc9%(zI?Xf8^7NC(9Oeqc<)HDV!Cr_^6 zfy_J0#}Hfx>ei9fRhf``QKxMROI}VoQUvNJ+6YGZmPIYd+XHnT_w_X0rlD8se(;@C z$zMVMz=R9(YoP!|0~>47_1G!)&^`8R9YSh6ygl(C|pr)EamrRy=q+bxpae8F@%h3cW7Ark#J*`~UdXHj#`%uxI5ewS$ht}3Xz;#B9L_WhmLyQityJ3U&QuAMxDzh!Bl#GBZjWPJU(jgzLb>Y|+nnp<;m zPetZ<@9{n7Y^7f#P8tRtq*Pv)mWKTSRtmdE_jX~8Dc61|Glf^HcXRz~hTbXTPg-0* zOuhzV=nUJAea=muEkDqC6uBKn_HUdkH1EST5*Ji7d5+f1YhE@*l{j`mripCm;r2ws z!O|ET68}(?ZF#~z7<1}fjk>l)%aTtep@E(jWq@sq*8EhC@^^DSF$_hayoM-kg`8`| zWZI^|v?3@xO9z}7E#xaNV5~YYtKHBPOK&7tI5{X!mC7e>*Diw7XyrxoBVD`qG+0M& zCN9cAxXH`0D z^Zs|7>bSXg%NDs@{ATOczf#=E-F!K>`{(~KPt;%f|6Bf7yX>ghcSjp==1s717KC(q zPl@&~$8X3l{tDiX6r%S3J9E9F+TrL9tiaXsr} CBYS56 literal 0 HcmV?d00001 diff --git a/src/main/resources/tutorial/schematics/0-2.schematic.gz b/src/main/resources/tutorial/schematics/0-2.schematic.gz deleted file mode 100644 index 70958bf0cd57f160c12f21662ce152388bcd7e53..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1449 zcmc(e`CHNl0LFcu%37OtD03!0WMwU3Dvv^@B6H4ZPbumoCDCt}pot{~p_0%eDh1O@ zG8%YP^T-P|4sTtDVJA&3<&x4x211z!^FX)f+4eW|{__6%d7k(4Lb&T}{*7r^aT1IG zug$>R^Hp+6H|?^gzXr8ow|bCm$Tk;aBBS>SL2fq)IwIu!p4Zq+yS7G0eFdsqOTPMh z(&n5XsJkoEDn`j#PgJn`Xs0~A7$~4=v^0+h;H`6dzA$5En*@3Duz2^6!btdt0@;4_ zGO;uGF(KCzDusCXO@wc#I4Zl{cBN12RTe*WoyfWj2effU+-qG;V%>g z^c_YAJO{A?)pjvR2MVs%8g(}~Ec-7=5h@Q~>j$J9=gL|F^W zRwyC|$f&F;PI`l(T4kShh|s7$Vwjt~cK@qXeL6bS!Wb`BL#+0)iXKbzopdy{)uE+9 z!B54gG6#pHp9+65Y2)c~DfpU<`H<&)_KxXv&^j7kAlLKs(-PFIWz~Ocef~Nh_SP5H zvljrmfHFXvw=i9=^HN~$tp&=P6!-t&isZLqJK`O0h1PsCN#x?;{bKFbWS?MuiE0A~ zOsQmJ;0dvs{xLH@vLW-SIJn;{BGC}T|Luo^PPeLS%_`%=1CFY#2gE&TKn&(#!(uZ; z^5Lp&_;=LOI+2n5YGgC}*U9gbHamIGML4kigR0uupJtFp;xk-VHtGnaK20AMYp#rW zRww^SFIS+njZ>DV%W}}9J9P=p*HV`)Q4bM;zt!-2A3w(0d zCElP&URV_7H=|L`Wwsc6)qeW~$j**hL=iG_lT!%+;zdFwwND-=F37F>;=YY69e&`X zp8qMIl-td7)}1piYi4N=TrKZ{IKwsG8JfCorwhQdZntAkMmq~Tub4vw=axiOV-hO0 z-`>4ozRX#{=wgjWY++GAMzUb4PX1-UXz`LuP@=9aw~OvSkm)vlV({6B`kB8yNau|% zhC_40xVq7mjQ!^5Xe@T``ZG8X#~lkG5(e$!BBn*P27c7rRdJ8JPb?^|Ws?MwV6TJ( z)t_Avh4ip_N28W%rXM{TnC2t_gQ{vN1pfi^uX zFl{BoSJ^0P)@ibLr5K+VcRN6(auPB{9P@DmjHswF)%HR@zx4kT1bT2kzOmHTbNR!@ zm)TVEbl0hXvOq{a5diSL2|&T6qWfcPzOE;Sex`*%rPCK_b4$n6QYND}yS0Onv-l1e z#w~ZeU%~hc#W~f}_(qQps;dW?#}!TYi0GVbM+4*_dJm5QUS5L_UTx4YR@?jy*M)qjL(9ce`#+I=~m<-v5NnvDX zFtU!xmUWEm%gC17x%VHq=iGblr~7_*zrD|M&hxy_IgjvbCcr<3Vbu!iCD6mOwj$a< zDRhS5Z)t}r+&SoB4?mXZKDYDc?%8v(JK7>XMR?r=Y4&UULT*4@(y9owhqvYereTE; zKP3*u8zx8jOH(Y#v?BthJ)-<@XEERejz>EjmLET8YRs1N!b$fcZ=Xy(Q%aSTJnh46 z?Hr7*s2#cF@i>roGRZeGl}=CYA&+X1YW?wd2nb)RN;DZsFAEFFa#^3*_`Nf8D3Tpw zR_SV$sG4sv&>UahObFgz4_l%(yUc1H9Bgcb93IVRoEpr-r7nb_r$)*wPWo44mZ);< zH7KE9tIMOuc!Dj-zC2VjTTbl6?QnH_ZI%AiLM{{6+W}YdNXi|^L%;BH*U3>S9fWx7@TeuX6vRSsb_KVW4XB z@p?s&?cpkwo=BN^-P^IYSYtm5oROQh9rd)~&PRUs!uMji%#?Sm0ytQ_PN#O~AE&A}5nntK#QP3V{vu#Bv{vyq+ZMuYZJ)*h6$ zW(^R&;jD0(du#B{7^-!aMRSw2Z7A96f#vbrk8Sd5l1=4nw&V_N8@T|6%C^aFsFT;M zMBhh^w#gRmC1WAQ7_JMOqW;%>IV)YXRD4A^5Z6Ll?ZYBlPMCU?LMmf!boi|CRk*h8 z`PR?T&5mH2BSy7p4e3g6$8)Hk2N>{rmsO`@!jJ?h>QeUw%VX~Tz@XVa&Uup{jQni3 z;@zoAc{>$Jv8}MdyLk$BArq-4!p#SoZfhOX&(1naAzT=-a1~c_-dDp+D8K%!6o%KB z?XWf)V%(Q-;#gAP%h3I4Uc7!zRT;I-?EVEjQs`6KL{rtJEvNV`p7rso=4Km|s1vD4 zdt{KN-ZelexY-WhU0Y=`08i?aK6V0a>49Z{AIl%32}F-yE=Zv|I|iQh`c}v)l1{AChB`qj~8Ljie=DgB*;>+BE2JNZ zl~S|BUL(BMEPtuyS(8c7->I9C;*Lq+~>SSN}IW;H&r0CfH>P<`%XAooUC@T&P;k zUKr-elOtbC7@6*?pQr8HdKJXed+dWj=*a_JIUs61r(DcL02ooLFBe@Gu-jQ=82*=8 zx@qVDjZKoAGG_CDr#(-}WP^d{%v6947u_Qg;z8p5D6&YG!O@;0!O^ZSQC{Z@NogZl z`ja?;r0TLY1^iH;+hRtlWp&zTSX^M18vXu;VBO6}x|J+O$seLRF*3ECxvY;O41ks_ zKM*)SDBGg1_ICCq|6BJVl=X0XGxz{>*bhX@8&9W)bOhlluihLm73nv+B;v3GCyoSz zAkZQUf4&$}_j8{Z$yn{?9#Ipk4Sjjwtwnf#dqOHX^zU#>MoxQ%j>Moc=kaU=H_?g=y zr!^^GmTb!5X62w9&01QSD-N)i3@ zZ~f$wob0wG6%il(c`dAfVjOJV5jo;+Sfv-Z5JjH|K*+23siDB!*|HB?tKSyuJ9!Kz z>b1{b?zz_Sb7TYDnjBTYq?rBnS#$c39#ePRe_0m@4;OOlG;B<&VGqJ?YJXa)@e|Y!D35y4wSe zEwOXziR+3vR_O{DY?E(Ro|_aK#0NdI^Y?UW$c1R5!JZ2=<~?5palE9v@H`!C;d$L@ z?QGLJ0^wZSaWt;C3M1;l!zZ#kX?=Oyz3-jJr5yDIoDNauuO6&CZ*^g=_d|cCM749* zxju`nv9*C--Fes!>?inzsA;?2;6CrD+`~fT7q_{M*BgJ4Y~bGZoUDhA9aYQ?Q{?-T z(oyvq0wkyZ*EtX+5ClPR1cK5N?4*^Y;<2!*sEMk{_Ve}@bzysEP^Z+mZ1WcTHm}p& zhrNaHRo$nxz_kiR=ycJZVG;I6vzaSJ1O7O1!!erhl*#33We}%^nXK;S%$5+MLwtcN z7ZqkuKJp98IakCc&nf!3@bso4r@%mxhCeAPBy*+y`c-F?;Dz8_GYc#gK4h#Di+fiq zBtoEu~e{%;tvc}-Z0}LAS0mj) zWAWc~L_41(cnrgITSi?2-{M*auc353eOml^FML9`rw3jtF3;aY01IcB^=-E7Ei{@M zZRPRtXE`w=sf8b$9qwUU2HTD58_shiS-es?Rxpe5T0tMC8ArB%V3&gH7dtO<<*qE} zb>}Xi7oNOzDceAoT-+k;#}k4BJ^e#4`^%=cYMnOKvLyC2XXq=p zd)2w7;V<0k)D_3}Le)fKpQs2fDLiq@?le~r;QwB|6;eqGyR<7FfZk&)=}Q&t*}mjC z;nA`FC6~QoEj6Qb_ivUa9BUVw%W^&7Yw+wnxuSeoyc_;x4iOeI9<_Tgx8=$R_&U9b zh&l%x(%M2OG5{RC5sf zjrFjFsd!TuPAmFLq10N|?$b6dxeP(IgshhX28XWaj)wf~E)<#a3z0Gyt#wwyWh zhwoL&@5*&1mj93${^$PxkpERJyXDzmiEsj1Zlt%HWc}jOxhrDReR}VS3*^r5n%=)< l7b{(b^m`$2>V1;U^ltweS^kgTr>6{no1x#bgVGoQ{{YyI+Moac literal 0 HcmV?d00001 diff --git a/src/main/resources/tutorial/schematics/0-3.schematic.gz b/src/main/resources/tutorial/schematics/0-3.schematic.gz deleted file mode 100644 index 3b5fc4b859346ac579c9b186654598f5b08152f0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1795 zcmc(e`!^E`0LObM_lUSjidfys5;b{59$PBc?T!^{QXUmr9y8@J3v;3~&iDJn_m}Snkn`KBADaEZ&NDq>rac#< z-(nYh5YZ8#j~g>;s5w&IvASb*X%LRH_npPAqet)<0Av;FHF?e?mbQ6F5X9ppYAh6E zyA@*joq|%yc}acN2O;uRG7o<4{|W@8t>$v`XL=;u-bkTvAj*UgSgU|VMp z65p)_{FwW+!jhh63cqzg!t~cYm$h$cZ!5;ehkkNkuRjxDpTI4nWK>FTwqoIr+e+Rg zW;|tS1#Njr+~+jy)df1}ve)(P+`@Cy4OGmb%I;@A;4Cd5;e>K8Q4?AY@KpwS1W_pI zQzXOnD*hQu-R@||w|uX@a357wdVX*G@+MkFTZZmQNK@@x5h8m|OnP?73 zK85BZIWyD9V4pCB9ZL3xC$ z4%-aO`;rlNh_IQ;B~^)wGQL;z5*9ZPs7=Yc26j1ICCBWajJxqYEMTv5CJy?7ji*wA zp~}FLA4MD00PbEd_MAmjg@dfjf$w|0sTQq~l#tV=E`*#NlycsT&awI;{WsAoSKt>P zb&PVCPu&77`@sGHUF&PTM*vHO8#g8~{fZ-P!j>Bi5}f$H*`Jm>{f$QjBWZ_6Azu4` zUhCJ|(|_=hN(Q4#B?Cxr7lgaaCMJ~==b&JUtXy;Z+obyPH)s(iK36RJ{FUKG^7Nfjr^k@()5Yb+( zT%sVKRBiQH@>^1Kj+sALvVj!i*utulj_nACcZ=JEaC)_Z1Dle9qYFf`E zJ-rJ>13wU#!#ZM{hPR>q)f}@wToZF4t$_u5VTQ)f3eIwi>-ZP&9*#>{T`o!~=~_fjtis2~WAoX55#?BO>{^ZqXV7JIa!{ zAs$REOF7W@qsaNH>QGWE`Uj)rt$~Ns{a5L!s`@8dIgMDCUBV&b{4NjsOCm-eLGRw^ zEjUBGkUE|_1|2?dUE1~O(oat7oWdGwIbDL0*3~j}x1V0-g!3JeI38-5DK`!YNVG1xKtlik diff --git a/src/main/resources/tutorial/schematics/0-4.schem.gz b/src/main/resources/tutorial/schematics/0-4.schem.gz new file mode 100644 index 0000000000000000000000000000000000000000..6fd6401f4c3cc180dd2a9fd24a0717e8e665faf2 GIT binary patch literal 3549 zcmeHJ`8N~{+nzQhq9|LI8A~WjV{BP7$V{?N!h}Kw4`UxYc}f|?Aj@bh$zb3xTs^s`XPQ7}_r&PoI<2gZ7MDuGs=p{yM1uDMNmS=@Rzjg%6!@UWg@ltu z9myqbu;;dzCA(qvh=xBhm3`IAJz@@{0(UASw649=uMhSA>OHYc-EIAOB1^Vn?67Utvs^tvC|sLp2Z`pn5el#gOa4HCG7PYZg^Tp9NH@?o1>J<(%!N&Qb z9d^c>?D^{HN;6rFKrQ|4*1qt*kZOW7cz9p$hw^kxeai$x zlx5BeQg`q4IVn1+hrBu^(VGajI@-qsZv~Gj8gEs&Tu%NNIM^k^taEf53@1i}YIlFC zS7ZW|AM*U*W&6oHD80LRHrT>Uod0=JfLEQWAC>&KLjg;zB(Wa?a4k za+>6EzKc#=Y`VdTZ7@Fds55AzMmAS3nyrhPYn?9+g)$;tN~Qjkb05k3eCM8n2=aSJ zDUbQ7ebr}Ji|(Yo2PLolkHczRWi=TxvS~j#(RHxl0>8JPI&Ro6F5n{P0DlF7`4tCb zJ_0MBT0s$7v_AXS*Nwb}SG_qC-~=ev?%Ke`7qtrNe>%|uF5RoDQ!N=#sT{C0#h9j9 zilFRH=HJeMC*_iEx16q_yhOUV7Fx{uU)N+foX?YL#}}P0k0-)ct;S_yZd^se6Sazi z2M_%w!D;?1g`N+afAVux2j33wK;J+|2gk9C%9wbQIv?pFPs@pDMf*&Qsr*>&mB*Sk zXrcuwAv44LVgn>1bjh^nXJXtxOe7ZFTcg`>_$O!ti#Yj)kgz@e1g5- zpo8zYOIVJu;+H3$SNVeA@CmE&S3+h;&#tD`&Y=$ZW-Dgxy0lNU2_*#URAvuxsNa0I zkb!R=GGOL=oTEi3As9L&b^G;z=ZP{* z78LPj@L2{xll5WnmSLDTu0Gu*IY&;3?$obV{G#Tm#@e%Z5(}xoz9N9U{`dqX_|5dHOaB^Y!ZlHlXI_sPr zrcXKaKphMGYZ3Y&eDb!=uW*4hgsFV7@S0C)ctinQwulSPOd2gTU)nrOMU*E=po`r= zi$L(XGGkwTP{%NTR`+CJ+vlQ<8jfR>-nFf&HiYymg?t?OAgH_4rz;<~VwnoWhqW0d z=-wq6z2lKb-M_ww`^5kbm;^z7g~^E+x^{f@tjYR>&FWqcN{T<=llalKSgJd>aDUkU z>e>XE=f;Tp_A{Efo_uz};-#orLW{Bcr#ZMcKdR<=eQ%SJnka1f4N+~dK>lK*&do2y_f%>`2n|b!U9V?Q;(;8%c{fGQ+%F4^GqAO0%4$p zw4mc2m=P;*DU_EAlQB~>Lz!$UaaV+}kdZB+&kaXr1 z6~}_7t`|&G+H6ZMzlf))r&(5x5vNnLB~BO$RDvfVqk4=awE}2R+fcikiZJBLbAm&! zU_0P~XuNs-OuKMwnvKcp%;5nsOo|)FR5EXpQed1;NcZIw#5qXwn*=D6@FJna)$P}1 zD#115zUuvl`)<-k>E$1HTjmVI2{Yt{@7ZfFzU;uNJjIbCqV#MuN)#t;EkX&0MiMS! zd*C^=FS>kpmpko9H^;;TQ(o41NFWo%?vBHZ{laaua~Ex>I=2&YxiQ1wE6VVbnnmW< z?&my~D$RT41XH#0YI`QvQ~dFfilA}5$9~4@&~X(<{2hR8dR0M{fl61K?U`j3-a6;{ zYIUlX%RGLxftW;%bDI}~f7KwE?L9S6slv6?n;>EQZJ^9ows#$?g}&7&XavXJ8=Fdr z_LBA13LesG|6_crL42v`9WpFcXwH~I?@rcORplp^@1i;hRVfa(@3rG!S9ml@r;h2J z$?3?ty6|;CJaj~LmoFnNI>5Vdd!(_&6XgOl3NUN94mpqPNmeEGWkgya{2k5U(${!? zEZo(#>e;G#|MUUM7@a=0(kHFAD1;7I<@ys#^G^Wh3`_sz+MA3bo$qykD79qA_VR0J z-?)J$Ld>lY(;fJeTz_ll1`pYHNwE;3STz-VOIBlwE#!OAT;i zw{k()&ICKqZ27PZD;pakN=1$4cSv*SleM@Qu%(V975=Hkc!LM)dvt)5am$ z`pl-?NRZx7sZ)Dsi>^+Qas9Z!f|NuaFs9iE&5^S5xgu>j{g{ zNiM6kmx^VS3a@e}bh!u8j3eH<6MlDOu%dCKz+fu@>HD!mwA2D*DJzK%x+2I1?=?j`GGO>9Q?#I%ad3i8=?p z&)1%_y_q)q$xgacdbj&eEvyvm4tXE;ar9bqmPS0uDD5a(VMs3DGF>TU2?bmzW?hJ& z8YB37cP7wA#4qfrCeynthxKm0`2$w4=Bh5XVqelXlL6}Xkw-Wi#gRM%6>VIQy!U(<-}!m;a*^2Gcy-+R2Rxb%DmlP5-( z6|-5y^Y1?pFh_RYqyRo2%z(J$)9-OB6s@^H*WARJVwqZG+%~NHd(Tc^=@cN=2$mdYMh?~JX$3OT+p~$*XGFGqo&I)SAxZh#hEHIz%fx?>mkyyrASkc z@)ptQ$n5NE;9~K!I6p|CI3KJ`sTZpOXEbnCpgZN5=qwqob9^W4{^j8277!b>{a* z|0j6;R{z)X|MiybV4lao^MJ-{87&t0T|TG*(4qav@Zlr4{?O{J|5aFA+nT+`pydcoio(aMlLzhbb;0uLbw-7KQ-H*$hQWacTcOzrri0#5V^3Oi1^TFNr6XIUDo z(|85f>Rj_LxaeU|b|amctA0ds{mi+!4{5s%W}g$^ScPYgJCX0<2_=oWW&A9wwcE~Q z>S`&KYR{7X0_z?5|8ZGEfLcuCX%ABtEAXJT&dkfpFZ$#f+n*u_Qi^*f4d*SAe{7Ij z8)tG-I2W|s&YNuTFd;8JQZdLyGV09Y|I;~?idnL{TS|D=> z%(Iwh+0el8#YISBiYUg=1o<|DQ!X!R)7DmH*ks)iD77iCgLkV_V-u7dxE%}=Ez~?l zxdS_~QN|Rr>)YVtunB_@?;SYmHunkkN31LUebTlA%SrjEf*!Tw)XmrSgb=eC%<8xy zntX$UqBgo_Isum((3D)fni35WKN-K=J|d~D~%1svs`pXQ#Yee`QsV=SZ-H)=TG1FavNc-fd)8~*k<3D0g&Y=!4 zlBX`E0mWIK!p$D|Av9Tfv;FAv*EJ<{D_e{O%H;G3@d%}5@7><`@!-{|wz|>NV6)$f z`uiGy*Oj2vii&zum8rJ@M7Z<3g1)*zDp$xct7yr-6i1rkFY$Cld(3OfIW!|P0 zp|{pB$+D{{x5Dlel@77*Hg}N|(kPARtO8zDH&^?EEo9+m_p|nLv6DtyT+W#w{ptws zh~b2bB#&^`+XKI5pyu?S2QZ5b{=C%?L5A($nrQSPkm?h4rUgK+lVHQZz!yA2x-Tb$ z1J(8{`9%_Qta6wTtQF>QVwHh4)V9*oOR&^AoDsgwKDrt;bKb}68o1qaER;wHvXi12 zGSgx06`r?fY%2T`Bgw_TH&6P6pJr$9%Nqy;A`&U|)7d6kVk%3_>L6ujR{b<9?x2f; z>g!jYZGjW{UK{8rSI80K9@~ z-4!pz85Y%&RhJZsn0KVNZr^mxOTCRrA|T#pfHW?BSFbL!$oDy^zxdRQ*pyz@AHW^- zSZ>zB^$4>+`^1{?SV{ylWxQdkzuGW_`2I|{5y%BvAqcQ7I+3+aa~vk}+qRAisZW)B z)&C~%xO;2F(ROFb=HM~6b7%C2`hr{!5E4QS+`l@ul|4`?__%d>e`_S)M6*?c1GH91 zuYdq<9l(FcCQ+MR!47*b>L94{U?z<%IK$;kqKwLjTiK3o9n(w%LL#E!4g;^5CKn>s zf!(xD*%Gh@S#h0oy`|L`U6^gEs`BOP6C=f-A{yJ1l&;Nj2>zOFHi$^7PcqvfLEP$t zyfA-9ufS)3C;Mm1d`B$9;pt@k-BZb5vr*3+7N+Ak7kwBb#zCaeGI;UeD;Qe+pFvYP zEvGp6F`#ziUpH!{A7$h2fB1b*;aB>GIEhNut?8!cEjs`TfI_*DdxZfeVHd*52MUFX zP*ge1r&HvW$OADcbzu&it5VBFM|a6bxy<`}2l7LLR)8Eh+|5Iv_675*qxC|KeEyJ7 pX_A497j)}j>V2xTGH?HVb3#A+DDmPNpL+DC7~M<798T}E{{nn&vB3ZU diff --git a/src/main/resources/tutorial/schematics/0-5.schem.gz b/src/main/resources/tutorial/schematics/0-5.schem.gz new file mode 100644 index 0000000000000000000000000000000000000000..a78ff2cc6232ca4e80085782d31e2033e82c939c GIT binary patch literal 4236 zcmeHK*EbxDx79@#ZIq}Hy@Y6=GGTOyJ|ZMSL=8qa1koirAEOJ=%P`95CDA3LMQ_o@ zD5J#aL-5P@-GAV&yY9MA_dJ~Qvd@0ld#`oY;f}jQ@NW_CSu8?02H8H%uNfolESgvq z>-H4tD47m5BMMcGQ~~1Ig#a4%0@cYGnvadhzdw!_>lu6GHg9{M&|HcHM|DNCdtcD0 zOF*^jT+8}zE$aL8+;5N7+LukPA9LjcB#$r~bL9v5vHci3psAj{7R~!qN$-yOEB(?1 zYeR$dEo@m9_IFKYZk}YLNXYMCDWwK;^2*~6lanZ0i)F~v))<#?$u0iU`c|R|{0n89 zm7lgAj}5twa=gZ$?#|x6&c7{O3ckQ2Zh{UMt%I*g=k0}GSYsw_TgAGDzlc7*wR_^* zOIp-q{nVi!$M@LkMmk?i`5I`Y^d2@gfU>O{O4>r%zv6N!I-65zNL}};7YibQOm<_u zfDPse#!5b?cJ;NRP4NqkiktZLde#pOO~&Wjd#=Vz4LB4&$db!9examjEAAVvIRk^K zF{ZZd1uo$NfQF%G~N;XdwYG{}nSDzkU(qW%B7~;^@&Y1WW&%w5tcS zr~!41@7ei+eBHrlk3~M8!_LP+GDFNeL>OU)64o$BXhPc)$GCO7j*e^tiSMa_IIFlI zzi8ftq=WTtHuh8Iyr(S3^A~nNYh|U8B*BJ;A{2i5==V+lP(>ws)S4x(Yzs5J?qr!O zkv}RKJO9HO*eUku)m+1RU&v)C)0G<25CCr>^{Xshq*cYm zoqz(;3T_?KFFc8Gfb@&Ga!1i<2>_l{ex~&6;$_FZ+G7BR_{*`V>BAV~5SQ^)lPfY2 zpxd)BHjnwg)5sN`{nxX2^0ztyWj z#4`pW7N;*e6E!R!_!7G(w5Bxoz}GZ~ExF#v9VX8Y5j%)Tg>7Y3^znbPUsjMx5o{6e z7<~C9swbFg1hzc8lgbx-R&3aCg3kncR#liGDX{{U!`1c=7*WS!kFwOOqdvWfznZnn z36e;Pe}jMgYEN-2Ppa@Xt@^wLK*HVlosmp49jALwAk|pK3*rko;uN4gKhtJhYnRZ5qf& zN(yp&J{kd2yhmouOR$QtvjC9S4MZwi|87*4$< z^H-BkvQws!UPiDD6+*rpp1~+WN9{zh=q!-ECSyN*ge&tM*ljMO)b=3E*qFjxycm{M z|9V|fB%jz}lKLE+$8e_OH7&6y8TokOT9{Ns2 zhGN@3BF2`M0k8V~!U{gwd#OriajG%zrBNvy|0u16P}T;0={i{7k8}Y-x}Dk6p99i| za-8+KMguubSoJm485Lhr3fn0L6ns0NjN9Zs9)dh$eg4#S4xp-s0?$S5OOdDiIa?Pf!MOpk)=lr5x|J zF^o+vvv4vc4%-0MTT-zLMG3Kz2_-r*E~rfgUqoFBFH?r#!s2oGkGS!U(~37d$vzxc znD~is(#Y;HCtfx`c{;trdsnb*Vye5aKE}}cCy9k?qF*+SVj~IZcQDdL6SSj$5?B5J z1gc_TNYxf^95@DVvv5b23i7+Jv|H;``?Z_BZ(eMq`ewS2_~O0WQLD0866d|<>6${U zTryGhesS{*1G<>>FaL<^85d>umqrVqC-<`!jF+ThX)+dGmO>hd=v=8m5uMp5P2)k_ znKrzv#45e}RJn4bOflI3*eq4r0c3=Fw%7-ba6+NEyRz@dQ{E6sl_^HDn*t69&%>XV zz33&J?1xZ%a#?MBQB0P3U?Ld#)P;*#Pdn~JZCU+$pnFD_H$9se17x%RpA{~9a%F4IYNy@Wyel>XUYoaM|^UCewHC4 zrW>spgbg<{{qA=sqR{Me(mI+#im(cjiO`c7rweOQ7%K{!J@494*5FtY3JI*IvN zsK6OKCUN!K^&#;?&bldhgu`KL#EO;4(yx7~&>>of$%@j+A;20T^r+DIZd`ew53o)-tvYC1(@frkrZ zqXX^Wt_H>+3Sny54KS4G$7Mr916qaM2KE=at;Rn{swLBG^}z= z=DdF7TIK{Q9E{Hn(GBdKeS7b|w7C`!^jF6Y1OrqI=6EOqH``kBh8Fb!0bAtUU2JE6 zXF+?L&#?zsV-k)6rG#~8>gh_=UvUriAk@#Y1=8!UuZxxRY-N2%l7j_(QlC3m7f?Sw ze7xs|93G-bAM=1 zn(h7X=%ll26%JYL@Xo$YGuZSDnT?+aD(z#1TL(&}?0jnx6lEG%Iq}eT+1Z1ovb+XC zG2*%SByryj#s6+S5;EKa(X9{$gsqNv=0%}Rcp(x_rl7896;EPU-pB3s2;_h3%U6?w_QYo6VAgPy#yhdm&6+FhAPe$Jp& zjikXOy1%RL!-VMXkZ}A%ughR4C{b*PiYhk4Gz`b~@m@c7BtpYpeAcR*j;C_=e?&!* zSu}Aam=goxC2Z9y6kNF-Z=GsMrltD{s+^=&P!`i?m2;x?Khj|NTb0NEga4$tA9F{W zx!-PfPV3c)yLjUc%&NHc3}$tz%OHt?S%qszk`Cz;64mJ%51RYwE-}5zb_i4Dar!#) zrT#cckfO+V{@ng@)pH#*f$`SA7FF^GvHv+NDjSA6jflPIA7$)RDGHT>2i(-mDK4BV zP%imn_!POC>ja3MYYIQyO1D9w%R}FxzVutPeOHYC>Q?{5tcA`8UuAzcIoFHF#p*X9 zI^Pg`ZvhMp?tZ*GB%fgKF8o*~K8x{(sUFhexUA>H2yfm00hqXMXxaMPXM8nPj?|^n z{U)mP2T|1LG&PLt)4&craoZ#+NV8f>{R?{4!$fd~gK!~M? zwzINtf;7V&l5h^yOIN*IgCg*Okg-Ibypi^B&IV^jlZqBi7<f-9l)@TfclJ(@DEEzE9(Tkv5x=H~$RUZ%rE?3yFrf6Kbi5I^Rs zGDPpqaX@ag^R}UWYrEAzKPnLZ~9QJ<}pWg&SA>D4(?MG4> XA-8sYbpHl}m_Y7*M3rt18Nq)5Y7cI* literal 0 HcmV?d00001 diff --git a/src/main/resources/tutorial/schematics/0-5.schematic.gz b/src/main/resources/tutorial/schematics/0-5.schematic.gz deleted file mode 100644 index e9c5a23788c0370159ec58b3601ee47ef80216b3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2682 zcmc)K>t7Ov8VB&5Q>`{^G+mbFW#z5BUoy)J9#^K$3#plxrevXLdC5xDz}#|^nt6+~ z87a$4B%qjhMa89I0-`CPA|Yzw4Mhb(!J+efcHW%7V9%T9dGY&vp6AW;HO$@j+26G^ z#?03X)!#dbFTZ$qoB`c;$hQ+pN*@HMo7U zue*XC{Pa`CF~$-4l~U0Q=z&<-mA+#h=<0FcLA^Uw?clGMo_y&0B*6t(X7mqz3&=gM z{9t-|&YR(-biGow9IVuHS^Z*HUzX5Wg;9# zrdt_F@l1#Eep@Cy#9BSY&HiF$4nQ$0;vjS6!QT z$qQu$0*ct`0pbXAHl{HXa~%7WJCR71;2i8|(7qLly(RW(;?b|f`)2cjnEit?N-N~^ zQI3d>5;Y*ly+)94U@(8>&qnfr0sK*|w9=-?Omzbn4-)DwcObiAVq@8gZZ@aq21Lp6y46fV4son^NBSad8xE-2&?%a@d`AFI~QiI*%HyLTauP=8cO`p(p3gudV2QARtR11>{M~ zAdv$$amy2~sfR}fS(M&O!CJNYak#&kFw7>XKlEMxwo~h2=keh1(m5w8WWt0Y@+3Rb zZbaXM9cONMPu;)j8<6EOfk68--Uc9&1P}FX$h2*?Lcc+jH5L1D$TPbx^p4_f-qE&( z#l((l$XR1>oUlg1lDKO9@16hImOPNstYpzxA{ikUX45b|JGiA-yIR&MW9DLV6Xb!n zX{Ov%vd=lpdHb+f%mw>>jgX6U~^^LVvPixY^fEhaA@ff3K*B{_#ci9M1gLtIwN~=TW7L{~4=> z{E@z7n{sJwIj5~%(u1Q@_8d~XtH2HeI*MeH;rWHMl(6%yvr`|~0$qsFrjT@{=o>ZU zb%IbS{BF8}7Krlbs8e-5NTpMPOG~`F1>)4V>pdP~EE1J+Z_yN@lJnFCD2p7(FiugS^F2Cs4V zl8nMZ4}aRMjX?gm<#pQ*Ds0$D_?V<2xAg;U5%-s&YAqTjFQ{yZrK^kYboDIaHFAP1 zd*ge9mH}|$;}tU`g_^QwO4L)N*ux{iUp=BFX{#@&%`^(2{Xy=PbnFD;BHillr;PIa zhOiPC-8zGBF^k4)_%o+*pFqQ8b0VG`ex}K+YhS<-%i8Puz-obLlNSOL$b+?W|+m zDGHSl(L`01yS*vNddhHok{mkC8!$19hVMp0)+YFF@{=o013|--tq`p@IHlNUb zHZ?%}F{5O?iw|QTl}(yP0CgTU>I}wemH4FdBT*uUi+y;iPo77VP^~Iq5&u+4dFPlo zD&GIfToXF@?|Zw{hH?V0aJ)j-nCs58^O+f@gzjq1PK}NU#OK+T;Rq_!zi@0G{o=p6f}n1^cH(v@W3D{n>#%^2=YEh zXdbl}U)By^fouBP04lh|V7%9zocO{8ySy2IK|>!dfxIz7oL*x7(y?dQrD!ZS#Qd^} zDsLG!Wd565c*<%-7)zTPLG$|Z&^MQFp-n)r>$`>#y;fCej!hp4ry`)KY;$e7)zI(a zgJo_h*Sza25l5B}3(wHC#?$Z!vdiG^f7ZpnxBr15(UOH zkamp*%2fpmsga#q+kQ`FG?9QPlga8jOWb^R(h9FKQ3Md~)2q`f5d+g!iCtQAr zEHjYoHniPIz5+_zIh!cMg`r(J_=c5$qS}VEtjr8Gm&IQ6^5V^~3$ivvPi?G|K?t=< zo|V0xm4K=dx_7A-7F4p)?XAJo!mOys?XK&uAdyj-@-}(2G(;G)Butq9fKf9OQ&>=bjQ%m z&^W^L-oN0jx8Ay+?)h-eS?9xEXYIYeZ1$*o1phALJ>y;HhduW*XIAvz_Emnd$>^%Y zcEvNbDL$aT^MU9FlMA`dQzoXjpKTyi)`TJ>wZ76*^!P+6s4Zoe|1#W?{oyWaH_U$_ z8oN*ObcAt0#H&UA0^qgJDsqE8_PO$CF=By=;C1U;j7yVYky=Q+)X5M_`Cd>W@@6V3 zaj5=MoGxT3DXQuuhWhlNLs%6k<|5j9)%!(_`R!}%^bQA8?HEQwF z>SEi6H=(EKz<6E^LAye5v5sP8TbzgZ!b0i#`_mM6p~o+zWld7n-Ol}M8b;NKdCogAiD#>qbI<@E zbeEZL5B}$#ca5BR%4fIt^}c~R59(B(&6j*!u#Mr?W{fJbp>W`@;jgJ<$vfh6`pURZU!9`Xh2j%GB&m4zs=uq**Q+43U|ouGF*96VJ=|DS2A&Zyp8v+kn{7X@vW5!@>Xb-4)Cb(H7{e&+$~wp zi^6%FxOy51vVR#CD(jC(*(jAmWVK+dmSSMn9)SjeQtqQZCdf)j3B%9zE&igijiZQk zv*DC=tXp7>PqmRElwHu1WMqN;o4)zkN&P`u)Wi%kI_R?Lw2nz-QP;{KW~8LJB4}?E z*Fsz5GRGagfA^Wcspoc|e?9+H+*C?iwY5<3^^)w1vvJ@Xv zmwGyP44$RHVDx}LFQ*twur5PWBqEm)Xc$rL3rC}U)B2bv#sW3})ct(7rk^U%6gkt+ zJxIwWD(lmx#lw5VB9@feB{nGaLTgQAkv_1)v^A_F05FuaIJKR~6>y#puR6U-RY2?( zdsaViq!ZYvtxP~(%MIw+VjOd@V4K_WO5Uuq_)7kZEV{;_D!b4v1sfA&g&O%i<$y5A zem&#r%^Lk15#5Hyq^aV0s(HR*IWKt?c$4(~8HhaL{Se1>Laj9I2d{FP;H0AW^bkPq ztl(`Np%yHJ#Cw4@BRJ9yrG6Oasr%UK9(ky7e1;#iK=HH%M$jgcLiYTVHoqKmXC!BT ze&}vCH8Xf(JGq(!15)Qy)zSn#%>x6XkFw0_bD=p6Fs&~(i>k1pHUTY|Y6c;V>qq@? zk>rF&%Is|$z(d$W?f@{=2SOUEJ2@O5P#QtXY*84XUI$NI8lGRM~vr_ zek$1U?RnccU?M!A*l~l6>3)*y0_^MHr*P!kVh>7mA@c!RSW0XEb_+m8UgXIc_O-fD zQZOGlKnOFgLwyHrqf4J_shg+{z?=sFiF6U%!!B!6(cB*z7s51Vh0WBHdZ;3_y{UQ*++Gv<3i0t2Dx%d6Zd+5O<0!G` zvHWVLp30z=^fgOoI%aEWa=s+Fj7ql?_8~A#W8%7+`YYO+^J?u62+%ju70U+-qjB_s zbzmYErxZBjV-19F92sa0G{XzF4@wFf9*=&fTMY|!=N-379Y4O{E;VIQ9DRm?k%xqe zdw_kfLqm0`%(&d)w8VMcB|xIX$Np0Q35F*h`YuCB78twz=WCBbpG1(8A_v8obe0{2 z0R`clJV*eDb=ra&bQ}4iTM_uw3JsMJjybR7I__X*i=**i$725^tT+g{c9;UO^sP0@ ztgx?rdo?LM3J_Fwm`Mi@L_|<}7eZzIP)3&(XUUL0uEbFsmp|DQj)KtxiRpW)aQhsc z0hfTY2yXy>m6$p2ga*s$up1Hkk5c$tZ%P%4fu92y$iR@mO$%qG>s?H3@lq!p zSRr*GAg_IbTvT3*R2nQk&FLP$@@tb98rw;BRq}{8Y1*Xq{$u`lzTOcZiWjaxAgleljKX)>Lw_JefHC?@Czw8WJ*W@ z6H)6hKVtbzz{M!X*G%nzE8eE#k~EAIK;?kvWAZK9TV5*VL-WW89CI1EBqME&vd9S+ zBy=Bv_)m?6q+y#z=pY?tPXKaQR;bxQIuTb9lJCTsdD{%(gGS zy6JctZvdC*Q010+VB(YRbW@T;dDmKCgyxGJUtPa=Q#@u*151c!6N|V`uyt54h`wFd zVp7GO-YJ>+E&BbsuG(br^_u|1v*y6VY2j(9THe@bWb$&a_3ho)#<`RH&9+BA!HS*P z-f~Pn@!8Y;Ct2N{**gh{4u`>tI;we$L+BCi}Z`WOK9chq# zcJ-jLR7uAr*`6ew<6v#Eyuc2{ggPm*sD<_llho(dB-U?72tMz^v8b`_z2 zx?dMKa6zEBeA&?6r{?3Pi=thqkGaWEuHSMtIOoj9MBX{&@lazw_r@bG_(%T%k?3-a zf8&Y*0L3D^qA>9^Q~k%ngI`U;5pFtAizgDc=)-0qD9+^v_^0X?mZ}u(l(qX#m|vyI zNZ-ii+g;nDS}kIcnwSgZ#_5f}2^z6eh?d|NcJYt~=#NiM5iTGa(^%$q!d$bNb(_Xf{Wx_balozS(>Cy`pCpzhO#V5R)}U4}9_F}C);M(vOV^qer+ZjUW=7i{ z8gd}+OQ(Ybl7?U+^Mxiz!+I5;t!gw=;6mjuD$Lb?DfD{)tE`9^sy`FRh4d*8M2e>) zIG-Cc=)||6f_+T> zG7k1kkef85-Tn#AaE=SHHEsAF0_cl^eiRgBVPu_DwR0M=|5CoU15fa-Gl_7|REuzm z{frK#GJ9xpcuI7zt+cY($x|R&?sGT;mW=OxEzA_NwJ__H*plWDZ^58--yhrlx=GS}on3;3m&{|1V}(p3mH81BrR*(b-=C4_ z&DKz=PG5FN(W>zpYwOw~O7Y4ev{04FQk z5glzv`{gkT-!BOFw@ER{LBiE@_bt{4m!%KC*W&ui_Lmx-mha6nJohjmFAw0<_jdxI zk&>uJB0W&c9NodvG*4^gE`C=Y_8cV21XSgYEkt$|r}AnSy>OIbWKuKZMPc*u7|i`8 zoeE!AyNMm6*L6Gl^q!C!N*KO-2kJ&ToEVSZdr$rC&X{=a$_o>L=%2i_%s^5s1&5F1 z^D)U3=8t0z{V)&u=CuY=vHl%uSspqWpPm{GARAmZT%PQOVQS&BD=ad$vmbSX!79%Z|BI~soA9THyv7%;<*gVM$$QD^m$f%pA&)qV2 z{cE=NOPYAO#6-3sesd>2P;0}gm+8N*f3g14<2LJ3=x^Y?z1?dkB>cMsqi)I%?vejH z1OMNf<9{LlzquS!*6b8!3SL>J93GCP*e?77VY@@MhzGbEfX66nZ-NFnh=n?)exE1_ zuE>L~)SvzD#Jg?OJR7(`1bMS|2ktexCtXaQc$}Q487Tf4-G?`pA75EZ0T&$NZ4Z0g zDQ#20<#SER5S^(4^RS&FopP14fMRx-r^$}(ull+iUzy^TMVyG9RDrX~nXOJhn$7)8 x8{M5t{t}I<(vGT9O;*3dT>$*MZ^+}R%vOg6~rE- z9j#DALq$>45{jk-p-E^Why)GM63dm!o_|ShNnsG(xIsp#N zXoB$FjkxEP?VT^)Vs#-X!X>c50?gH0@s4(%M;Ev7{(e3?6+cDw7V z*22R5Rl#cQ-GLv2FdLx4c#vev-^WX`H6UDdZrK)b4e)Si0Ne%^f=c_cIhK2{3A(WJ zJxNH;V3{h;F!It9kt&zvdZx|Z4QQuZ7b4Q0zP_~;_vJhKW1gKp#FlcM7WqJq+!(I> z%w9RiA>8AN9KXrY5ODbV_{B3h-w1qb_o}{Dm>Hk9cfjQxEe_b5c%av6r8?MC?E%Id z0foB{Ic;OJD%g+3R&E+G*s{YKQ-33cKj$CIXo{%Jb^IC)Wb9u}mlrLsYgIebZo52B zMGWN4svi#yq@Q|bpUor2dI+;Y%7!{2KtjA9WiiCh-Rl68_m855#o@K1Sj!%B8LjI#cS`rCi zyG3>m5Eb>Cv~%UjHjW#%c|}2m3w}JWkdbe)YL6(D{I$#F_jbVdj{#hBx%7Tn|4{T1 zANNGz%TJY#ygRh-6FX$vv4!-E&h1c3g7e;1>CU?)3x>o)mQ8T%8vfv_T`Kf@!8>EHUIQi!k7{|y3MtG?~x=)N4MeD!cNDXmbIadQ5~Pp z)j$F?mRTOmgXVHgd%@z!#@FXc?2tP13+M8lh%nv@Qw$_*iujU3kV*C%r{^eGlQ=?wz#-rA9|(UzADou}6E{>b z>XBmuX!F#Q0Gk3{Z(OK^4X$wjhtNM%RbRo?oVm=ND242Th6K&vq>Z7{D~>#-0cq8& zT_k!jygJ!b9>;7zvqBoht@Dg96)^Xng%(zSsJH)zK($rL62D;TJYvHsd$+|k2Q*&D zXlC`D@yOX6F>ZU?(3X-rx=7CmZP0-b>e|p{V-+bSctmq{<1qH+ymzfSZ z>@8gv#POMo+>tXd2nDeuNaWd*VPz?tilSN9#{WzxC|y&c_|`3Mr>%ta)LKu)jd-GfG}j zQJGR<(&Z(JrQU*2+~G(B?KP<7h@MO!Qg!M2ql+3>D7M~nmy)fqcfvhmv~VQCOcT$- zNyg9DYBC;sBgY1|WWt75p|-ZSelR~XQ2m|R!& zJBX5N9wbY3lxJHHFb{tYZ(#&}4}-9-z40W+L;CgJo9s2NLo1E@t2CY3JJgk_vprjb zG&1HkMd+j^x14qSaw|%dq?Wm)&&UOz62=&|{T`+>fLR&GU$u-b8c%7Y0SaVg-o}T1 z;Wh0rG54pvY%!031cw2Z=Lq;B1~Ez%UJE5e`rhx<-09AWt#@C=M-|JKzL)JS0c@o{ z?XJqpya>-84lJsgXuqjZs|)HK*iZ}oPLqv_fIMU&r9(yaeDX@IG-JN-Skr`62`G8Z zLk~0P3shdds+?m&4j!teW%DOkCjFnN5pm$;e3eOa0Z$RIAS9@vzO< ze_0DSFUAF>Dtj+>5`(!3d#Pqkp&7sb+4sX#RKBAv(=?F&Ss7_}&^B|!iNrK_v@r3_ zo))al@-F!5$YgY6l@DFzY?>2Mc2Vv4?9oZup8m+5%6~fKSe?a~-5{V_9MV#2M7y znQs1Ih zu_s5v(r4z&S1Ae5`zRRc&4}?Hx>_2t^_p@y*kl&qSgt=#=HD#5d}U-!x&)+Gm=XkS zh6O&TNyBMT4?--ARR&9SQ7}KV=tZ#=sVhv6dZ8V@U3QiL$ta!rW8Rc=Rblwr+K~rA zIPT;#%nHgz*XAQjd%U<#DZOfWE~K4fokpmW+Ir5%b-#U|sqvwCESZ19l4d_81rH{1 z06iT~enWFY9f&^mad>KrACeV+YUG(hu3MnS$Q%XV`Gb)4$!1FFAC=Dk;V`RGVL1nC z)3Lk6lrSWWg$*2exr2-RG-c%7xnGZk7Br-tgX33(OM(rdJREA%j@^~?sZ7~QxqZ!H zc=(wxR7%39T{7q+u=H_-dIh!Y9+jFbSPq_$@#K`=qk=&a-ugtVKJo7@DJDUnU_k7Q zJs3&+ygq^J_2P6MJRP?KwWm3&KTNWAPFY)hwwC&N0w?2X$+QMZnu$UY9150-cbvC~ zT;vALscZXV&LVz_(23m^bGoG*NS4J~SLcpczzjQgu-y=LX}4MYsoxl;mltLCENHWQvFZ_;1Rn1!2Ls0 zm!hIMSAzv$@;oHe%Ll#m?D{Mw*sHi&u=23CyF0KmxrN4W4#w%#Qu^)1ryck5`yZ>Sf!73y*yb_8 zQhB8n8nwRu$4d^VTq{PgW1nXYGeGX&4b3(+tqq^S`9?iPC0OIYaYnc9dn&nkyJ|Uu zgI1X8OMi#ao=a^1wV3tVYQq*b(z12pj$4C}U-ksOW?nvUL|>;O9A=b+ytJ`pBHc4_ z46dZB-((|&wj2e62Xkz0N#rJ#V1FF27q#6d-Cy2H3kK%lxC^-Y8a`maCs%1;Ra07) zxr8ORP+*?Rl{ZU|{$teb!|d|>K@1&skKp|1#Z3R-Y+(C?X%>IELHeE#4@(|86V{q| zrUf+y@1rnRp;_b+A?t>QPT2l48>KuIg`pE8LG9B`?86VMxYgaG{p+nG7uDaY8D@u< zCFjd_(4Y(>JhxNHVesX%ymg9=i5AfA&SM>JXYF%`l<<*?h;?LHw#1{rbDLlvkyRPh zLBaD#AVLB!;bcU>#lnWwWY5Y0NZH(ZQ z+%7%S1ws$+SVY|GbbTv@pCWBTSKuM^@(9xEmUtZ;g1s3%a7IC`K|V!uBzBQO@=*@6$8wDW?HMEdg(>; zj{^2PPwp;lt?JQaVv#av(dh!}hL^p*auRXT6Ow8pBZNzDm$>o*uhu;(Kd3I=@9x5#o+o}5N2Y;%N#tA|ck+9{@P8hci>a%2>FtI}~(HSfs$ zJ=B%62}24GZ0(G=`#-X3%!9bp!=ql1~Ri{Izj90qs;0_de_nWZr(#!z4lscJDry^WlNmV!;TI6Mvmt{M3Eh$WEXDDjYhSn+;cFL}WuN2QRu5 z^YCh*QGv=s2~$!EvAp#9?bhJCDUBdkvbS;Ieo@Ic0mKa%n^K$seQs;S(i!X+=^=AF zW+N$UC8<>H0Pq==_Z2nuDT|C*uywBy{A}iq+VIMz{on6^l8m2vr7s(kEe7F&1Ba&i zjWVtP87|(Vf})q}4M3(G$I!cVgTRmt#^H)dklj%VQG~IzjaP^VEUO?s!nAK~!^75> z`jG6@(>lL(LBpt0fpNMYK+F>9YD@fVf#6~Tt5p?#_wad?6m2jGs-Hqqg@ga=_Qn#a zCYmg+@fsrE%G>ryy%d(|{YIcAX3~t3NWu9LZyYcdCScDlr3n~WRua-A*OP5)wT^%= z6*KS&3Isjn3ua}vwMKY7HM8_>&EgoWOt{}f=3&e9Dqot1#ISBavM2XaZ;Yb073N=< z5U!d|fq5U>9>KuyxUab5YqqWdBq?n^VsS15fcl}hzO5OuIwqCn`9~}hyi1nI+BWGj zlexqiv*BN@o^M$}wFI6I1uoA}K6naYsi>X7MHccY5I@3n)ysPNxMhxx3E*=gn%jLR11>6pPBKi9^K0v zUUhzjzq;=`<^QJep#1W>#egKJ1G8p#o9QZioUlhwny;om8mq|XvB>%3O1(-eAg)d~ z{RQ~D&P@t8$KA5j$eCfz2LB_EO$Fwj&Y>i;;NJ`&(0c3Y12t2))Bd7hB_-BG#vRG9WvPMimOTWQupZxeoWV#dA-9=Eh^ck6%$8(^1KWJt z(^+xOhE5%m)Av(3HuoWe_keq;l<&#?ccTO2ZHin0ZD@c=#wDiv0J1~ zMpFpyr*;Ru)~MFk7M_V`heH!xW_KNF`V0I`gC^dc3~1A*w!xw{IvQc)WHNODHP|hG ze%CLlKcJR}7a_-0x#dyELFlO|0>8zTNTHu{i0~*w0+6qz&jg+S%T4#{b})UmRiJKt zu?L{%T29dCRv;l_(k)~Qa-}~jTZ6@RvLj8qd@FZ$ci!BA4rm%ku614!XXOaVdRN>H z#xI#o3FG~PO!={f5XsiooCP_iat)V3hbd-duJ{v>gQ0xZ3`@lcLA-621 zz%jo;jZ9V%%Fmrq?=Drazvf=W;bMS)$Ue7FWSkV%Ts-d>v+QZ^lqLE&o9m+#vTKGb zHyvM9>GPnV?kylfozzx zO72ezd!6|&dqusBocwm9xom8Fft&{qB(9da*}B&u8!VTO=r$0L`V)yy*^9qgjn`AI zBN|kkA2D$38dA)l2yY{1tNY3;u%F?n9u_1{v)ho4+0nH#EO(=LacgmQa1h28kSeI3 zXdC=-qk`qs<^9?i)nU09AwR03iPr$++ed*UfS=pLFM1GYo}1J-5JZ!}+Kze(xJ1WW z3&4@FnIA+3tD3&F-V$4xg2ZY(YHJS+-|4eXFq@qQPTO znh|85)(-ow&&tGepytg!zCV}PIzW!tGr5B`D1+Mcqel)9^4M|l;#c>vPy_K|%qPPJ z=SZ1C-3M8aju*^fzLP3s*;$_ql&Fo=!o^2o2v!9 zcqd%Q-Q0EWkT>PzQMDAYfqd>VQj%&26fMr8Ql4msIb>=A1Hhgxv)^H>jhNY`O8nib z1HN`bn$W_;>~bzY#x`$NL}cj+wkJbb1qS6v&KX@U0%fNM-iWcCE^eNevYmZ3U}hv z1oBGBJ~`hoU0vkORvQm6+)@`CR|1*E^&;=nFb6Z~@5a&JqhaafG-V#}x4MN0 zbaqK%8bDNTqg5u(TE_x$6s5_-5DL`%*Y=?fnUKO1Bb`dT^&0V#f=g}leu~w6moJTK zeT9V##$5`10W;Ze68|JJtL{Ploa1~ZpA}L2Cux`CCTR4t784ceHwpUR$|>k&p~N<6 zyU#xjrTwABo%GruHx++phcI@ztXdT>HTsx|ah&bGm&{x>b~h#FxQ`?u!+IyB zpruk9`zC4SCyO|d;SBhko>}EJ4wte#snZ{Mj~z?08(F-ITUZ1SKg+_;bxe@%rcV&QfTVrWLJWBj#;kU0f6@h8f^(hL4Js z{fxvvt-LELm+>!7MHL8)9N)Ng%-y7a_(vL)q%j*e<4ZBARQ~||d;Y&Jp;~8Z|5yt* zH@g^O;(wa=$=5Y_O6vc#8~(@H_5UINw{MA+((hJhf4|&)dlI7YM7QcnI58p;5ms2m z_{){Voh+=AQQZ99e!U`)evWB@_cX-vzbvEw_J=oLU-oe?wBfGnRAfs~s!mre=Q5VS zj;I+ZcJg=k#j#HpxWzr>%k8vH{4_<{b^2B7t`Q?>8#vied?7yR2nxBg6A0>n`^s*2 zy-nM;Gf|oI$~G~pdo3{W;l=T(c*B~NX`SJsqnv9dm>_;=UNQ{*;y8$C&^C literal 0 HcmV?d00001 diff --git a/src/main/resources/tutorial/schematics/0-7.schematic.gz b/src/main/resources/tutorial/schematics/0-7.schematic.gz deleted file mode 100644 index b4a38d844c0e8ae3562505bce52370c823529ce3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3099 zcmc(g`#%#3AIE#t=^|QB4&@-PZgi!?Vy^392+tb8&S7^n!lcU+JyBE?EkxWQsT-^<}0B~ z7!2HaosIO`oYoX>(ClhJyb$iq+B{bSIc}74edx5Q$0q)zDs_!kCTFOFaMld5+lr=Y zHep5HvAWm^DZwo2B@7qkWJ;Bro#-C3cM2S4RzQ08RfvtUri;ZBc9Oix>!v$29; zrN1?6=drhNe-Wam>_bWG$uow-_oL4kB65n0YomrZ&Vmm9=b>+(G?-G3py;OGwL)z8 zF1{;g%;qu$GLo=|!|zi)an19CP7m~zJ-G}J4U8=0ingkI2w^FzwH;83q8GugxGH~( zQ7uI{B)euuhx_k;^(ZIo_Yj6c-U3U0H}y!!5wwMk`!)EG#gg!c=Y$vEY-E@~WG9#x zY7T$gkMf6Dzc0Qy_3%yETELwcunzw5lQ-Rx@aYG-0dSWQpM3jB$N7Dz&d{f|+y_`Y zR=7(ru9?z*a7{&+VyOm(ZPdk8nMc2MM3nx9Trpv-k!U5D9o5#`R%IPa=e2_ipypPnShLY_*agXANdmnEG+?asy= zDI01Y=sT1$ie4o8 znRmR?D7=p&h$wL1zE*yu(`FYBE1j(~#W~{jO?+~pyNx}CBUGy|SdRN>!iU*-Bdtj# zMpOQr6X}{)*6lfgXuwD_$&FVOwV+V1W?VvUD%n42Wi89Z$=1YDJk z4O!6KyOpn4xJrRVNiN=mhgC?D3I@$O#i<{ge)a-oE+;O1J1Q`Ir#wKA#*s-0P^0p% z7z&P<*aL2@{hqF%Qf8AsAdH(@^Z{mOh=g>g>=)$dzQtPOy&%8n9!{4STMMWT-wx== zlV?lqo_sXtb|BB%^ZLiB!7L=1)Y45-O4&tU{bg|aYN%-tVs6q;3|(CGdF7nTptLR~ zBrqs>Zbs;{H(r6W(pfjG@&=QSw=`cc$MiUk@awJMFi)WgR$S-FJ?FBju`%Ir4I1|W ziH{Ul!I`J-AGKMi1q|2ht2eDHR>7T z#^UbrGry)!xE*+My;1hiA}11mMQA0mZ5)rCw`pQ8hMAs^Up?B;t`2`OHVQr5tnNJw z6ka_`B%#nox&1is%$LrQ=p?;EI!@`0ia8tYiLMfH`2ddNqsPJ3SF=KcbgJXW$^78f zY>zr(bvrRfmH)-8+6hnujpD6!6DoI`J^ z{ZYj#(}3%1o6T*gA;WgI zA>G!1R5DW0-c$MrJs3@Y_R|q1wpc&8Zi?e@H`B*wvp4 z$WR5^yniz^_iI~n8-lI-F3^JDO(Rv22emtoOl*35ef2&Ov3vy_Pv%lQ2fY&5>Vd-E zlVJrsW8U&`@c!o>oyKPyBKOLOV9S zYk`Ejv|=%!KYcN?WFlzC_6cN2(o86u_TjRkL^pYBzD$^8xsaItvQ5(#;XW-_1Fbu_fKwpfPdn#5PI#V61Cq&w{ zWMr^m-AG_OJnqJxDCSNUyo60%)-9jeYe;15H$D1G4J6Am02sh5XrVDcLAEDe963If zv76p7rV+PPijI7|1ccjmquZAZ)y9uARKc7Gc`p%nS?!pHYSmzYHDM3K?=en}Mdm=j zY>SY=Wdo!OK1kG5G9rAji)?TLa#Jqm%p_exY-Bg~QAg&MfPb`+@9}y|SM+560?1#t zrYgvV6Jbo{B%7h{*mwFas7bJ$8cC9UsA6+4ZK`wUlZ_U_Ta_YLPeMZ>6Z8!^Rzze2d)8C z!2xOG&9bUJ(yPlOq}bO|o93)Bc4ni%);R4yEjh4!(Io=Sb!)}kv3A2CFFlbw6O|{3 z?zTT~4AdZism|-AE$0~SkJ?&D-mnoPVgqK^Dc=bf7&Vq%8Pm8vE4@|yRGd9Mqu&sr z;H%kspo;j!fD(vPUp;ggvnL_&(1K9)uThY89r1?$_Xa>5&nVv?;F(leSXfEkGP(xu zVh6NU8El`GnMj@kEH%M1Tmr(P?Pas|tg}O8dA-DFX)^8pU=N40I19?gaVoETe63b0^QB~$}3-_A&q&cR0z5MX4LKUiD(ELKu zd9-z{F~rRk#?znuln3Y9H(KRKsb#!Pm^wUurO$pFUi#iQc0zM1yq4A+a15#5^w#*e+{tb=Te15{Q8iL3O8Hy&+W=i+nu=^keUy=Pw)#tueQaEjvd z+_JJGzkU$3{zwf8bGU*;$F0=Imwd*2Fh>{8!uPf5qIo^fwk=TGtA4%N?UPkbJ(C5j z5e~VY*l+-?sgu$*y@vlJJo(o2l2E=C<`qe~9wla5l3Py0_^24c^gEuD0d%0{&dZ z^!KHLsTpxKnxc=lGLFTf;^aaGgO!JD6f}%4b0Yg)G*F8w%MY3Ey<7422k|j-C0-a* zfR`xa7GHvrR^&_XL2}LPT}n-heo7+tu7oi%E4zVwiwD}Ro9cWG{xZD=HNT_!run-5 z-WH0L-W&F;$%sl}cuTloVG)?7sb7&zUz5ownjv#a>lgU?6t%idMVVj5m+e5}@F=BF zs%4&xp2&iNO{Av)bjyhAPjKrH$=JFo&z&Ltn%BM~Sp$*aQ*YlA JO(bvH@PAhRB%c5P diff --git a/src/main/resources/tutorial/schematics/0-env.schematic.gz b/src/main/resources/tutorial/schematics/0-env.schematic.gz deleted file mode 100644 index 7ec81c29999966e7a57976653c71faa70d0575c1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3942 zcmeH}`BxH%+Q&P0#;m+*?@TVGrB0cddrt04H>`0owbv#w1u54|Ma2a{(c5iYN|Pot zOBBZx%|Re9iUNvbE{yxQq99T#AR#C!ZUkK4^WHz={&1gjp7WgZ{PH~Kd!FZWz9vOS z4*h>fX8obYKOzr*yb$->fN=;)!{*45^|#v#Nc*oc@AqgKy*45JOsU7b#!?&zMZ-rk z5Al8n%Ji~-{tNrg8yV_MBSLx(Veae~K9W9QM7_B%d<~YEd<}Yo zs7)L^U21m*^kxZ{-QAg!_gHbPJYLxu4zZkJVdc{aC=>{iQeNxVoVS9T^~k#1>Xw;_ z`j%Ld> zm)~}Rjn|5jgO?;Dtwj+BIDo%6aYCnnuTuV1v2f}&b0`i0;h(6 zcy)RN-HD-e=}obXymxF(?ERhVVO>w}X>8=E?p|~J>9+H=OU<48b2%)eSHQAMRS!=$ zot-}8Pz^4Q0lLzI^L)6UuD9Xdvg67tSfg4s$BEWn9XrAOcYxV?J^7+x=6CeCueq(iH za>Ba3uwVv$I>bFGa=ivR%y74tfTmC+@)-lED315ayzPAna&^DvusEeSAC`nRq081i zrsV_LxrLz0VzB5Rfs>cBe`9)tWf``;Kitsc0>&VlQXQABNY7wD|8J8`f7~DZ-+ssj zD)2%|*#2-I_+7c_bsBGH6RUGqyWbl7cB^Ho#U=$3+067rb4QdStKS(mKE`<&=VLCL zXCwuuKfLCN4?^%`gn}k%GD*1D{FGna<}ZNqItXoRS)5JzK+|bz85G#Mp_fS!BXSPm)5FTQwrf&1S&@v z(D5Dv$nIL~CCGEY<>W1ibJJ;d0kH-Mp1h-fUe2)ANpSj%aaLdDXhBKc`$il0PjM7q zwxX{mCv0o@Y5x25|6Bf(6zFJCT>3J}9IIAs?aCA;L)&Xz>ajJig|cep#**;==vj>` zNNydu4~jJM_P^f2|N85IN)T5KhSrCCyrcb>q+lInvsbxBEW(e5<250nZspeMTO_sGg5lDh%A}wFSaW?(jpCf(X)$8jM`^Sb!T9W>*3|>*f(B_C;)F^ zOP)Ad=LC#dGJa_4UP7#`@zvpY>DOLJ4hb!o z&+HXX8rRjyE`mmeQjc<=m&ScMDjKX=nTGoTFdYX$ zBEyR5BDUic^%d$RX};|})*moq_t$84#a?D8hqLQB6^Y?YoSz;YkfF_VqNSPhO%yW1 zAm8{t-Ho#!cN4#m7t-c&g^UmW4ycd_lrbYu zKHK;Cg{#@Jj!WCZHuoh!rRtlZs_`Zig5-CYPGuVTc|B)W4T%jKZ1ihqu-o?v%_u<_ zf5DF{Pvfj`GDeN(rwxax8Jf*>$ZD;iRroinzetEIzi*Tod5r`_%dA0NqM9hJXEA>m zeedo`=2ny>V;ez2mql~h69+77+k--t03guF2||c~`r4LFF_Cw4HthhoAMW0aB$38oXsn|C->(OFP)rQ$$Le z7X$iooAN2k!Dal5Wo-^Zc<@dD8Vau0(yePJrPElsp${5X z`oC&~E*Kz8rzU=;P*tyboVl1`au)1zU_sf|tz$#J2+7 zx+X`7HRXnKr!@TEI{rZS+ZU#Sx`^cpiUwu?%7M?lyW&&ORCM z-~W8mqOKi97#<@fe))OIpbS(;3%{KNc!|AG%(W@ThlCl^EYmo@>{#hHstUtzI5X#e zRaq%@y(G3jloB$hegIjWbyb3@-AFac7S<(#Ed^G=YwdF_CP*Ky?efiXgI4qjoj6pS zAq@P_nH?&KGZz(5l#S105}xF(3TLZY*#ORm1eaqEUI~LpJ%28gcahbU1@kW1lhZ{2 zOwqw$Vh-J*`MD&K>l~XHwsDBRDC7?cugtI9HCy@Z+K$=-ahzOw34bUN&hbh8Xu(_F zwzzcc_a+`=WNw^T3PGBV5Pi6R9$X?ToE{WQ4cdq;^tjQMbG4#>N3Fhc5##Tgo#4bW z@r{gfjM43~8%3mMBfgIrim`M{aN1jAFVAirpn@=+v7yaGf3kMgCT4`f>Na~EulJXe z=k{^_Ji)CSBYlSPwdoxIaoh5GLtf+A;_l@tQ9sZTL;3ZjG3`yjz!6q=!bZ68k0tH& zLv!mtU4UgY!@!TJ4FK@xdD=eqb$DXx#UR;L7I5d4+ol-|GeLV2HLBia*>B+|D79(1 z=&k}YS~1{TizXB<>OF_JYL5<-#2Q9`ow)A?>mm3f+nf#&y`;5@lC^UFIVPmdAz-ZC z3vlK|PM|>H!o`B7b1q^iT5<`%80*2FQ`DQtZUx?r^Y7grWxA&Ae7^vSDd^N`SCxai z?8thB<|CRx@S_oY_As4pFK&d6)N5s^qYdJXKDnHjG@>g`EyZiTqnBA6^ol0I-5rN* zsG|Ov8-qWY`?>xoxH~`(X8X{hFtFT9ug>_QI`IU^#Zj*8q}D*I=0v?>2N%-8kUnZ* zC+|REwLJPKa4NN#PES~eZE@*T7i3f=#SqK4lON;i0wdEXYE@hU#95YuLI=sRKNX zaqW!}P$p%#@;2EYGt;D5L)}aD^V~61=j@^b;+qagLQ1=Pd`hEuu9Bp|1AoBV$aH1k|B94Fd?N0E|^C;w)5PdwvWyG>)6Sx)qdw z?W{mv#&CWa=NKF~`rO<{&iK+Dd1S@3Qsn2jr~EiA;1Q+jSYSA&ZGC$&f*=;149ggD zgiAJd7d#@%>+`YhMe$;HIDrrJsMm^J?bva)b1HNe(<*U8Bhes;Q|Q5j za?gfJb(nLxCLZNV(zD3OM5akbXg2>Em8zAb`%5cR<3Gtu{CAgsE5P`B&6klbuN<`q z=$)PO<;$*!Sse(WSEE$**>ZGs&hGXmoS(#d^@-KBFXX9J%)sj0&B;J-Wzx=G5_(*; z>Ft@L*zH-%*4s5O0;Dd2%E7 Nn?>7q^WSM7`WGd})b{`Y From 068002a5040a5fd4f78efca473f78f28b97834e6 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 26 Apr 2025 22:08:14 +0200 Subject: [PATCH 087/175] implement split_core functionality for reviews --- .../commands/review/CMD_EditFeedback.java | 10 +- .../database/providers/ReviewProvider.java | 110 +++++++++++------- .../plotsystem/core/menus/FeedbackMenu.java | 4 +- .../core/menus/PlayerPlotsMenu.java | 14 ++- .../core/menus/PlotActionsMenu.java | 18 +-- .../menus/review/ReviewPlotTogglesMenu.java | 44 +++++-- .../plotsystem/core/system/plot/Plot.java | 29 ++--- .../core/system/plot/utils/PlotUtils.java | 2 +- .../core/system/review/PlotReview.java | 54 ++++++--- 9 files changed, 171 insertions(+), 114 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index 33006f9e..7b442cc3 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.commands.review; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; @@ -75,7 +74,8 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - if (!plot.isReviewed() && !plot.isRejected()) { + Optional review = plot.getLatestReview(); + if (review.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLOT_EITHER_UNCLAIMED_OR_UNREVIEWED))); return; } @@ -90,12 +90,6 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N for (int i = 2; i <= args.length; i++) { feedback.append(args.length == 2 ? "" : " ").append(args[i - 1]); } - Optional review = plot.getLatestReview(); - if (review.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().error("Could not retrieve latest review!"); - return; - } boolean successful = review.get().updateFeedback(feedback.toString()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, plot.getID() + ""))); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 24cc6980..b02009b2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -10,10 +34,7 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import java.util.*; public class ReviewProvider { @@ -65,7 +86,7 @@ public ReviewProvider() { } public Optional getReview(int reviewId) { - String query = "SELECT plot_id, rating, feedback, score, reviewed_by, review_date FROM plot_review WHERE review_id = ?;"; + String query = "SELECT plot_id, rating, score, split_score, feedback, reviewed_by FROM plot_review WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, reviewId); @@ -74,17 +95,14 @@ public Optional getReview(int reviewId) { if (!rs.next()) return Optional.empty(); int plotId = rs.getInt(1); - String feedback = rs.getString(3); - int score = rs.getInt(4); - UUID reviewedBy = UUID.fromString(rs.getString(5)); - - String ratingString = rs.getString(2); - int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); - int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - HashMap toggleCriteria = getReviewToggleCriteria(reviewId); - ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); - - return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); + int score = rs.getInt(3); + int splitScore = rs.getInt(4); + if (rs.wasNull()) splitScore = -1; + String feedback = rs.getString(5); + UUID reviewedBy = UUID.fromString(rs.getString(6)); + + return Optional.of(new PlotReview(reviewId, plotId, rating, score, splitScore, feedback, reviewedBy)); } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -93,7 +111,8 @@ public Optional getReview(int reviewId) { } public Optional getLatestReview(int plotId) { - String query = "SELECT review_id, rating, feedback, score, reviewed_by, review_date FROM plot_review WHERE plot_id = ? ORDER BY review_date DESC LIMIT 1;"; + String query = "SELECT review_id, rating, score, split_score, feedback, reviewed_by FROM plot_review " + + "WHERE plot_id = ? ORDER BY review_date DESC LIMIT 1;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); @@ -102,17 +121,14 @@ public Optional getLatestReview(int plotId) { if (!rs.next()) return Optional.empty(); int reviewId = rs.getInt(1); - String feedback = rs.getString(3); - int score = rs.getInt(4); - UUID reviewedBy = UUID.fromString(rs.getString(5)); - - String ratingString = rs.getString(2); - int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); - int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - HashMap toggleCriteria = getReviewToggleCriteria(reviewId); - ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); - - return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); + int score = rs.getInt(3); + int splitScore = rs.getInt(4); + if (rs.wasNull()) splitScore = -1; + String feedback = rs.getString(5); + UUID reviewedBy = UUID.fromString(rs.getString(6)); + + return Optional.of(new PlotReview(reviewId, plotId, rating, score, splitScore, feedback, reviewedBy)); } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -122,7 +138,7 @@ public Optional getLatestReview(int plotId) { public List getPlotReviewHistory(int plotId) { List reviews = new ArrayList<>(); - String query = "SELECT review_id, rating, feedback, score, reviewed_by, review_date FROM plot_review WHERE plot_id = ?;"; + String query = "SELECT review_id, rating, score, split_score, feedback, reviewed_by FROM plot_review WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); @@ -130,17 +146,14 @@ public List getPlotReviewHistory(int plotId) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { int reviewId = rs.getInt(1); - String feedback = rs.getString(3); - int score = rs.getInt(4); - UUID reviewedBy = UUID.fromString(rs.getString(5)); - - String ratingString = rs.getString(2); - int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); - int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - HashMap toggleCriteria = getReviewToggleCriteria(reviewId); - ReviewRating rating = new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); - - reviews.add(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); + int score = rs.getInt(3); + int splitScore = rs.getInt(4); + if (rs.wasNull()) splitScore = -1; + String feedback = rs.getString(5); + UUID reviewedBy = UUID.fromString(rs.getString(6)); + + reviews.add(new PlotReview(reviewId, plotId, rating, score, splitScore, feedback, reviewedBy)); } } } catch (SQLException ex) { @@ -149,6 +162,13 @@ public List getPlotReviewHistory(int plotId) { return reviews; } + private ReviewRating getReviewRating(int reviewId, String ratingString) { + int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); + int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); + HashMap toggleCriteria = getReviewToggleCriteria(reviewId); + return new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); + } + public boolean updateFeedback(int reviewId, String newFeedback) { String query = "UPDATE plot_review SET feedback = ? WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -162,19 +182,21 @@ public boolean updateFeedback(int reviewId, String newFeedback) { return false; } - public boolean createReview(Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { + public boolean createReview(Plot plot, ReviewRating rating, int score, int splitScore, UUID reviewerUUID) { boolean result = DataProvider.PLOT.setMcVersion(plot.getID()); if (!result) return false; // Create Review - String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) " + - "VALUES (?, ?, ?, ?);"; + String query = "INSERT INTO plot_review (plot_id, rating, score, split_score, reviewed_by) " + + "VALUES (?, ?, ?, ?, ?);"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plot.getID()); stmt.setString(2, rating.getRatingDatabaseString()); stmt.setInt(3, score); - stmt.setString(4, reviewerUUID.toString()); + if (splitScore == -1) stmt.setNull(4, Types.INTEGER); + else stmt.setInt(4, splitScore); + stmt.setString(5, reviewerUUID.toString()); result = stmt.executeUpdate() > 0; } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 73d882fb..08af473b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -72,7 +72,7 @@ protected void setMenuItemsAsync() { getMenu().getSlot(10).setItem(new ItemBuilder(BaseItems.REVIEW_SCORE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.SCORE), AQUA, BOLD)) .setLore(new LoreBuilder() - .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY).append(text(plot.getTotalScore(), WHITE))) + .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY).append(text(review.getScore(), WHITE))) .emptyLine() .addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) .append(Utils.ItemUtils.getColoredPointsComponent(review.getRating().getAccuracyPoints(), 5) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 7b657d6f..991ddf31 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -145,23 +145,25 @@ protected Mask getMask() { */ private LoreBuilder getLore(Plot plot, Player p) { LoreBuilder builder = new LoreBuilder(); + + Optional review = plot.getLatestReview(); + int score = (review.isEmpty() || plot.isRejected()) ? 0 : review.get().getScore(); if (plot.getPlotMembers().isEmpty()) { // Plot is single player plot builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY) - .append(text((plot.getTotalScore() == -1 ? 0 : plot.getTotalScore()), WHITE))); + .append(text(score, WHITE))); } else { // Plot is multiplayer plot builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.OWNER) + ": ", GRAY) .append(text(plot.getPlotOwner().getName(), WHITE))); builder.emptyLine(); - int score = (plot.getTotalScore() == -1 ? 0 : plot.getTotalScore()); builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY) .append(text(score + " ", WHITE)) - .append(text(LangUtil.getInstance().get(p, LangPaths.Plot.GroupSystem.SHARED_BY_MEMBERS, Integer.toString(plot.getPlotMembers().size() + 1)), DARK_GRAY))); + .append(text(LangUtil.getInstance().get(p, LangPaths.Plot.GroupSystem.SHARED_BY_MEMBERS, + Integer.toString(plot.getPlotMembers().size() + 1)), DARK_GRAY))); } - Optional review = plot.getLatestReview(); if (review.isPresent()) { ReviewRating rating = review.get().getRating(); builder.emptyLine(); @@ -187,7 +189,7 @@ private LoreBuilder getLore(Plot plot, Player p) { } builder.emptyLine(); - if (plot.isReviewed() && plot.isRejected()) builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.REJECTED), RED, BOLD)); + if (plot.isRejected()) builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.REJECTED), RED, BOLD)); builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.STATUS) + ": ", GRAY) .append(text(plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), WHITE))); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index bc179ed6..a4eaa68d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -1,7 +1,7 @@ /* * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -48,13 +48,13 @@ public class PlotActionsMenu extends AbstractMenu { private final Plot plot; - private final boolean hasFeedback; + private final boolean hasReview; public PlotActionsMenu(Player menuPlayer, Plot plot) { super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getID() + " | " + plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), menuPlayer); this.plot = plot; - hasFeedback = plot.isReviewed() || plot.isRejected(); + hasReview = plot.getLatestReview().isPresent(); } @Override @@ -80,14 +80,14 @@ protected void setMenuItemsAsync() { } // Set teleport to plot item - getMenu().getSlot(hasFeedback ? 12 : 13) + getMenu().getSlot(hasReview ? 12 : 13) .setItem(new ItemBuilder(BaseItems.PLOT_TELEPORT.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.TELEPORT), GOLD).decoration(BOLD, true)) .setLore(new LoreBuilder().addLine(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.TELEPORT)).color(GRAY), true).build()) .build()); // Set plot abandon item - getMenu().getSlot(hasFeedback ? 14 : 16) + getMenu().getSlot(hasReview ? 14 : 16) .setItem(new ItemBuilder(BaseItems.PLOT_ABANDON.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.ABANDON), RED).decoration(BOLD, true)) .setLore(new LoreBuilder() @@ -98,7 +98,7 @@ protected void setMenuItemsAsync() { .build()); // Set plot feedback item - if (hasFeedback) { + if (hasReview) { getMenu().getSlot(16) .setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA).decoration(BOLD, true)) @@ -142,19 +142,19 @@ protected void setItemClickEventsAsync() { }); // Set click event for teleport to plot item - getMenu().getSlot(hasFeedback ? 12 : 13).setClickHandler((clickPlayer, clickInformation) -> { + getMenu().getSlot(hasReview ? 12 : 13).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); plot.getWorld().teleportPlayer(clickPlayer); }); // Set click event for abandon plot item - getMenu().getSlot(hasFeedback ? 14 : 16).setClickHandler((clickPlayer, clickInformation) -> { + getMenu().getSlot(hasReview ? 14 : 16).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); clickPlayer.performCommand("plot abandon " + plot.getID()); }); // Set click event for feedback menu button - if (hasFeedback) { + if (hasReview) { getMenu().getSlot(16).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); clickPlayer.performCommand("plot feedback " + plot.getID()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 6590ca76..4fc20fc5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.menus.review; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -117,10 +141,10 @@ private void submitReview() { int totalRating = rating.getTotalRating(); double scoreMultiplier = DataProvider.DIFFICULTY.getDifficultyByEnum(plot.getDifficulty()).orElseThrow().getMultiplier(); - double totalRatingWithMultiplier = totalRating * scoreMultiplier; - int score = (int) Math.floor(totalRatingWithMultiplier); + int score = (int) Math.floor(totalRating * scoreMultiplier); + int splitScore = plot.getPlotMembers().isEmpty() ? -1 : (int) Math.floor(score / (plot.getPlotMembers().size() + 1d)); - boolean successful = DataProvider.REVIEW.createReview(plot, rating, score, getMenuPlayer().getUniqueId()); + boolean successful = DataProvider.REVIEW.createReview(plot, rating, score, splitScore, getMenuPlayer().getUniqueId()); if (!successful) { getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); return; @@ -129,7 +153,7 @@ private void submitReview() { Component reviewerConfirmationMessage; if (!isRejected) { reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), getParticipantsString())); - if(!acceptPlot(totalRating)) return; + if(!acceptPlot(score, splitScore)) return; } else { reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), getParticipantsString())); PlotUtils.Actions.undoSubmit(plot); @@ -169,7 +193,7 @@ private String getParticipantsString() { } } - private boolean acceptPlot(int totalRating) { + private boolean acceptPlot(int score, int splitScore) { getMenuPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.SAVING_PLOT))); Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { try { @@ -185,23 +209,23 @@ private boolean acceptPlot(int totalRating) { plot.setStatus(Status.completed); // Remove Plot from Owner - if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(plot), -1)) return false; + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plot.getID()), -1)) return false; if (plot.getPlotMembers().isEmpty()) { // Plot was made alone // Builder gets 100% of score - return plot.getPlotOwner().addScore(totalRating); + return plot.getPlotOwner().addScore(score); } else { // Plot was made in a group // Score gets split between all participants - if (!plot.getPlotOwner().addScore(plot.getSharedScore())) return false; + if (!plot.getPlotOwner().addScore(splitScore)) return false; for (Builder builder : plot.getPlotMembers()) { // Score gets split between all participants - if (!builder.addScore(plot.getSharedScore())) return false; + if (!builder.addScore(splitScore)) return false; // Remove Slot from Member - if (!builder.setSlot(builder.getSlot(plot), -1)) return false; + if (!builder.setSlot(builder.getSlotByPlotId(plot.getID()), -1)) return false; } } return true; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index dc2886f7..6898dad0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -162,19 +162,6 @@ public T getWorld() { } } - public int getTotalScore() { - Optional review = getLatestReview(); - return review.map(PlotReview::getScore).orElse(-1); - } - - public int getSharedScore() { - int score = getTotalScore(); - if (score != -1 && !getPlotMembers().isEmpty()) { - return (int) Math.floor(score / (members.size() + 1d)); - } - return score; - } - @Override public byte[] getInitialSchematicBytes() { return DataProvider.PLOT.getInitialSchematic(getID()); @@ -197,6 +184,14 @@ public Optional getLatestReview() { return DataProvider.REVIEW.getLatestReview(getID()); } + public boolean isReviewed() { + return getLatestReview().isPresent(); + } + + public boolean isRejected() { + return (getStatus() == Status.unfinished || getStatus() == Status.unreviewed) && isReviewed(); + } + public boolean setPasted(boolean pasted) { return DataProvider.PLOT.setPasted(getID(), pasted); } @@ -231,14 +226,6 @@ public boolean removePlotMember(Builder member) { return false; } - public boolean isReviewed() { - return getLatestReview().isPresent(); - } - - public boolean isRejected() { - return (getStatus() == Status.unfinished || getStatus() == Status.unreviewed) && getTotalScore() != -1; // -1 == null - } - public static boolean meetsPlotDifficultyScoreRequirement(@NotNull Builder builder, PlotDifficulty plotDifficulty) { int playerScore = builder.getScore(); int scoreRequirement = DataProvider.DIFFICULTY.getDifficultyByEnum(plotDifficulty).orElseThrow().getScoreRequirement(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 353fe135..0a965212 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -292,7 +292,7 @@ public static void checkPlotsForLastActivity() { if (inactivityIntervalDays == -2 && rejectedInactivityIntervalDays == -2) return; for (Plot plot : plots) { LocalDate lastActivity = plot.getLastActivity(); - long interval = (plot.isRejected()) ? rejectedInactivityIntervalDays : inactivityIntervalDays; + long interval = plot.isRejected() ? rejectedInactivityIntervalDays : inactivityIntervalDays; if (interval == -2 || lastActivity == null || lastActivity.plusDays(interval).isAfter(LocalDate.now())) continue; Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 844b6d89..25254671 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -1,3 +1,27 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.system.review; import com.alpsbte.plotsystem.PlotSystem; @@ -16,16 +40,18 @@ public class PlotReview { private final int plotId; private final ReviewRating rating; private final int score; + private final int splitScore; private final UUID reviewedBy; @Nullable private String feedback; - public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, @Nullable String feedback, UUID reviewedBy) { + public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, int splitScore, @Nullable String feedback, UUID reviewedBy) { this.reviewId = reviewId; this.plotId = plotId; this.rating = rating; this.score = score; + this.splitScore = splitScore; this.feedback = feedback; this.reviewedBy = reviewedBy; } @@ -38,6 +64,12 @@ public ReviewRating getRating() { return rating; } + public int getScore() { + return score; + } + + public int getSplitScore() { return splitScore; } + public @Nullable String getFeedback() { return feedback; } @@ -58,10 +90,6 @@ public UUID getReviewerUUID() { return reviewedBy; } - public int getScore() { - return score; - } - public boolean updateFeedback(String feedback) { if (DataProvider.REVIEW.updateFeedback(reviewId, feedback)) { this.feedback = feedback; @@ -71,22 +99,23 @@ public boolean updateFeedback(String feedback) { } public boolean undoReview() { - Plot plot = DataProvider.PLOT.getPlotById(this.plotId); + Plot plot = getPlot(); if (plot == null) { - PlotSystem.getPlugin().getComponentLogger().error(text("Plot of review could not be found!")); + PlotSystem.getPlugin().getComponentLogger().error(text("Could not undo review with the id (" + + reviewId + "). Plot with the id (" + plotId + ") not found.")); return false; } // remove owner score and remove plot from slot - if (!plot.getPlotOwner().addScore(-plot.getSharedScore())) return false; - if (plot.getPlotOwner().getFreeSlot() != null - && !plot.getPlotOwner().setSlot(plot.getPlotOwner().getFreeSlot(), plot.getID())) + if (!plot.getPlotOwner().addScore(splitScore == -1 ? -score : -splitScore)) return false; + if (plot.getPlotOwner().getSlotByPlotId(plotId) != null + && !plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plotId), plotId)) return false; // remove members score and remove plot from slot for (Builder member : plot.getPlotMembers()) { - if (!member.addScore(-plot.getSharedScore())) return false; - if (member.getFreeSlot() != null && !member.setSlot(member.getFreeSlot(), plot.getID())) + if (!member.addScore(-splitScore)) return false; + if (member.getSlotByPlotId(plotId) != null && !member.setSlot(member.getSlotByPlotId(plotId), plotId)) return false; } @@ -94,7 +123,6 @@ public boolean undoReview() { plot.setPasted(false); DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); - return DataProvider.REVIEW.removeReview(reviewId); } } From a1a80d5c81f33e14b16147ebb2476aa57c8f987b Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sun, 27 Apr 2025 18:18:56 +0200 Subject: [PATCH 088/175] fix leaderboard query and remove player ranking in action bar --- .../plotsystem/core/EventListener.java | 2 +- .../database/providers/BuilderProvider.java | 106 ++++++++---------- .../database/providers/ReviewProvider.java | 44 +++----- .../leaderboards/LeaderboardEntry.java | 49 -------- .../leaderboards/ScoreLeaderboard.java | 90 +-------------- .../menus/review/ReviewPlotTogglesMenu.java | 8 +- .../core/system/plot/utils/PlotUtils.java | 4 +- .../core/system/review/PlotReview.java | 36 ++---- 8 files changed, 89 insertions(+), 250 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index cf6fb85e..703e1c04 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -208,7 +208,7 @@ public void onPlayerChatEvent(@NotNull AsyncChatEvent event) { feedbackInput.getReview().updateFeedback(messageComp.content()); ChatInput.awaitChatInput.remove(playerUUID); event.getPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(event.getPlayer(), - LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, String.valueOf(feedbackInput.getReview().getPlotId())))); + LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, String.valueOf(feedbackInput.getReview().getPlot().getID())))); } else if (input instanceof PlayerInviteeChatInput inviteeInput) { Player player = Bukkit.getPlayer(messageComp.content()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 62e3b575..16cbe375 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -26,7 +26,6 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardEntry; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; @@ -34,7 +33,6 @@ import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Slot; -import javax.annotation.Nullable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -275,71 +273,38 @@ public List getReviewersByBuildTeam(int buildTeamId) { return builders; } - /** - * Retrieves the leaderboard entry for a specific player based on their UUID and the specified timeframe. - * The leaderboard entry includes the player's score, rank, and total number of players. - * - * @param uuid the unique identifier of the player. - * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). - * @return provides the leaderboard entry for the player, or null if not found. - */ - public LeaderboardEntry getLeaderboardEntryByUUID(UUID uuid, LeaderboardTimeframe sortBy) { - return null; // TODO: fix leaderboard query - /* - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(uuid, sortBy))) { - stmt.setString(1, uuid.toString()); - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new LeaderboardEntry(rs.getInt(2), rs.getInt(3), rs.getInt(4)); - } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null;*/ - } - /** * Retrieves the leaderboard entries for all players within a specified timeframe, including their names and scores. * * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). * @return provides a map of player names and their scores, or null if no data is found. */ - public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { - return null; // TODO: fix leaderboard query - /* + public LinkedHashMap getLeaderboardEntries(LeaderboardTimeframe sortBy) { try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(null, sortBy))) { + PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(sortBy))) { try (ResultSet rs = stmt.executeQuery()) { - Map playerEntries = new HashMap<>(); + LinkedHashMap playerEntries = new LinkedHashMap<>(); while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); return playerEntries; } } catch (SQLException ex) { Utils.logSqlException(ex); } - return null;*/ + return null; } /** - * Constructs an SQL query to retrieve leaderboard data, optionally filtering by a specific UUID - * and sorting based on a given timeframe. + * Constructs a SQL query to retrieve leaderboard data by sorting based on a given timeframe. * - *

If a UUID is provided, the query will calculate the leaderboard position for the specified - * UUID and include the total number of leaderboard entries matching the timeframe criteria. - * If no UUID is provided, the query will return the top leaderboard entries ordered by score + *

This query returns the top leaderboard entries ordered by the score * within the specified timeframe.

* - * @param uuid the unique identifier of the builder for which to calculate the leaderboard position. - * If {@code null}, the query retrieves the top entries instead of a specific position. * @param sortBy the timeframe used to filter entries. Determines the minimum date for reviews * (e.g., daily, weekly, monthly, yearly). * @return the constructed SQL query as a {@code String}. */ - private static String getLeaderboardQuery(@Nullable UUID uuid, LeaderboardTimeframe sortBy) { - // TODO: fix leaderboard query + private static String getLeaderboardQuery(LeaderboardTimeframe sortBy) { String minimumDate = switch (sortBy) { case DAILY -> "(NOW() - INTERVAL 1 DAY)"; case WEEKLY -> "(NOW() - INTERVAL 1 WEEK)"; @@ -348,21 +313,44 @@ private static String getLeaderboardQuery(@Nullable UUID uuid, LeaderboardTimefr default -> null; }; - return "SELECT b.name, b.score" + (uuid != null ? ", ROW_NUMBER() OVER (ORDER BY b.score DESC) AS position" : "") + - (uuid != null ? ", (SELECT COUNT(*) FROM builder_has_plot bhp_sub " + - "INNER JOIN builder b_sub ON b_sub.uuid = bhp_sub.uuid " + - "INNER JOIN plot_review r_sub ON r_sub.plot_id = bhp_sub.plot_id " + - (minimumDate != null ? "WHERE r.review_date BETWEEN " + minimumDate + " AND NOW()" : "") + ") " + - "AS total_positions" : "") + - " FROM builder_has_plot bhp " + - "INNER JOIN builder b ON b.uuid = bhp.uuid " + - "INNER JOIN plot_review r ON r.plot_id = bhp.plot_id " + - (minimumDate != null - ? "WHERE r.review_date BETWEEN " + minimumDate + " AND NOW()" - : "") + - (uuid != null - ? "WHERE b.uuid = ?;" - : "ORDER BY b.name, b.score DESC LIMIT 10;" - ); + return "WITH latest_reviews AS ( " + + " SELECT pr.* " + + " FROM plot_review pr " + + " INNER JOIN ( " + + " SELECT plot_id, MAX(review_date) AS latest_review_date " + + " FROM plot_review " + + " GROUP BY plot_id " + + " ) latest ON pr.plot_id = latest.plot_id AND pr.review_date = latest.latest_review_date " + + "), " + + "plot_member_counts AS ( " + + " SELECT plot_id, COUNT(*) AS member_count " + + " FROM builder_is_plot_member " + + " GROUP BY plot_id " + + "), " + + "all_builders AS ( " + + " SELECT " + + " p.owner_uuid AS builder_uuid, " + + " p.plot_id " + + " FROM plot p " + + " WHERE p.status = 'completed' " + + " UNION ALL " + + " SELECT " + + " bipm.uuid AS builder_uuid, " + + " bipm.plot_id " + + " FROM builder_is_plot_member bipm " + + " JOIN plot p ON p.plot_id = bipm.plot_id " + + " WHERE p.status = 'completed' " + + ") " + + "SELECT b.name, SUM( " + + " IF(pmc.member_count IS NULL OR pmc.member_count = 0, lr.score, FLOOR(lr.score / (pmc.member_count + 1))) " + + ") AS total_score " + + "FROM all_builders ab " + + "JOIN builder b ON b.uuid = ab.builder_uuid " + + "JOIN latest_reviews lr ON lr.plot_id = ab.plot_id " + + "LEFT JOIN plot_member_counts pmc ON pmc.plot_id = ab.plot_id " + + (minimumDate != null ? "WHERE lr.review_date BETWEEN " + minimumDate + " AND NOW() " : "") + + "GROUP BY b.name " + + "ORDER BY total_score DESC, b.name " + + "LIMIT 10;"; } -} +} \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index b02009b2..da24ac34 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -86,7 +86,7 @@ public ReviewProvider() { } public Optional getReview(int reviewId) { - String query = "SELECT plot_id, rating, score, split_score, feedback, reviewed_by FROM plot_review WHERE review_id = ?;"; + String query = "SELECT plot_id, rating, score, feedback, reviewed_by FROM plot_review WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, reviewId); @@ -97,12 +97,10 @@ public Optional getReview(int reviewId) { int plotId = rs.getInt(1); ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); int score = rs.getInt(3); - int splitScore = rs.getInt(4); - if (rs.wasNull()) splitScore = -1; - String feedback = rs.getString(5); - UUID reviewedBy = UUID.fromString(rs.getString(6)); + String feedback = rs.getString(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); - return Optional.of(new PlotReview(reviewId, plotId, rating, score, splitScore, feedback, reviewedBy)); + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -111,7 +109,7 @@ public Optional getReview(int reviewId) { } public Optional getLatestReview(int plotId) { - String query = "SELECT review_id, rating, score, split_score, feedback, reviewed_by FROM plot_review " + + String query = "SELECT review_id, rating, score, feedback, reviewed_by FROM plot_review " + "WHERE plot_id = ? ORDER BY review_date DESC LIMIT 1;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -123,12 +121,10 @@ public Optional getLatestReview(int plotId) { int reviewId = rs.getInt(1); ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); int score = rs.getInt(3); - int splitScore = rs.getInt(4); - if (rs.wasNull()) splitScore = -1; - String feedback = rs.getString(5); - UUID reviewedBy = UUID.fromString(rs.getString(6)); + String feedback = rs.getString(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); - return Optional.of(new PlotReview(reviewId, plotId, rating, score, splitScore, feedback, reviewedBy)); + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -138,7 +134,7 @@ public Optional getLatestReview(int plotId) { public List getPlotReviewHistory(int plotId) { List reviews = new ArrayList<>(); - String query = "SELECT review_id, rating, score, split_score, feedback, reviewed_by FROM plot_review WHERE plot_id = ?;"; + String query = "SELECT review_id, rating, score, feedback, reviewed_by FROM plot_review WHERE plot_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plotId); @@ -148,12 +144,10 @@ public List getPlotReviewHistory(int plotId) { int reviewId = rs.getInt(1); ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); int score = rs.getInt(3); - int splitScore = rs.getInt(4); - if (rs.wasNull()) splitScore = -1; - String feedback = rs.getString(5); - UUID reviewedBy = UUID.fromString(rs.getString(6)); + String feedback = rs.getString(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); - reviews.add(new PlotReview(reviewId, plotId, rating, score, splitScore, feedback, reviewedBy)); + reviews.add(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } } } catch (SQLException ex) { @@ -182,9 +176,9 @@ public boolean updateFeedback(int reviewId, String newFeedback) { return false; } - public boolean createReview(Plot plot, ReviewRating rating, int score, int splitScore, UUID reviewerUUID) { + public PlotReview createReview(Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { boolean result = DataProvider.PLOT.setMcVersion(plot.getID()); - if (!result) return false; + if (!result) return null; // Create Review String query = "INSERT INTO plot_review (plot_id, rating, score, split_score, reviewed_by) " + @@ -194,21 +188,19 @@ public boolean createReview(Plot plot, ReviewRating rating, int score, int split stmt.setInt(1, plot.getID()); stmt.setString(2, rating.getRatingDatabaseString()); stmt.setInt(3, score); - if (splitScore == -1) stmt.setNull(4, Types.INTEGER); - else stmt.setInt(4, splitScore); - stmt.setString(5, reviewerUUID.toString()); + stmt.setString(4, reviewerUUID.toString()); result = stmt.executeUpdate() > 0; } catch (SQLException ex) { Utils.logSqlException(ex); } - if (!result) return false; + if (!result) return null; PlotReview review = plot.getLatestReview().orElseThrow(); HashMap allToggles = rating.getAllToggles(); for (ToggleCriteria criteria : allToggles.keySet()) { if (!addReviewToggleCriteria(review.getReviewId(), criteria, allToggles.get(criteria))) - return false; + return null; } @@ -217,7 +209,7 @@ public boolean createReview(Plot plot, ReviewRating rating, int score, int split for (Builder builder : plot.getPlotMembers()) { createReviewNotification(review.getReviewId(), builder.getUUID()); } - return true; + return review; } public boolean removeReview(int reviewId) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java deleted file mode 100644 index 99a860ab..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardEntry.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.holograms.leaderboards; - -public class LeaderboardEntry { - private final int score; - private final int position; - private final int totalPositions; - - public LeaderboardEntry(int score, int position, int totalPositions) { - this.score = score; - this.position = position; - this.totalPositions = totalPositions; - } - - public int getScore() { - return score; - } - - public int getPosition() { - return position; - } - - public int getTotalPosition() { - return totalPositions; - } -} \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index 748cfc42..1aa9af22 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -29,19 +29,9 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.holograms.HologramConfiguration; import com.alpsbte.plotsystem.core.holograms.HologramRegister; -import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; -import com.alpsbte.plotsystem.utils.io.LangPaths; -import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; -import eu.decentsoftware.holograms.api.DHAPI; -import eu.decentsoftware.holograms.api.holograms.Hologram; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; -import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -59,13 +49,6 @@ public ScoreLeaderboard() { super("score-leaderboard", null, false, PlotSystem.getPlugin()); setEnabled(PlotSystem.getPlugin().getConfig().getBoolean(getEnablePath())); setLocation(HologramRegister.getLocation(this)); - - Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> { - for (Player player : getPlayersInRadiusForRanking()) { - if (AbstractTutorial.getActiveTutorial(player.getUniqueId()) != null) continue; - player.sendActionBar(getPlayerRankingComponent(player)); - } - }, 0L, 20L); } @Override @@ -116,80 +99,17 @@ public List> getContent(UUID playerUUID) { lines.add(new HologramRegister.LeaderboardPositionLine(index + 1, null, 0)); } - Map playerRankings = DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard); + LinkedHashMap playerRankings = DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard); if (playerRankings != null) { - for (int i = 0; i < playerRankings.size(); i++) { - String key = (String) playerRankings.keySet().toArray()[i]; - lines.set(i, new HologramRegister.LeaderboardPositionLine(i + 1, key, playerRankings.get(key))); + int i = 0; + for (Map.Entry entry : playerRankings.entrySet()) { + lines.set(i, new HologramRegister.LeaderboardPositionLine(i + 1, entry.getKey(), entry.getValue())); + i++; } } return lines; } - private Component getPlayerRankingComponent(Player player) { - LeaderboardEntry leaderboardEntry = DataProvider.BUILDER.getLeaderboardEntryByUUID(player.getUniqueId(), sortByLeaderboard); - if (leaderboardEntry == null) return Component.empty(); - - // Start building the component - TextComponent.Builder builder = Component.text() - .append(Component.text(" " + LangUtil.getInstance().get(player, sortByLeaderboard.langPath)) - .color(NamedTextColor.GOLD) - .decorate(TextDecoration.BOLD) - ) - .append(Component.text(" ➜ ") - .color(NamedTextColor.DARK_GRAY) - .decorate(TextDecoration.BOLD) - ); - - if (leaderboardEntry.getPosition() == -1) { - builder.append(Component.text(LangUtil.getInstance().get(player, LangPaths.Leaderboards.NOT_ON_LEADERBOARD)) - .color(NamedTextColor.RED) - .decoration(TextDecoration.BOLD, false) - ); - } else if (leaderboardEntry.getPosition() < 50) { - builder.append(Component.text( - LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_POSITION, - String.valueOf(leaderboardEntry.getPosition()))) - .color(NamedTextColor.GREEN) - .decoration(TextDecoration.BOLD, false) - ); - } else { - String topPercentage = df.format(leaderboardEntry.getPosition() * 1.0 / leaderboardEntry.getTotalPosition()); - builder.append(Component.text( - LangUtil.getInstance().get(player, LangPaths.Leaderboards.ACTIONBAR_PERCENTAGE, topPercentage)) - .decoration(TextDecoration.BOLD, false) - ); - } - - if (leaderboardEntry.getScore() != -1) { - builder.append( - Component.text(" (", NamedTextColor.DARK_GRAY) - .append(Component.text(leaderboardEntry.getScore() + " " + - LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_POINTS), NamedTextColor.AQUA)) - .append(Component.text(")", NamedTextColor.DARK_GRAY)) - ); - } - - return builder.build(); - } - - private List getPlayersInRadiusForRanking() { - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - boolean actionBarEnabled = config.getBoolean(ConfigPaths.DISPLAY_OPTIONS_ACTION_BAR_ENABLE, true); - int actionBarRadius = config.getInt(ConfigPaths.DISPLAY_OPTIONS_ACTION_BAR_RADIUS, 30); - List players = new ArrayList<>(); - if (!actionBarEnabled) return players; - for (Player player : Bukkit.getOnlinePlayers()) { - Hologram holo = DHAPI.getHologram(player.getUniqueId() + "-" + getId()); - if (holo == null) continue; - if (player.getWorld().getName().equals(holo.getLocation().getWorld().getName()) && - holo.getLocation().distance(player.getLocation()) <= actionBarRadius) { - players.add(player); - } - } - return players; - } - @Override public long getInterval() { return PlotSystem.getPlugin().getConfig().getInt(ConfigPaths.DISPLAY_OPTIONS_INTERVAL) * 20L; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 4fc20fc5..3dc3b8b7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -32,6 +32,7 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; +import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.core.system.review.ReviewRating; import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; import com.alpsbte.plotsystem.utils.Utils; @@ -142,10 +143,9 @@ private void submitReview() { double scoreMultiplier = DataProvider.DIFFICULTY.getDifficultyByEnum(plot.getDifficulty()).orElseThrow().getMultiplier(); int score = (int) Math.floor(totalRating * scoreMultiplier); - int splitScore = plot.getPlotMembers().isEmpty() ? -1 : (int) Math.floor(score / (plot.getPlotMembers().size() + 1d)); - boolean successful = DataProvider.REVIEW.createReview(plot, rating, score, splitScore, getMenuPlayer().getUniqueId()); - if (!successful) { + PlotReview review = DataProvider.REVIEW.createReview(plot, rating, score, getMenuPlayer().getUniqueId()); + if (review == null) { getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); return; } @@ -153,7 +153,7 @@ private void submitReview() { Component reviewerConfirmationMessage; if (!isRejected) { reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), getParticipantsString())); - if(!acceptPlot(score, splitScore)) return; + if(!acceptPlot(review.getScore(), review.getSplitScore())) return; } else { reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), getParticipantsString())); PlotUtils.Actions.undoSubmit(plot); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 0a965212..528a5488 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -600,10 +600,10 @@ public static void sendFeedbackMessage(@NotNull List notific player.sendMessage(text(MSG_LINE, DARK_GRAY)); for (ReviewNotification notification : notifications) { PlotReview review = DataProvider.REVIEW.getReview(notification.getReviewId()).orElseThrow(); - player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(review.getPlotId())), GREEN))); + player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(review.getPlot().getID())), GREEN))); Component tc = text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_SHOW_FEEDBACK), GOLD) - .clickEvent(ClickEvent.runCommand("/plot feedback " + review.getPlotId())) + .clickEvent(ClickEvent.runCommand("/plot feedback " + review.getPlot().getID())) .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.PLOT_NAME) + " " + LangUtil.getInstance().get(player, LangPaths.Review.FEEDBACK))); player.sendMessage(tc); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 25254671..f40b3764 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.core.system.review; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -33,25 +32,25 @@ import java.util.UUID; -import static net.kyori.adventure.text.Component.text; - public class PlotReview { private final int reviewId; - private final int plotId; + private final Plot plot; private final ReviewRating rating; private final int score; private final int splitScore; private final UUID reviewedBy; - @Nullable - private String feedback; + @Nullable private String feedback; + public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, @Nullable String feedback, UUID reviewedBy) { + this(reviewId, DataProvider.PLOT.getPlotById(plotId), rating, score, feedback, reviewedBy); + } - public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, int splitScore, @Nullable String feedback, UUID reviewedBy) { + public PlotReview(int reviewId, Plot plot, ReviewRating rating, int score, @Nullable String feedback, UUID reviewedBy) { this.reviewId = reviewId; - this.plotId = plotId; + this.plot = plot; this.rating = rating; this.score = score; - this.splitScore = splitScore; + this.splitScore = plot.getPlotMembers().isEmpty() ? -1 : (int) Math.floor(score / (plot.getPlotMembers().size() + 1d)); this.feedback = feedback; this.reviewedBy = reviewedBy; } @@ -75,11 +74,7 @@ public int getScore() { } public Plot getPlot() { - return DataProvider.PLOT.getPlotById(plotId); - } - - public int getPlotId() { - return plotId; + return plot; } public Builder getReviewer() { @@ -99,23 +94,16 @@ public boolean updateFeedback(String feedback) { } public boolean undoReview() { - Plot plot = getPlot(); - if (plot == null) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not undo review with the id (" + - reviewId + "). Plot with the id (" + plotId + ") not found.")); - return false; - } - // remove owner score and remove plot from slot if (!plot.getPlotOwner().addScore(splitScore == -1 ? -score : -splitScore)) return false; - if (plot.getPlotOwner().getSlotByPlotId(plotId) != null - && !plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plotId), plotId)) + if (plot.getPlotOwner().getSlotByPlotId(plot.getID()) != null + && !plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plot.getID()), plot.getID())) return false; // remove members score and remove plot from slot for (Builder member : plot.getPlotMembers()) { if (!member.addScore(-splitScore)) return false; - if (member.getSlotByPlotId(plotId) != null && !member.setSlot(member.getSlotByPlotId(plotId), plotId)) + if (member.getSlotByPlotId(plot.getID()) != null && !member.setSlot(member.getSlotByPlotId(plot.getID()), plot.getID())) return false; } From 211887081019394a17f4694b1802998ba01efda2 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 19 May 2025 02:45:40 +0200 Subject: [PATCH 089/175] remove duplicate score column --- .../plotsystem/core/database/DatabaseConnection.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index 0da0633a..b37aa355 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -327,7 +327,7 @@ public static List getTables() { ");", // Review - "CREATE TABLE IF NOT EXISTS plot_review" + + "CREATE TABLE IF NOT EXISTS plotsystem_v2.plot_review" + "(" + " review_id INT NOT NULL AUTO_INCREMENT," + " plot_id INT NOT NULL," + @@ -336,10 +336,8 @@ public static List getTables() { " feedback VARCHAR(256) NULL," + " reviewed_by VARCHAR(36) NOT NULL," + " review_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + - " score int NOT NULL," + - " split_score int NULL," + " PRIMARY KEY (review_id)," + - " FOREIGN KEY (plot_id) REFERENCES plot (plot_id)" + + " FOREIGN KEY (plot_id) REFERENCES plotsystem_v2.plot (plot_id)" + " ON DELETE CASCADE ON UPDATE CASCADE" + ");", From 04d7b02513e0e56eeb6083735977a8b1d9ce2f08 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Fri, 23 May 2025 03:39:31 +0200 Subject: [PATCH 090/175] =?UTF-8?q?=F0=9F=90=9B=20Remove=20schema=20from?= =?UTF-8?q?=20statement=20&=20fix=20result=20set?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alpsbte/plotsystem/core/database/DatabaseConnection.java | 4 ++-- .../plotsystem/core/database/providers/BuildTeamProvider.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index b37aa355..f87c5369 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -327,7 +327,7 @@ public static List getTables() { ");", // Review - "CREATE TABLE IF NOT EXISTS plotsystem_v2.plot_review" + + "CREATE TABLE IF NOT EXISTS plot_review" + "(" + " review_id INT NOT NULL AUTO_INCREMENT," + " plot_id INT NOT NULL," + @@ -337,7 +337,7 @@ public static List getTables() { " reviewed_by VARCHAR(36) NOT NULL," + " review_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + " PRIMARY KEY (review_id)," + - " FOREIGN KEY (plot_id) REFERENCES plotsystem_v2.plot (plot_id)" + + " FOREIGN KEY (plot_id) REFERENCES plot (plot_id)" + " ON DELETE CASCADE ON UPDATE CASCADE" + ");", diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 91db667b..f7e3cbfe 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -40,7 +40,7 @@ import java.util.UUID; public class BuildTeamProvider { - public static final List BUILD_TEAMS = new ArrayList<>(); + private static final List BUILD_TEAMS = new ArrayList<>(); private final CityProjectProvider cityProjectProvider; public BuildTeamProvider(BuilderProvider builderProvider, CityProjectProvider cityProjectProvider) { @@ -112,6 +112,7 @@ public boolean addBuildTeam(String name) { PreparedStatement stmt = conn.prepareStatement(resultQuery)) { stmt.setString(1, name); try (ResultSet rs = stmt.executeQuery()) { + rs.next(); // get the last inserted build team id BUILD_TEAMS.add(new BuildTeam(rs.getInt(1), name, List.of(), List.of())); } } catch (SQLException ex) { From 7e693887d71391e87c2297d474dd7d189590510e Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 29 May 2025 15:00:05 +0200 Subject: [PATCH 091/175] =?UTF-8?q?=F0=9F=94=A7=20Add=20copyright=20config?= =?UTF-8?q?=20files=20&=20encodings=20to=20repo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/copyright/AlpsMIT.xml | 6 ++++++ .idea/copyright/profiles_settings.xml | 3 +++ .idea/encodings.xml | 10 ++++++++++ 3 files changed, 19 insertions(+) create mode 100644 .idea/copyright/AlpsMIT.xml create mode 100644 .idea/copyright/profiles_settings.xml create mode 100644 .idea/encodings.xml diff --git a/.idea/copyright/AlpsMIT.xml b/.idea/copyright/AlpsMIT.xml new file mode 100644 index 00000000..0ccafc12 --- /dev/null +++ b/.idea/copyright/AlpsMIT.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml new file mode 100644 index 00000000..521907dd --- /dev/null +++ b/.idea/copyright/profiles_settings.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 00000000..3f22c8f3 --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file From 5a1f9b0938735e7450b2fe61fab80ae47102d89d Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 29 May 2025 17:13:46 +0200 Subject: [PATCH 092/175] =?UTF-8?q?=F0=9F=94=A7=20Fix=20and=20improve=20ps?= =?UTF-8?q?s=20setup=20cmds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/admin/setup/CMD_Setup_City.java | 32 +++++++++++++++---- .../admin/setup/CMD_Setup_Country.java | 24 +++++++++++--- .../providers/CityProjectProvider.java | 8 +++-- 3 files changed, 50 insertions(+), 14 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 14432db7..272f6e1c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,12 +24,16 @@ package com.alpsbte.plotsystem.commands.admin.setup; +import com.alpsbte.alpslib.utils.AlpsUtils; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.CommandSender; import java.util.List; @@ -151,12 +155,17 @@ public void onCommand(CommandSender sender, String[] args) { } // Check if server exists if (!DataProvider.SERVER.serverExists(serverName)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + serverName + "!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with Name " + serverName + "!")); sendInfo(sender); return; } - int buildTeamId = Integer.parseInt(args[4]); + Integer buildTeamId = AlpsUtils.tryParseInt(args[4]); + if (buildTeamId == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build Team ID must be a number!")); + sendInfo(sender); + return; + } if (DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId).isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any build team with ID " + buildTeamId + "!")); sendInfo(sender); @@ -164,7 +173,18 @@ public void onCommand(CommandSender sender, String[] args) { } boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, buildTeamId, country.get().getCode(), serverName); - if (added) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with ID '" + cityProjectId + "' under country with the code " + countryCode + "!")); + if (added) { + try { + LangUtil.getInstance().languageFiles[0].set(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".name", cityProjectId); + LangUtil.getInstance().languageFiles[0].set(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".description", ""); + LangUtil.getInstance().languageFiles[0].save(LangUtil.getInstance().languageFiles[0].getFile()); // TODO Fix ugly config file + } catch (Exception e) { + PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for City Project " + cityProjectId + "!").color(RED), e); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for City Project " + cityProjectId + "!")); + } + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be the ID of the City & no description will be present!")); + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); + } else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); } @@ -180,7 +200,7 @@ public String getDescription() { @Override public String[] getParameter() { - return new String[]{"City-Project-ID", "Country-Code", "Server-Name", "Build-Team-ID"}; + return new String[]{"City-Project-Name", "Country-Code", "Server-Name", "Build-Team-ID"}; } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 519b9f94..56e418e4 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,13 +24,15 @@ package com.alpsbte.plotsystem.commands.admin.setup; -import com.alpsbte.alpslib.utils.AlpsUtils; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.CommandSender; import java.util.Arrays; @@ -129,7 +131,7 @@ public CMD_Setup_Country_Add(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 3 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 3) {sendInfo(sender); return;} String code = args[1]; if (code.length() > 2) { @@ -149,7 +151,19 @@ public void onCommand(CommandSender sender, String[] args) { String customModelData = args.length > 4 ? args[4] : null; boolean successful = DataProvider.COUNTRY.addCountry(code, continent, material, customModelData); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); + if (successful) + { + try { + LangUtil.getInstance().languageFiles[0].set(LangPaths.Database.COUNTRY + "." + code + ".name", code); + LangUtil.getInstance().languageFiles[0].save(LangUtil.getInstance().languageFiles[0].getFile()); // TODO Fix ugly config file + } catch (Exception e) { + PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for country " + code + "!").color(RED), e); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for country " + code + "!")); + } + + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + code + " language config setting, otherwise the name will be the ID of the Country & no description will be present!")); + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); + } else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 33b4ae5a..2d7616d8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -98,7 +98,9 @@ public boolean add(String id, int buildTeamId, String countryCode, String server stmt.setInt(2, buildTeamId); stmt.setString(3, countryCode); stmt.setString(4, serverName); - return stmt.executeUpdate() > 0; + boolean result = stmt.executeUpdate() > 0; + if (result) cachedCityProjects.add(new CityProject(id, countryCode, serverName, true, buildTeamId)); + return result; } catch (SQLException ex) { Utils.logSqlException(ex); } From efc155ffd374d9fbcab0c1f41d33bab68707167e Mon Sep 17 00:00:00 2001 From: Zoriot Date: Tue, 3 Jun 2025 21:23:02 +0200 Subject: [PATCH 093/175] =?UTF-8?q?=F0=9F=A9=B9=20Fix=20outline=20schem=20?= =?UTF-8?q?and=20better=20handling=20of=20isPlayerOnPlot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plotsystem/core/system/plot/utils/PlotUtils.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 528a5488..68b80689 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -151,7 +151,8 @@ public static AbstractPlot getCurrentPlot(@NotNull Builder builder, Status... st public static boolean isPlayerOnPlot(@NotNull AbstractPlot plot, Player player) { if (plot.getWorld().isWorldLoaded() && plot.getWorld().getBukkitWorld().getPlayers().contains(player)) { Location playerLoc = player.getLocation(); - return plot.getWorld().getProtectedRegion().contains(Vector3.toBlockPoint(playerLoc.getX(), playerLoc.getY(), playerLoc.getZ())); + ProtectedRegion protectedRegion = plot.getWorld().getProtectedRegion(); + return protectedRegion == null || protectedRegion.contains(Vector3.toBlockPoint(playerLoc.getX(), playerLoc.getY(), playerLoc.getZ())); } return false; } @@ -188,7 +189,7 @@ public static boolean isPlotWorld(World world) { try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { writer.write(new BlockArrayClipboard(region)); } - return null; + return outputStream.toByteArray(); } public static @NotNull String getDefaultSchematicPath() { From f8ac23b6f8c46de66f279d25a70639a2771656af Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 8 Jun 2025 16:35:24 +0200 Subject: [PATCH 094/175] update to langlibs 1.5 --- pom.xml | 2 +- .../com/alpsbte/plotsystem/PlotSystem.java | 1 - .../alpsbte/plotsystem/utils/io/LangUtil.java | 24 ++++++++++--------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/pom.xml b/pom.xml index 920bf04a..c3e37c7f 100644 --- a/pom.xml +++ b/pom.xml @@ -195,7 +195,7 @@ li.cinnazeyy LangLibs - 1.4.2 + 1.5 provided diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 2f63bf3f..dfb341a7 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -85,7 +85,6 @@ public class PlotSystem extends JavaPlugin { public void onEnable() { System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); // Disable Logging YamlFileFactory.registerPlugin(this); - li.cinnazeyy.langlibs.core.file.YamlFileFactory.registerPlugin(this); plugin = this; Component successPrefix = text("[", DARK_GRAY).append(text("✔", DARK_GREEN)).append(text("]", DARK_GRAY)).append(text(" ", GRAY)); Component errorPrefix = text("[", DARK_GRAY).append(text("X", RED)).append(text("]", DARK_GRAY)).append(text(" ", GRAY)); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java index b2d16235..687df7ca 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java @@ -26,27 +26,29 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.utils.Utils.ChatUtils; -import li.cinnazeyy.langlibs.core.Language; +import li.cinnazeyy.langlibs.core.LangLibAPI; +import li.cinnazeyy.langlibs.core.language.Language; import li.cinnazeyy.langlibs.core.file.LanguageFile; -import li.cinnazeyy.langlibs.core.language.LangLibAPI; import li.cinnazeyy.langlibs.core.language.LanguageUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; public class LangUtil extends LanguageUtil { private static LangUtil langUtilInstance; public static void init() { if (langUtilInstance != null) return; - LangLibAPI.register(PlotSystem.getPlugin(), new LanguageFile[]{ - new LanguageFile(Language.en_GB, 2.5), - new LanguageFile(Language.de_DE, 2.5, "de_AT", "de_CH"), - new LanguageFile(Language.fr_FR, 2.5, "fr_CA"), - new LanguageFile(Language.pt_PT, 2.5, "pt_BR"), - new LanguageFile(Language.ko_KR, 2.5), - new LanguageFile(Language.ru_RU, 2.5, "ba_RU", "tt_RU"), - new LanguageFile(Language.zh_CN, 2.5), - new LanguageFile(Language.zh_TW, 2.5, "zh_HK"), + Plugin plugin = PlotSystem.getPlugin(); + LangLibAPI.register(plugin, new LanguageFile[]{ + new LanguageFile(plugin, 2.5, Language.en_GB), + new LanguageFile(plugin, 2.5, Language.de_DE, "de_AT", "de_CH"), + new LanguageFile(plugin, 2.5, Language.fr_FR, "fr_CA"), + new LanguageFile(plugin, 2.5, Language.pt_PT, "pt_BR"), + new LanguageFile(plugin, 2.5, Language.ko_KR), + new LanguageFile(plugin, 2.5, Language.ru_RU, "ba_RU", "tt_RU"), + new LanguageFile(plugin, 2.5, Language.zh_CN), + new LanguageFile(plugin, 2.5, Language.zh_TW, "zh_HK"), }); langUtilInstance = new LangUtil(); } From 37862a99788a375a144509363e1a390c0b188413 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 8 Jun 2025 16:58:07 +0200 Subject: [PATCH 095/175] fix dynamically setting translations --- .../plotsystem/commands/admin/setup/CMD_Setup_City.java | 5 ++--- .../plotsystem/commands/admin/setup/CMD_Setup_Country.java | 3 +-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 272f6e1c..8cec0ba6 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -175,9 +175,8 @@ public void onCommand(CommandSender sender, String[] args) { boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, buildTeamId, country.get().getCode(), serverName); if (added) { try { - LangUtil.getInstance().languageFiles[0].set(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".name", cityProjectId); - LangUtil.getInstance().languageFiles[0].set(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".description", ""); - LangUtil.getInstance().languageFiles[0].save(LangUtil.getInstance().languageFiles[0].getFile()); // TODO Fix ugly config file + LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".name", cityProjectId); + LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".description", ""); } catch (Exception e) { PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for City Project " + cityProjectId + "!").color(RED), e); sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for City Project " + cityProjectId + "!")); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 56e418e4..237b3360 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -154,8 +154,7 @@ public void onCommand(CommandSender sender, String[] args) { if (successful) { try { - LangUtil.getInstance().languageFiles[0].set(LangPaths.Database.COUNTRY + "." + code + ".name", code); - LangUtil.getInstance().languageFiles[0].save(LangUtil.getInstance().languageFiles[0].getFile()); // TODO Fix ugly config file + LangUtil.getInstance().setDynamicKey(LangPaths.Database.COUNTRY + "." + code + ".name", code); } catch (Exception e) { PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for country " + code + "!").color(RED), e); sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for country " + code + "!")); From 88331248d1352c8e3d3a085fbcac5b6fbb61b576 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sun, 15 Jun 2025 23:03:16 +0200 Subject: [PATCH 096/175] =?UTF-8?q?=F0=9F=90=9B=20Fix=20wrong=20plot=20typ?= =?UTF-8?q?e=20query=20&=20cim=20plot=20resolution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- .../database/providers/BuilderProvider.java | 34 ++++++++++--------- .../core/system/plot/world/PlotWorld.java | 20 +++++------ 2 files changed, 28 insertions(+), 26 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 16cbe375..9df4af30 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -32,6 +32,8 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.enums.Slot; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.PreparedStatement; @@ -102,7 +104,7 @@ public boolean addBuilderIfNotExists(UUID uuid, String name) { return false; } - public boolean setName(UUID uuid, String name) { + public boolean setName(@NotNull UUID uuid, String name) { String query = "UPDATE builder SET name = ? WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -116,7 +118,7 @@ public boolean setName(UUID uuid, String name) { return false; } - public boolean addScore(UUID uuid, int score) { + public boolean addScore(@NotNull UUID uuid, int score) { String query = "UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -130,7 +132,7 @@ public boolean addScore(UUID uuid, int score) { return false; } - public boolean setSlot(UUID uuid, int plotID, Slot slot) { + public boolean setSlot(UUID uuid, int plotID, @NotNull Slot slot) { String query = "UPDATE builder b SET " + slot.name().toLowerCase() + "_slot = " + (plotID > 0 ? "?" : "DEFAULT(first_slot)") + " WHERE uuid = ?;"; @@ -146,14 +148,13 @@ public boolean setSlot(UUID uuid, int plotID, Slot slot) { return false; } - public boolean setPlotType(UUID uuid, int plotTypeId) { - String query = "UPDATE builder b SET plot_type = " + - (plotTypeId > 0 ? "?" : "DEFAULT(plot_type)") + " WHERE uuid = ?;"; + public boolean setPlotType(@NotNull UUID uuid, int plotTypeId) { + String query = "UPDATE builder b SET plot_type = ? WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { - if (plotTypeId > 0) stmt.setInt(1, plotTypeId); - stmt.setString(plotTypeId > 0 ? 2 : 1, uuid.toString()); + stmt.setInt(1, plotTypeId); + stmt.setString(2, uuid.toString()); stmt.executeUpdate(); return true; } catch (SQLException ex) { @@ -162,7 +163,7 @@ public boolean setPlotType(UUID uuid, int plotTypeId) { return false; } - public int getCompletedBuildsCount(UUID uuid) { + public int getCompletedBuildsCount(@NotNull UUID uuid) { String query = "SELECT COUNT(p.plot_id) AS completed_plots FROM plot p INNER JOIN builder_is_plot_member " + "bipm ON p.plot_id = bipm.plot_id WHERE p.status = 'completed' AND (p.owner_uuid = ? OR bipm.uuid = ?);"; try (Connection conn = DatabaseConnection.getConnection(); @@ -179,7 +180,7 @@ public int getCompletedBuildsCount(UUID uuid) { return 0; } - public Slot getFreeSlot(UUID uuid) { + public Slot getFreeSlot(@NotNull UUID uuid) { String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -197,7 +198,7 @@ public Slot getFreeSlot(UUID uuid) { return null; } - public Slot getSlot(UUID uuid, int plotId) { + public Slot getSlot(@NotNull UUID uuid, int plotId) { String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { @@ -216,7 +217,7 @@ public Slot getSlot(UUID uuid, int plotId) { } @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean canReviewPlot(UUID uuid, Plot plot) { + public boolean canReviewPlot(@NotNull UUID uuid, Plot plot) { // TODO: cache String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -237,7 +238,7 @@ public boolean canReviewPlot(UUID uuid, Plot plot) { return false; } - public boolean isAnyReviewer(UUID uuid) { + public boolean isAnyReviewer(@NotNull UUID uuid) { // TODO: cache String query = "SELECT uuid FROM build_team_has_reviewer WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -304,7 +305,8 @@ public LinkedHashMap getLeaderboardEntries(LeaderboardTimeframe * (e.g., daily, weekly, monthly, yearly). * @return the constructed SQL query as a {@code String}. */ - private static String getLeaderboardQuery(LeaderboardTimeframe sortBy) { + @Contract(pure = true) + private static @NotNull String getLeaderboardQuery(@NotNull LeaderboardTimeframe sortBy) { String minimumDate = switch (sortBy) { case DAILY -> "(NOW() - INTERVAL 1 DAY)"; case WEEKLY -> "(NOW() - INTERVAL 1 WEEK)"; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index 63645302..9137002a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.core.system.plot.world; +import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; @@ -117,8 +118,7 @@ public boolean unloadWorld(boolean movePlayers) { } } - Bukkit.unloadWorld(getBukkitWorld(), true); - return !isWorldLoaded(); + return Bukkit.unloadWorld(getBukkitWorld(), true); } return true; } else PlotSystem.getPlugin().getComponentLogger().warn(text("Could not unload world " + worldName + " because it is not generated!")); @@ -206,7 +206,7 @@ public boolean isWorldGenerated() { return mvCore.getMVWorldManager().getMVWorld(worldName) != null || mvCore.getMVWorldManager().getUnloadedWorlds().contains(worldName); } - private ProtectedRegion getRegion(String regionName) { + private @Nullable ProtectedRegion getRegion(String regionName) { RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); if (loadWorld()) { RegionManager regionManager = container.get(BukkitAdapter.adapt(getBukkitWorld())); @@ -226,7 +226,7 @@ public AbstractPlot getPlot() { * @param worldName - the name of the world * @return - true if the world is a plot world */ - public static boolean isOnePlotWorld(String worldName) { + public static boolean isOnePlotWorld(@NotNull String worldName) { return worldName.toLowerCase(Locale.ROOT).startsWith("p-") || worldName.toLowerCase(Locale.ROOT).startsWith("t-"); } @@ -234,7 +234,7 @@ public static boolean isOnePlotWorld(String worldName) { * @param worldName - the name of the world * @return - true if the world is a city plot world */ - public static boolean isCityPlotWorld(String worldName) { + public static boolean isCityPlotWorld(@NotNull String worldName) { return worldName.toLowerCase(Locale.ROOT).startsWith("c-"); } @@ -243,12 +243,12 @@ public static boolean isCityPlotWorld(String worldName) { * It won't return the CityPlotWorld class because there is no use case without a plot. * * @param worldName - name of the world - * @param - OnePlotWorld or PlotWorld * @return - plot world */ - public static T getPlotWorldByName(String worldName) { + public static @Nullable PlotWorld getPlotWorldByName(String worldName) { if (isOnePlotWorld(worldName) || isCityPlotWorld(worldName)) { - int id = Integer.parseInt(worldName.substring(2)); + Integer id = AlpsUtils.tryParseInt(worldName.substring(2)); + if (id == null) return new PlotWorld(worldName, null); AbstractPlot plot = worldName.toLowerCase().startsWith("t-") ? DataProvider.TUTORIAL_PLOT.getById(id).orElse(null) : DataProvider.PLOT.getPlotById(id); return plot == null ? null : plot.getWorld(); } From 727a446d1f86f865fe87405323dd9c66a3264d60 Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Mon, 16 Jun 2025 23:09:42 +0200 Subject: [PATCH 097/175] update language files to match latest string set --- src/main/resources/lang/de_DE.yml | 39 ++++++++++++++++++++++++++++- src/main/resources/lang/en_GB.yml | 2 +- src/main/resources/lang/fr_FR.yml | 38 ++++++++++++++++++++++++++++ src/main/resources/lang/ko_KR.yml | 40 +++++++++++++++++++++++++++++- src/main/resources/lang/pt_PT.yml | 40 +++++++++++++++++++++++++++++- src/main/resources/lang/ru_RU.yml | 40 +++++++++++++++++++++++++++++- src/main/resources/lang/zh_CN.yml | 41 +++++++++++++++++++++++++++++-- src/main/resources/lang/zh_TW.yml | 40 +++++++++++++++++++++++++++++- 8 files changed, 272 insertions(+), 8 deletions(-) diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index c3688210..788ac2b1 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -158,6 +158,11 @@ review: feedback: "Feedback" reviewer: "Reviewer" player-language: "Spielersprache" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "Genauigkeit" accuracy-desc: "Wie akkurat ist das Gebäude?%newline%%newline%- Sieht aus wie in RL%newline%- Korrekte Umrisse%newline%- Korrekte Höhen%newline%- Ist vollständig" @@ -172,6 +177,11 @@ note: wont-be-able-continue-building: "Du wirst auf diesem Plot nicht weiterbauen können!" score-will-be-split: "Die Punkte werden bei der Bewertung auf alle Mitglieder aufgeteilt!" player-has-to-be-online: "Spieler muss online sein!" + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'Gelesen' read-more: 'Mehr lesen' @@ -195,6 +205,7 @@ note: click-to-play-with-friends: "§7Willst du mit deinen Freunden spielen? §6Klicke hier..." tutorial-show-stages: 'Stages Anzeigen' click-to-open-plots-menu: 'Klicke hier, um das Plot Menü zu öffnen...' + click-to-toggle: "Click to toggle..." #----------------------------------------------------- #| Messages #----------------------------------------------------- @@ -219,6 +230,10 @@ message: removed-plot-member: "§a§6{0}§a wurde vom Plot entfernt §6#{1}§a!" left-plot: "§aVerlasse Plot §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lWARNING: §cDieser Plot wird automatisch aufgelassen werden!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§aSpeichere Plot..." creating-plot: "§aErstelle neuen Plot..." created-new-plot: "§aEin neuer Plot§a wurde für §6{0}§a erstellt!" @@ -244,6 +259,8 @@ message: cannot-undo-review: "Du kannst eine Bewertung nicht rückgängig machen, wenn du sie nicht selbst erstellt hast!" cannot-send-feedback: "Du kannst auf einen Plot kein Feedback geben, wenn du ihn nicht selbst bewertet hast!" cannot-review-own-plot: "Du kannst deine eigenen Plots nicht bewerten!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "Du hast keine Berechtigung dafür!" player-has-no-invitations: "Du hast keine offenen Einladungen!" player-is-not-allowed: "Du bist dazu nicht berechtigt!" @@ -266,6 +283,7 @@ message: chat-input-expired: "Die Eingabe ist abgelaufen." tutorial-disabled: 'Tutorials sind auf diesem Server deaktiviert.' tutorial-already-running: "Du hast bereits ein Tutorial am Laufen! Schließe dieses ab, bevor du ein neues beginnst." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Heute" @@ -408,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + #NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 07c2b7e0..26f364fe 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -446,4 +446,4 @@ database: windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index aed69477..ab88b4ec 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: 'Fermer' back: 'Retour' + continue: 'Continue' next-page: 'Page Suivante' previous-page: 'Page Précédente' error: 'Erreur' @@ -157,6 +158,11 @@ review: feedback: "Commentaires" reviewer: "Relecteur" player-language: "Langage du joueur" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "Précision" accuracy-desc: "Quelle est la précision du bâtiment?%newline%%newline%- Ressemble à RL%newline%- Contours corrects%newline%- Hauteur correcte%newline%- Est terminé" @@ -171,6 +177,11 @@ note: wont-be-able-continue-building: "Vous ne pourrez plus continuer à construire sur ce terrain!" score-will-be-split: "Le score sera partagé entre tous les membres lors de la révision!" player-has-to-be-online: "Le joueur doit être en ligne!" + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'Lire' read-more: 'En savoir plus' @@ -194,6 +205,7 @@ note: click-to-play-with-friends: "§7Vous voulez jouer avec vos amis? §6Cliquez ici..." tutorial-show-stages: 'Montrer les étapes' click-to-open-plots-menu: 'Cliquez pour ouvrir le menu des parcelles...' + click-to-toggle: "Click to toggle..." #----------------------------------------------------- #| Messages #----------------------------------------------------- @@ -218,6 +230,10 @@ message: removed-plot-member: "§aSupprimé §6{0}§a du tracé §6#{1}§a!" left-plot: "§aTracé de gauche §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lATTENTION: §cCette parcelle sera automatiquement abandonnée!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§aEnregistrement de l'intrigue..." creating-plot: "§aCréation d'un nouveau tracé..." created-new-plot: "§aCréé un nouveau tracé§a pour §6{0}§a!" @@ -243,6 +259,8 @@ message: cannot-undo-review: "Vous ne pouvez pas annuler une révision que vous n'avez pas révisée vous-même!" cannot-send-feedback: "Vous ne pouvez pas envoyer de commentaires à un tracé que vous n'avez pas révisé vous-même!" cannot-review-own-plot: "Vous ne pouvez pas réviser votre propre intrigue!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "Vous n'avez pas la permission de faire ça!" player-has-no-invitations: "Vous n'avez aucune invitation!" player-is-not-allowed: "Vous n'êtes pas autorisé à faire ça!" @@ -265,6 +283,7 @@ message: chat-input-expired: "La saisie du chat a expiré." tutorial-disabled: 'Les tutoriels sont désactivés sur ce serveur.' tutorial-already-running: "Vous avez déjà un tutoriel en cours ! Terminez-le avant d'en commencer un nouveau." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Quotidien" @@ -407,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + #NOTE: Do not change config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index c4dde658..2090f462 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: "닫기" back: "뒤로가기" + continue: 'Continue' next-page: "다음 페이지" previous-page: "이전 페이지" error: "에러" @@ -157,6 +158,11 @@ review: feedback: "피드백" reviewer: "검토자" player-language: "Player Language" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "정확도" accuracy-desc: "얼마나 정확하게 건축되었나요?%newline%%newline%- 현실과의 유사성%newline%- 올바른 외곽선%newline%- 올바른 높이%newline%- 완성도" @@ -171,6 +177,11 @@ note: wont-be-able-continue-building: "더 이상 이 플롯에서 건축하실 수 없게 됩니다!" score-will-be-split: "리뷰된 후에는 플롯의 모든 멤버에게 점수가 배분될 것입니다." player-has-to-be-online: "해당 플레이어가 접속 중이어야 합니다!" + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'Read' read-more: 'Read More' @@ -194,6 +205,7 @@ note: click-to-play-with-friends: "§7친구와 플레이하시려면 §6여기§7를 클릭하세요!" tutorial-show-stages: 'Show Stages' click-to-open-plots-menu: "클릭하여 플롯 메뉴 열기..." + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -218,6 +230,10 @@ message: removed-plot-member: "§6{0}§a님을 플롯 §6#{1}§a에서 제외하였습니다!" left-plot: "§a플롯 §6#{0}§a을 나갔습니다!" plot-will-get-abandoned-warning: "§c§l경고: §c이 플롯은 자동으로 버려질 것입니다!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§a플롯 저장 중..." creating-plot: "§a새로운 플롯 생성 중..." created-new-plot: "§6{0}§a님의 플롯을 생성하였습니다!" @@ -243,6 +259,8 @@ message: cannot-undo-review: "오직 자신의 리뷰만 취소할 수 있습니다!" cannot-send-feedback: "오직 자신이 리뷰한 플롯에만 피드백을 보낼 수 있습니다!" cannot-review-own-plot: "자신의 플롯은 검토할 수 없습니다!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "이 기능을 사용할 수 있는 권한이 없습니다!" player-has-no-invitations: "초대장이 없습니다!" player-is-not-allowed: "권한이 없습니다!" @@ -265,6 +283,7 @@ message: chat-input-expired: "The chat input has expired." tutorial-disabled: 'Tutorials are disabled on this server.' tutorial-already-running: "You already have a tutorial running! Complete it before starting a new one." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Daily" @@ -407,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + # NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index f830043e..ae6d8ef1 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: "Fechar" back: "Voltar" + continue: 'Continue' next-page: "Próxima Página" previous-page: "Página Anterior" error: "Erro" @@ -157,6 +158,11 @@ review: feedback: "Feedback" reviewer: "Avaliador" player-language: "Player Language" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "Precisão" accuracy-desc: "Quão precisa é a construção?%newline%%newline%- Pare como na vida real%newline%- MArcação correta%newline%- Altura correta%newline%- Completa" @@ -171,6 +177,11 @@ note: wont-be-able-continue-building: "Você não poderá continuar construindo neste terreno!" score-will-be-split: "A pontuação será dividida entre todos os membros quando revisada!" player-has-to-be-online: "O jogador tem que estar online!" + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'Read' read-more: 'Read More' @@ -194,6 +205,7 @@ note: click-to-play-with-friends: "§7Quer jogar com seus amigos? §6Clique aqui..." tutorial-show-stages: 'Show Stages' click-to-open-plots-menu: 'Clique para abrir o menu de parcelas...' + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -218,6 +230,10 @@ message: removed-plot-member: "§aRemovido §6{0}§a do terreno §6#{1}§a!" left-plot: "§aDeixou o terreno §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lAVISO: §cEsse terreno vai ser abandonado automaticamente!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§aSalvando terreno..." creating-plot: "§aCriando um novo terreno..." created-new-plot: "§aCriou novo terreno para §6{0}§a!" @@ -243,6 +259,8 @@ message: cannot-undo-review: "Você não pode desfazer uma avaliação que você mesmo não avaliou!" cannot-send-feedback: "Você não pode enviar feedback para um lote que você mesmo não avaliou!" cannot-review-own-plot: "Você não pode revisar seu próprio terreno!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "Você não tem permissão para fazer isso!" player-has-no-invitations: "Você não tem convites!" player-is-not-allowed: "Você não tem permissão para fazer isso!" @@ -265,6 +283,7 @@ message: chat-input-expired: "The chat input has expired." tutorial-disabled: 'Tutorials are disabled on this server.' tutorial-already-running: "You already have a tutorial running! Complete it before starting a new one." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Daily" @@ -407,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + # NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index c84b0727..fde46d7a 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: "Закрыть" back: "Назад" + continue: 'Continue' next-page: "Следующая Страница" previous-page: "Предыдущая Страница" error: "Ошибка" @@ -157,6 +158,11 @@ review: feedback: "Отзыв" reviewer: "Оценщик" player-language: "Player Language" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "Точность Воссоздания" accuracy-desc: "Насколько точно исполнено здание?%newline%%newline%- Выглядит как в настоящей жизни%newline%- Правильные контуры%newline%- Правильная высота%newline%- Полностью завершен" @@ -171,6 +177,11 @@ note: wont-be-able-continue-building: "Вы не сможете больше строить на этом участке!" score-will-be-split: "Общая Оценка будет разделена между всеми участниками после проверки!" player-has-to-be-online: "Игрок должен быть в сети!" + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'Read' read-more: 'Read More' @@ -194,6 +205,7 @@ note: click-to-play-with-friends: "§7Хотите играть с друзьями? §6Нажмите здесь..." tutorial-show-stages: 'Show Stages' click-to-open-plots-menu: "Нажмите, чтобы открыть меню участков..." + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -218,6 +230,10 @@ message: removed-plot-member: "§6{0}§a §aудалён из участка§6#{1}§a!" left-plot: "§aПокинул участок §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lВНИМАНИЕ: §cЭтот участок будет автоматически сброшен!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§aСохранение участка..." creating-plot: "§aСоздание нового участка..." created-new-plot: "§aСоздан новый участок§a для §6{0}§a!" @@ -243,6 +259,8 @@ message: cannot-undo-review: "Вы не можете отменить оценку которую выставляли не вы!" cannot-send-feedback: "Вы не можете отправить отзыв к участку который оценивали не вы!" cannot-review-own-plot: "Вы не можете оценить свой участок!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "У вас нет доступа для выполнения этого действия!" player-has-no-invitations: "У вас нет приглашений!" player-is-not-allowed: "Вам запрещено выполнение этого действия!" @@ -265,6 +283,7 @@ message: chat-input-expired: "The chat input has expired." tutorial-disabled: 'Tutorials are disabled on this server.' tutorial-already-running: "You already have a tutorial running! Complete it before starting a new one." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Daily" @@ -407,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + # NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 2a2819ec..b67a6be4 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -11,7 +11,6 @@ lang: name: "简体中文(中国大陆)" head-id: "23238" - # ----------------------------------------------------- # | Plot # ----------------------------------------------------- @@ -69,6 +68,7 @@ difficulty: menu-title: close: "关闭" back: "返回" + continue: 'Continue' next-page: "下一页" previous-page: "上一页" error: "错误" @@ -157,6 +157,11 @@ review: rejected: "驳回" feedback: "回馈" reviewer: "审核员" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" player-language: "Player Language" criteria: accuracy: "准确性" @@ -172,6 +177,11 @@ note: wont-be-able-continue-building: "你将无法继续在此建地上进行建设! " score-will-be-split: "审核时积分将分配给所有成员! " player-has-to-be-online: "玩家必须上线! " + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'Read' read-more: 'Read More' @@ -195,6 +205,7 @@ note: click-to-play-with-friends: "§7想和你的朋友一起玩吗? §6点击此区..." tutorial-show-stages: 'Show Stages' click-to-open-plots-menu: "点击此区 显示你的建地..." + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -219,6 +230,10 @@ message: removed-plot-member: "§a从建地 §6#{1}§a 移除 §6{0}§a! " left-plot: "§a剩余建地 §6#{0}§a! " plot-will-get-abandoned-warning: "§c§l警告: §c此建地将自动废弃! " + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§a储存建地..." creating-plot: "§a创建新建地..." created-new-plot: "§a创建新建地§a 为 §6{0}§a! " @@ -244,6 +259,8 @@ message: cannot-undo-review: "你无法撤回你自己未审核过的审核! " cannot-send-feedback: "你无法发送你自己未审核过的回馈! " cannot-review-own-plot: "你无法审核你所有的建地! " + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "你没有权限做这个! " player-has-no-invitations: "你没有受到邀请! " player-is-not-allowed: "你不被允许做这个! " @@ -266,6 +283,7 @@ message: chat-input-expired: "The chat input has expired." tutorial-disabled: 'Tutorials are disabled on this server.' tutorial-already-running: "You already have a tutorial running! Complete it before starting a new one." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "Daily" @@ -408,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + # NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index 3b41d8c2..10c4bb0d 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -68,6 +68,7 @@ difficulty: menu-title: close: "關閉" back: "返回" + continue: 'Continue' next-page: "下一頁" previous-page: "上一頁" error: "錯誤" @@ -157,6 +158,11 @@ review: feedback: "評語" reviewer: "審核人" player-language: "玩家語言" + no-feedback: "No feedback" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "Toggle points" + total-points: "Total points" criteria: accuracy: "準確性" accuracy-desc: "建築的精確度如何?%newline%%newline%- 看起來像在真實世界%newline%- 正確的輪廓%newline%- 正確的高度%newline%- 完成了" @@ -171,6 +177,11 @@ note: wont-be-able-continue-building: "你將無法繼續在此建地上進行建設!" score-will-be-split: "審核時積分將分配給全部的成員!" player-has-to-be-online: "玩家必須上線!" + optional: "Optional" + required: "Required" + criteria-fulfilled: "Fulfilled" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: '已讀' read-more: '閱讀更多' @@ -194,6 +205,7 @@ note: click-to-play-with-friends: "§7想和你的朋友一起玩嗎?§6點擊此處..." tutorial-show-stages: '顯示階段' click-to-open-plots-menu: '點擊以開啟建地選單...' + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -218,6 +230,10 @@ message: removed-plot-member: "§a將§6{0}§a從建地§6#{1}§a中移除!" left-plot: "§a離開建地§6#{0}§a!" plot-will-get-abandoned-warning: "§c§l警告:§c此建地將自動被廢棄!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "§a儲存建地..." creating-plot: "§a建立新建地..." created-new-plot: "§a為§6{0}§a建立了新建地§a!" @@ -243,6 +259,8 @@ message: cannot-undo-review: "你無法撤回未經你本人審核過的審核!" cannot-send-feedback: "你無法給未經你本人審核過建地的發送評語!" cannot-review-own-plot: "你無法審核你所有的建地!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" player-has-no-permissions: "你沒有權限使用!" player-has-no-invitations: "你沒有受到邀請!" player-is-not-allowed: "你不被允許使用!" @@ -265,6 +283,7 @@ message: chat-input-expired: "聊天輸入過期了。" tutorial-disabled: '此伺服器的教學被停用了。' tutorial-already-running: "你已經有一個教學正在進行!在開始新的教學前請先將它完成。" + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "每日" @@ -407,5 +426,24 @@ database: name: 'Medium' hard: name: 'Hard' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'Unfinished' + unreviewed: + name: 'Unreviewed' + completed: + name: 'Completed' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' + # NOTE: Do not change -config-version: 2.5 +config-version: 2.5 \ No newline at end of file From 22479876e2a3f1f0306bcb535a9b4d4c09bbe8e8 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 21 Jun 2025 16:44:05 +0200 Subject: [PATCH 098/175] implement caching for reviewer methods and minor cleanup --- .../commands/review/CMD_EditFeedback.java | 2 +- .../commands/review/CMD_EditPlot.java | 2 +- .../commands/review/CMD_Review.java | 2 +- .../commands/review/CMD_UndoReview.java | 2 +- .../plotsystem/core/EventListener.java | 4 +- .../database/providers/BuildTeamProvider.java | 12 ++++- .../database/providers/BuilderProvider.java | 50 +++---------------- .../leaderboards/ScoreLeaderboard.java | 12 ++--- .../core/menus/review/ReviewMenu.java | 2 +- 9 files changed, 30 insertions(+), 58 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index 7b442cc3..d750c3c2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -57,7 +57,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } CompletableFuture.runAsync(() -> { - if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILD_TEAM.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 8b3762b5..57f16bdc 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -66,7 +66,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } CompletableFuture.runAsync(() -> { - if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILD_TEAM.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 95af1414..97f257d2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -60,7 +60,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } CompletableFuture.runAsync(() -> { - if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILD_TEAM.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index b111ce4b..1344530f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -59,7 +59,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } CompletableFuture.runAsync(() -> { - if (!DataProvider.BUILDER.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { + if (!DataProvider.BUILD_TEAM.isAnyReviewer(player.getUniqueId()) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 703e1c04..117f8c62 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -310,8 +310,8 @@ private void sendReviewNotices(@NotNull Player player, Builder builder) { PlotUtils.startUnfinishedPlotReminderTimer(player); // Informing reviewer about new reviews - if (player.hasPermission("plotsystem.admin") || DataProvider.BUILDER.isAnyReviewer(builder.getUUID())) { - List reviewerCityProjects = DataProvider.BUILD_TEAM.getReviewerCities(builder); + if (player.hasPermission("plotsystem.admin") || DataProvider.BUILD_TEAM.isAnyReviewer(builder.getUUID())) { + List reviewerCityProjects = DataProvider.BUILD_TEAM.getReviewerCities(builder.getUUID()); List unreviewedPlots = DataProvider.PLOT.getPlots(reviewerCityProjects, Status.unreviewed); if (!unreviewedPlots.isEmpty()) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index f7e3cbfe..fad19583 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; +import org.jetbrains.annotations.NotNull; import java.sql.Connection; import java.sql.PreparedStatement; @@ -178,9 +179,16 @@ public boolean removeReviewer(int id, String reviewerUUID) { return false; } - public List getReviewerCities(Builder builder) { + public boolean isAnyReviewer(@NotNull UUID reviewerUUID) { + return BUILD_TEAMS.stream() + .anyMatch(bt -> bt.getReviewers().stream() + .anyMatch(r -> r.getUUID().equals(reviewerUUID)) + ); + } + + public List getReviewerCities(UUID reviewerUUID) { List buildTeams = BUILD_TEAMS.stream().filter(b - -> b.getReviewers().stream().anyMatch(r -> r.getUUID().equals(builder.getUUID()))).toList(); + -> b.getReviewers().stream().anyMatch(r -> r.getUUID().equals(reviewerUUID))).toList(); List cities = new ArrayList<>(); for (BuildTeam buildTeam : buildTeams) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 9df4af30..b2cb893b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -26,7 +26,6 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; import com.alpsbte.plotsystem.utils.Utils; @@ -42,10 +41,10 @@ import java.util.*; public class BuilderProvider { - public static final Map builders = new HashMap<>(); + protected static final Map BUILDERS = new HashMap<>(); public Builder getBuilderByUUID(UUID uuid) { - if (builders.containsKey(uuid)) return builders.get(uuid); + if (BUILDERS.containsKey(uuid)) return BUILDERS.get(uuid); String query = "SELECT name, score, first_slot, second_slot, third_slot, plot_type FROM builder WHERE uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -82,7 +81,7 @@ public Builder getBuilderByName(String name) { } public boolean addBuilderIfNotExists(UUID uuid, String name) { - if (builders.containsKey(uuid)) return true; + if (BUILDERS.containsKey(uuid)) return true; String selectQuery = "SELECT 1 FROM builder WHERE uuid = ?;"; String insertQuery = "INSERT INTO builder (uuid, name, plot_type) VALUES (?, ?, 1);"; @@ -218,40 +217,7 @@ public Slot getSlot(@NotNull UUID uuid, int plotId) { @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean canReviewPlot(@NotNull UUID uuid, Plot plot) { - // TODO: cache - String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, uuid.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - Optional team = DataProvider.BUILD_TEAM.getBuildTeam(rs.getInt(1)); - if (team.isEmpty()) continue; - if (team.get().getCityProjects().stream().anyMatch(c -> Objects.equals(c.getID(), plot.getCityProject().getID()))) - return true; - } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; - } - - public boolean isAnyReviewer(@NotNull UUID uuid) { - // TODO: cache - String query = "SELECT uuid FROM build_team_has_reviewer WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, uuid.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) return true; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + return DataProvider.BUILD_TEAM.getReviewerCities(uuid).stream().anyMatch(c -> c.getID().equals(plot.getCityProject().getID())); } public List getReviewersByBuildTeam(int buildTeamId) { @@ -278,21 +244,21 @@ public List getReviewersByBuildTeam(int buildTeamId) { * Retrieves the leaderboard entries for all players within a specified timeframe, including their names and scores. * * @param sortBy the timeframe used to filter leaderboard data (e.g., daily, weekly, etc.). - * @return provides a map of player names and their scores, or null if no data is found. + * @return provides a map of player names and their scores, or an empty map if no data is found. */ - public LinkedHashMap getLeaderboardEntries(LeaderboardTimeframe sortBy) { + public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { + LinkedHashMap playerEntries = new LinkedHashMap<>(); try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(sortBy))) { try (ResultSet rs = stmt.executeQuery()) { - LinkedHashMap playerEntries = new LinkedHashMap<>(); while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); return playerEntries; } } catch (SQLException ex) { Utils.logSqlException(ex); } - return null; + return playerEntries; } /** diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index 1aa9af22..a65183e6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -99,13 +99,11 @@ public List> getContent(UUID playerUUID) { lines.add(new HologramRegister.LeaderboardPositionLine(index + 1, null, 0)); } - LinkedHashMap playerRankings = DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard); - if (playerRankings != null) { - int i = 0; - for (Map.Entry entry : playerRankings.entrySet()) { - lines.set(i, new HologramRegister.LeaderboardPositionLine(i + 1, entry.getKey(), entry.getValue())); - i++; - } + Map playerRankings = DataProvider.BUILDER.getLeaderboardEntries(sortByLeaderboard); + int i = 0; + for (Map.Entry entry : playerRankings.entrySet()) { + lines.set(i, new HologramRegister.LeaderboardPositionLine(i + 1, entry.getKey(), entry.getValue())); + i++; } return lines; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index f60f8b85..df1cffed 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -60,7 +60,7 @@ public ReviewMenu(Player player) { @Override protected List getSource() { List plots = new ArrayList<>(); - cityProjects = DataProvider.BUILD_TEAM.getReviewerCities(Builder.byUUID(getMenuPlayer().getUniqueId())); + cityProjects = DataProvider.BUILD_TEAM.getReviewerCities(getMenuPlayer().getUniqueId()); plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unreviewed)); plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unfinished)); return plots; From 0a2682613619df2a51377f286dd257bcc2a77271 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 21 Jun 2025 18:04:06 +0200 Subject: [PATCH 099/175] standardise provider cache naming schemes, use unused return values and more cleanup --- .../alpsbte/plotsystem/commands/CMD_Tpll.java | 2 +- .../admin/setup/CMD_Setup_Server.java | 3 +- .../core/database/DataProvider.java | 4 +- .../providers/CityProjectProvider.java | 14 ++--- .../database/providers/CountryProvider.java | 14 ++--- .../providers/DifficultyProvider.java | 10 ++-- .../database/providers/ReviewProvider.java | 38 ++++++------- .../database/providers/ServerProvider.java | 12 ++-- .../providers/TutorialPlotProvider.java | 2 +- .../core/holograms/HologramRegister.java | 2 + .../leaderboards/ScoreLeaderboard.java | 2 +- .../core/system/plot/utils/PlotUtils.java | 57 +++++++++++-------- .../core/system/review/ReviewRating.java | 5 +- 13 files changed, 90 insertions(+), 75 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index 7efa6832..9183f83c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -122,7 +122,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { int highestY = getHighestY(playerWorld, plotCoordinates); - player.teleport(new Location(playerWorld, plotCoordinates[0], highestY + 1, plotCoordinates[1], player.getLocation().getYaw(), player.getLocation().getPitch())); + player.teleport(new Location(playerWorld, plotCoordinates[0], highestY + 1f, plotCoordinates[1], player.getLocation().getYaw(), player.getLocation().getPitch())); DecimalFormat df = new DecimalFormat("##.#####"); df.setRoundingMode(RoundingMode.FLOOR); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index dcbfa135..410cdb87 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -135,8 +135,9 @@ public void onCommand(CommandSender sender, String[] args) { } int buildTeamId = AlpsUtils.tryParseInt(args[2]); - if (DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId) == null) { + if (DataProvider.BUILD_TEAM.getBuildTeam(buildTeamId).isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team with id " + buildTeamId + " could not be found!")); + return; } boolean successful = DataProvider.SERVER.addServer(serverName, buildTeamId); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index b0323cbc..a1dba9df 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -26,7 +26,7 @@ import com.alpsbte.plotsystem.core.database.providers.*; -public class DataProvider { +public final class DataProvider { public static final BuilderProvider BUILDER = new BuilderProvider(); public static final PlotProvider PLOT = new PlotProvider(); public static final DifficultyProvider DIFFICULTY = new DifficultyProvider(); @@ -36,4 +36,6 @@ public class DataProvider { public static final TutorialPlotProvider TUTORIAL_PLOT = new TutorialPlotProvider(); public static final ReviewProvider REVIEW = new ReviewProvider(); public static final BuildTeamProvider BUILD_TEAM = new BuildTeamProvider(BUILDER, CITY_PROJECT); // has to be initialized after builder and city project providers + + private DataProvider() {} } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 2d7616d8..7c371891 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -37,7 +37,7 @@ import java.util.Optional; public class CityProjectProvider { - public static final List cachedCityProjects = new ArrayList<>(); + protected static final List CITY_PROJECTS = new ArrayList<>(); public CityProjectProvider() { String query = "SELECT city_project_id, country_code, server_name, is_visible, build_team_id FROM city_project;"; @@ -45,7 +45,7 @@ public CityProjectProvider() { PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { - cachedCityProjects.add(new CityProject(rs.getString(1), // cache all city projects + CITY_PROJECTS.add(new CityProject(rs.getString(1), // cache all city projects rs.getString(2), rs.getString(3), rs.getBoolean(4), rs.getInt(5))); } } @@ -55,16 +55,16 @@ public CityProjectProvider() { } public Optional getById(String id) { - return cachedCityProjects.stream().filter(c -> c.getID().equals(id)).findFirst(); + return CITY_PROJECTS.stream().filter(c -> c.getID().equals(id)).findFirst(); } public List getByCountryCode(String countryCode, boolean onlyVisible) { - return cachedCityProjects.stream().filter(c -> (!onlyVisible || c.isVisible()) && + return CITY_PROJECTS.stream().filter(c -> (!onlyVisible || c.isVisible()) && c.getCountry().getCode().equals(countryCode)).toList(); } public List get(boolean onlyVisible) { - return cachedCityProjects.stream().filter(c -> !onlyVisible || c.isVisible()).toList(); + return CITY_PROJECTS.stream().filter(c -> !onlyVisible || c.isVisible()).toList(); } public List getCityProjectsByBuildTeam(int buildTeamId) { @@ -99,7 +99,7 @@ public boolean add(String id, int buildTeamId, String countryCode, String server stmt.setString(3, countryCode); stmt.setString(4, serverName); boolean result = stmt.executeUpdate() > 0; - if (result) cachedCityProjects.add(new CityProject(id, countryCode, serverName, true, buildTeamId)); + if (result) CITY_PROJECTS.add(new CityProject(id, countryCode, serverName, true, buildTeamId)); return result; } catch (SQLException ex) { Utils.logSqlException(ex); @@ -116,7 +116,7 @@ public boolean remove(String id) { PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, id); boolean result = stmt.executeUpdate() > 0; - if (result) cachedCityProjects.remove(cityProject.get()); + if (result) CITY_PROJECTS.remove(cityProject.get()); return result; } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index 165ce50a..57e33b9a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -39,7 +39,7 @@ import java.util.Optional; public class CountryProvider { - private static final List cachedCountries = new ArrayList<>(); + protected static final List COUNTRIES = new ArrayList<>(); public CountryProvider() { String query = "SELECT country_code, continent, material, custom_model_data FROM country;"; @@ -50,7 +50,7 @@ public CountryProvider() { Continent continent = Continent.fromDatabase(rs.getString(2)); Country country = new Country(rs.getString(1), continent, rs.getString(3), rs.getString(4)); - cachedCountries.add(country); // cache all countries + COUNTRIES.add(country); // cache all countries } } } catch (SQLException ex) { @@ -59,15 +59,15 @@ public CountryProvider() { } public List getCountries() { - return cachedCountries; + return COUNTRIES; } public List getCountriesByContinent(Continent continent) { - return cachedCountries.stream().filter(c -> c.getContinent() == continent).toList(); + return COUNTRIES.stream().filter(c -> c.getContinent() == continent).toList(); } public Optional getCountryByCode(String code) { - return cachedCountries.stream().filter(c -> c.getCode().equals(code)).findFirst(); + return COUNTRIES.stream().filter(c -> c.getCode().equals(code)).findFirst(); } public boolean setMaterialAndCustomModelData(String code, String material, @Nullable String customModelData) { @@ -95,7 +95,7 @@ public boolean addCountry(String code, Continent continent, String material, @Nu stmt.setString(3, material); stmt.setString(4, customModelData); boolean result = stmt.executeUpdate() > 0; - if (result) cachedCountries.add(new Country(code, continent, material, customModelData)); + if (result) COUNTRIES.add(new Country(code, continent, material, customModelData)); return result; } catch (SQLException ex) { Utils.logSqlException(ex); @@ -112,7 +112,7 @@ public boolean removeCountry(String code) { PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, code); boolean result = stmt.executeUpdate() > 0; - if (result) cachedCountries.remove(cachedCountry.get()); + if (result) COUNTRIES.remove(cachedCountry.get()); return result; } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index c7f4a3df..c48abf4f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -42,7 +42,7 @@ import static net.kyori.adventure.text.Component.text; public class DifficultyProvider { - private static final List cachedDifficulties = new ArrayList<>(); + protected static final List DIFFICULTIES = new ArrayList<>(); public DifficultyProvider() { // cache all difficulties @@ -57,7 +57,7 @@ public DifficultyProvider() { PlotDifficulty plotDifficulty = PlotDifficulty.valueOf(id); Difficulty difficulty = new Difficulty(plotDifficulty, id, multiplier, scoreRequirement); - cachedDifficulties.add(difficulty); + DIFFICULTIES.add(difficulty); } } } catch (SQLException ex) { @@ -66,16 +66,16 @@ public DifficultyProvider() { } public List getDifficulties() { - return cachedDifficulties; + return DIFFICULTIES; } public Optional getDifficultyById(String id) { - return cachedDifficulties.stream().filter(d -> d.getID().equalsIgnoreCase(id)).findAny(); + return DIFFICULTIES.stream().filter(d -> d.getID().equalsIgnoreCase(id)).findAny(); } public Optional getDifficultyByEnum(PlotDifficulty difficulty) { if (difficulty == null) return Optional.empty(); - return cachedDifficulties.stream().filter(d -> d.getID().equalsIgnoreCase(difficulty.name())).findFirst(); + return DIFFICULTIES.stream().filter(d -> d.getID().equalsIgnoreCase(difficulty.name())).findFirst(); } public boolean setMultiplier(String id, double multiplier) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index da24ac34..bc542d31 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -38,9 +38,9 @@ import java.util.*; public class ReviewProvider { - private static final List cachedNotifications = new ArrayList<>(); - private static final List cachedToggleCriteria = new ArrayList<>(); - private static final List cachedBuildTeamToggleCriteria = new ArrayList<>(); + protected static final List NOTIFICATIONS = new ArrayList<>(); + protected static final List TOGGLE_CRITERIA = new ArrayList<>(); + protected static final List BUILD_TEAM_TOGGLE_CRITERIA = new ArrayList<>(); public ReviewProvider() { // cache all review notifications @@ -49,7 +49,7 @@ public ReviewProvider() { PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { - cachedNotifications.add(new ReviewNotification(rs.getInt(1), UUID.fromString(rs.getString(2)))); + NOTIFICATIONS.add(new ReviewNotification(rs.getInt(1), UUID.fromString(rs.getString(2)))); } } } catch (SQLException ex) { @@ -62,7 +62,7 @@ public ReviewProvider() { PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { - cachedToggleCriteria.add(new ToggleCriteria(rs.getString(1), rs.getBoolean(2))); + TOGGLE_CRITERIA.add(new ToggleCriteria(rs.getString(1), rs.getBoolean(2))); } } } catch (SQLException ex) { @@ -76,8 +76,8 @@ public ReviewProvider() { try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { String criteriaName = rs.getString(1); - ToggleCriteria toggle = cachedToggleCriteria.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst().orElseThrow(); - cachedBuildTeamToggleCriteria.add(new BuildTeamToggleCriteria(rs.getInt(2), toggle)); + ToggleCriteria toggle = TOGGLE_CRITERIA.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst().orElseThrow(); + BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(rs.getInt(2), toggle)); } } } catch (SQLException ex) { @@ -159,7 +159,7 @@ public List getPlotReviewHistory(int plotId) { private ReviewRating getReviewRating(int reviewId, String ratingString) { int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); - HashMap toggleCriteria = getReviewToggleCriteria(reviewId); + Map toggleCriteria = getReviewToggleCriteria(reviewId); return new ReviewRating(accuracyPoints, blockPalettePoints, toggleCriteria); } @@ -197,9 +197,9 @@ public PlotReview createReview(Plot plot, ReviewRating rating, int score, UUID r if (!result) return null; PlotReview review = plot.getLatestReview().orElseThrow(); - HashMap allToggles = rating.getAllToggles(); - for (ToggleCriteria criteria : allToggles.keySet()) { - if (!addReviewToggleCriteria(review.getReviewId(), criteria, allToggles.get(criteria))) + Map allToggles = rating.getAllToggles(); + for (Map.Entry criteriaEntry : allToggles.entrySet()) { + if (!addReviewToggleCriteria(review.getReviewId(), criteriaEntry.getKey(), criteriaEntry.getValue())) return null; } @@ -257,14 +257,14 @@ public boolean removeAllReviewsOfPlot(int plotId) { // --- Toggle Criteria --- public Optional getToggleCriteria(String criteriaName) { - return cachedToggleCriteria.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst(); + return TOGGLE_CRITERIA.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst(); } public List getBuildTeamToggleCriteria(int buildTeamId) { - return cachedBuildTeamToggleCriteria.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); + return BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); } - public HashMap getReviewToggleCriteria(int reviewId) { + public Map getReviewToggleCriteria(int reviewId) { HashMap toggleCriteriaList = new HashMap<>(); String query = "SELECT criteria_name, is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -312,15 +312,15 @@ public boolean removeCheckedToggleCriteria(int reviewId) { // --- Review Notification --- public Optional getReviewNotification(int reviewId, UUID uuid) { - return cachedNotifications.stream().filter(n -> n.getReviewId() == reviewId && n.getUuid() == uuid).findFirst(); + return NOTIFICATIONS.stream().filter(n -> n.getReviewId() == reviewId && n.getUuid() == uuid).findFirst(); } public List getReviewNotifications(int reviewId) { - return cachedNotifications.stream().filter(n -> n.getReviewId() == reviewId).toList(); + return NOTIFICATIONS.stream().filter(n -> n.getReviewId() == reviewId).toList(); } public List getReviewNotifications(UUID uuid) { - return cachedNotifications.stream().filter(n -> n.getUuid() == uuid).toList(); + return NOTIFICATIONS.stream().filter(n -> n.getUuid() == uuid).toList(); } public boolean removeReviewNotification(int reviewId, UUID uuid) { @@ -333,7 +333,7 @@ public boolean removeReviewNotification(int reviewId, UUID uuid) { stmt.setInt(1, reviewId); stmt.setString(2, uuid.toString()); boolean result = stmt.executeUpdate() > 0; - if (result) cachedNotifications.remove(notification.get()); + if (result) NOTIFICATIONS.remove(notification.get()); return result; } catch (SQLException ex) { Utils.logSqlException(ex); @@ -354,7 +354,7 @@ public void createReviewNotification(int reviewId, UUID uuid) { stmt.setInt(1, reviewId); stmt.setString(2, uuid.toString()); boolean result = stmt.executeUpdate() > 0; - if (result) cachedNotifications.add(new ReviewNotification(reviewId, uuid)); + if (result) NOTIFICATIONS.add(new ReviewNotification(reviewId, uuid)); } catch (SQLException ex) { Utils.logSqlException(ex); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java index bdc3b7d4..212f4f66 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java @@ -35,14 +35,14 @@ import java.util.List; public class ServerProvider { - private static final List cachedServers = new ArrayList<>(); + protected static final List SERVERS = new ArrayList<>(); public ServerProvider() { String query = "SELECT server_name FROM server;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) cachedServers.add(rs.getString(1)); // cache all servers + while (rs.next()) SERVERS.add(rs.getString(1)); // cache all servers } } catch (SQLException ex) { Utils.logSqlException(ex); @@ -50,11 +50,11 @@ public ServerProvider() { } public boolean serverExists(String serverName) { - return cachedServers.stream().anyMatch(s -> s.equals(serverName)); + return SERVERS.stream().anyMatch(s -> s.equals(serverName)); } public List getServers() { - return cachedServers; + return SERVERS; } public boolean addServer(String name, int buildTeamId) { @@ -66,7 +66,7 @@ public boolean addServer(String name, int buildTeamId) { stmt.setString(1, name); stmt.setInt(2, buildTeamId); boolean result = stmt.executeUpdate() > 0; - if (result) cachedServers.add(name); + if (result) SERVERS.add(name); return result; } catch (SQLException ex) { Utils.logSqlException(ex); @@ -82,7 +82,7 @@ public boolean removeServer(String name) { PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setString(1, name); boolean result = stmt.executeUpdate() > 0; - if (result) cachedServers.remove(name); + if (result) SERVERS.remove(name); return result; } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index 4f7bfc5f..dc75471e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -35,7 +35,7 @@ import java.util.*; public class TutorialPlotProvider { - public static final HashMap tutorialPlots = new HashMap<>(); + public static final Map tutorialPlots = new HashMap<>(); public static final LinkedList freeTutorialPlotIds = new LinkedList<>(); public Optional getById(int id) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java index 4033cdd3..72652253 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramRegister.java @@ -13,6 +13,8 @@ import java.util.Objects; public final class HologramRegister { + private HologramRegister() {} + /** * Registers the {@link ScoreLeaderboard} and adds * them to {@link DecentHologramDisplay#activeDisplays}. diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index a65183e6..f536658f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -56,7 +56,7 @@ public List getPages() { if (ConfigUtil.getInstance() == null) return new ArrayList<>(); FileConfiguration config = PlotSystem.getPlugin().getConfig(); return Arrays.stream(LeaderboardTimeframe.values()) - .filter(p -> config.getBoolean(p.configPath)).map(LeaderboardTimeframe::toString).collect(Collectors.toList()); + .filter(p -> config.getBoolean(p.configPath)).map(LeaderboardTimeframe::toString).toList(); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 68b80689..d4a7fb8e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -87,7 +87,6 @@ import java.time.LocalDate; import java.util.*; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; @@ -233,7 +232,7 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { double initialY = clipboard.getRegion().getMinimumY(); double offset = initialY - cuboidRegion.getMinimumY(); - writer.write(cb.transform(new AffineTransform().translate(Vector3.at(0,offset,0)))); + writer.write(cb.transform(new AffineTransform().translate(Vector3.at(0, offset, 0)))); } } @@ -393,42 +392,50 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { return false; } - try { - CompletableFuture.runAsync(() -> { - if (plot.getPlotType() == PlotType.TUTORIAL) return; - Plot dPlot = (Plot) plot; - DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getID()); - for (Builder builder : dPlot.getPlotMembers()) dPlot.removePlotMember(builder); - - if (plot.getPlotOwner() != null) { - Cache.clearCache(plot.getPlotOwner().getUUID()); - if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1)) return; - } + CompletableFuture.runAsync(() -> { + if (plot.getPlotType() == PlotType.TUTORIAL) return; + Plot dPlot = (Plot) plot; + boolean successful; + successful = DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getID()); - dPlot.setPlotOwner(null); - dPlot.setLastActivity(true); - dPlot.setStatus(Status.unclaimed); - dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); - }).join(); - } catch (CompletionException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!"), ex); - return false; - } + for (Builder builder : dPlot.getPlotMembers()) { + if (!successful) break; + successful = dPlot.removePlotMember(builder); + } + + if (successful && plot.getPlotOwner() != null) { + Cache.clearCache(plot.getPlotOwner().getUUID()); + successful = plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlot(dPlot), -1); + } + + if (successful) { + successful = dPlot.setPlotOwner(null) + && dPlot.setLastActivity(true) + && dPlot.setStatus(Status.unclaimed) + && dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); + } + + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!")); + }); return true; } public static boolean deletePlot(Plot plot) { if (abandonPlot(plot)) { - CompletableFuture.runAsync(() -> DataProvider.PLOT.deletePlot(plot.getID())); + CompletableFuture.runAsync(() -> { + if (DataProvider.PLOT.deletePlot(plot.getID())) return; + PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to abandon plot with the ID " + plot.getID() + "!")); + }); return true; } - PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to delete plot with the ID " + plot.getID() + "!")); + PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to abandon plot with the ID " + plot.getID() + "!")); return false; } } public static final class Cache { private Cache() {} + private static final HashMap> cachedInProgressPlots = new HashMap<>(); public static void clearCache() { @@ -454,6 +461,7 @@ public static Map> getCachedInProgressPlots() { public static final class Effects { private Effects() {} + public static final int CACHE_UPDATE_TICKS = 20 * 60; private static int time; @@ -526,6 +534,7 @@ public static void showOutlines() { public static final class ChatFormatting { private ChatFormatting() {} + public static void sendLinkMessages(AbstractPlot plot, Player player) { Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { Component[] tc = new Component[3]; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java index 1807984a..e21aee21 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewRating.java @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; +import java.util.Map; public class ReviewRating { private int accuracyPoints; @@ -17,7 +18,7 @@ public ReviewRating(int accuracyPoints, int blockPalettePoints, List toggles) { + public ReviewRating(int accuracyPoints, int blockPalettePoints, Map toggles) { this.accuracyPoints = accuracyPoints; this.blockPalettePoints = blockPalettePoints; @@ -51,7 +52,7 @@ public List getUncheckedToggles() { return uncheckedToggles; } - public HashMap getAllToggles() { + public Map getAllToggles() { HashMap allToggles = new HashMap<>(); for (ToggleCriteria checked : checkedToggles) allToggles.put(checked, true); for (ToggleCriteria unchecked : uncheckedToggles) allToggles.put(unchecked, false); From 6cf4c771a959a62691d127459977e12e3ebe4197 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 21 Jun 2025 21:00:45 +0200 Subject: [PATCH 100/175] fix getOutlineSchematicBytes method and remove unused variable --- .../leaderboards/ScoreLeaderboard.java | 3 --- .../core/system/plot/utils/PlotUtils.java | 20 +++++++++++++++++-- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index f536658f..c1ca5ef4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -36,13 +36,10 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.text.DecimalFormat; import java.util.*; import java.util.logging.Level; -import java.util.stream.Collectors; public class ScoreLeaderboard extends DecentHologramPagedDisplay implements HologramConfiguration { - private final DecimalFormat df = new DecimalFormat("#.##"); private LeaderboardTimeframe sortByLeaderboard; public ScoreLeaderboard() { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index d4a7fb8e..caf9d63d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -182,11 +182,27 @@ public static boolean isPlotWorld(World world) { clipboard = reader.read(); } - Polygonal2DRegion region = new Polygonal2DRegion(BukkitAdapter.adapt(world), plot.getOutline(), clipboard.getMinimumPoint().y(), clipboard.getMaximumPoint().y()); + Polygonal2DRegion region = new Polygonal2DRegion( + BukkitAdapter.adapt(world), + plot.getOutline(), + clipboard.getMinimumPoint().y(), + clipboard.getMaximumPoint().y() + ); + + BlockArrayClipboard newClipboard = new BlockArrayClipboard(region); + newClipboard.setOrigin(BlockVector3.at(region.getCenter().x(), region.getMinimumPoint().y(), region.getCenter().z())); + ForwardExtentCopy copy = new ForwardExtentCopy( + clipboard, + region, + newClipboard, + region.getMinimumPoint() + ); + + Operations.complete(copy); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (ClipboardWriter writer = AbstractPlot.CLIPBOARD_FORMAT.getWriter(outputStream)) { - writer.write(new BlockArrayClipboard(region)); + writer.write(newClipboard); } return outputStream.toByteArray(); } From 13e99cb6be91597c7970b10c7c0b7a1a145f5b91 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 21 Jun 2025 22:59:52 +0200 Subject: [PATCH 101/175] move teleport call to the main thread --- .../com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index d14cc257..5f7b2f38 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -91,7 +91,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - plot.getWorld().teleportPlayer(player); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> plot.getWorld().teleportPlayer(player)); }); } From a1a444f44b9f5f1e45da0010c067b5e53bc9b85b Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 21 Jun 2025 23:17:31 +0200 Subject: [PATCH 102/175] update pom.xml --- pom.xml | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/pom.xml b/pom.xml index c3e37c7f..5f8eab91 100644 --- a/pom.xml +++ b/pom.xml @@ -64,7 +64,7 @@ OnARandomBox https://repo.onarandombox.com/content/groups/public/ - + codemc-repo https://repo.codemc.io/repository/maven-public/ @@ -129,7 +129,7 @@ com.github.decentsoftware-eu decentholograms - 2.8.12 + 2.9.2 provided @@ -164,20 +164,6 @@ 4.0.3 compile - - - commons-net - commons-net - 3.11.0 - compile - - - - com.jcraft - jsch - 0.1.55 - compile - com.comphenix.protocol From 8e0dba936a7dc5d3067fd768a77d64993d93e63d Mon Sep 17 00:00:00 2001 From: R3tuxn Date: Sat, 21 Jun 2025 23:28:57 +0200 Subject: [PATCH 103/175] update README.md --- README.md | 78 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 49 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index f99c8c59..5cdf251d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,8 @@

- Logo + Plot System Logo

@@ -25,12 +26,9 @@ build status code quality releases - total lines repo size

- - # About The Project The Plot System is an essential part of any BuildTheEarth server system, meant to run alongside the classic Terra servers to make participating a lot easier @@ -50,15 +48,23 @@ The plugin is mostly developed by the Alps-BTE team and is intended for everyone If you have any questions regarding the setup or contribution, please do not hesitate to contact us. All used Libraries and APIs are listed below. + # Features ## Plot Types -![FocusMode_PlotSystemBanner](https://user-images.githubusercontent.com/64250550/184678178-f8b5c3e5-ec35-4b6b-9b1b-ac3170148d34.png)The focus mode is the old well-known mode that was also used by default before the release of v3.0. Build your plot on a floating island in an empty void world. Simple and straightforward, like in the good old days. +![FocusMode_PlotSystemBanner](https://user-images.githubusercontent.com/64250550/184678178-f8b5c3e5-ec35-4b6b-9b1b-ac3170148d34.png) +The focus mode is the old well-known mode that was also used by default before the release of v3.0. Build your plot on a +floating island in an empty void world. Simple and straightforward, like in the good old days.

➖ No Environment
➖ No Neighbouring Plots -


![InspirationMode_PlotSystemBanner](https://user-images.githubusercontent.com/64250550/184681201-2f7e2103-df8d-42a3-93b0-ce42770e4fa8.png)The inspiration mode feels like building in a normal world. By adding the surrounding area of your plot, you will see neighbouring buildings, streets and vegetation. In comparison to the focus mode, you will have a better orientation which helps you when building. This mode is selected as default, when using the Plot System for the first time. +

![InspirationMode_PlotSystemBanner](https://user-images.githubusercontent.com/64250550/184681201-2f7e2103-df8d-42a3-93b0-ce42770e4fa8.png) +The inspiration mode feels like building in a normal world. By adding the surrounding area of your plot, you will see +neighbouring buildings, streets and vegetation. In comparison to the focus mode, you will have a better orientation +which helps you when building. This mode is selected as default, when using the Plot System for the first time.

➕ Environment
➖ No Neighbouring Plots -


![CityInspirationMode_PlotSystemBanner](https://user-images.githubusercontent.com/64250550/184683030-27f1760b-09ad-43f7-b5ed-bdd46c972246.png)The city inspiration mode will give you the full building experience by combining the inspiration mode with other players. Build with your friends and others in one world next to each other and see continuous progress. +

![CityInspirationMode_PlotSystemBanner](https://user-images.githubusercontent.com/64250550/184683030-27f1760b-09ad-43f7-b5ed-bdd46c972246.png) +The city inspiration mode will give you the full building experience by combining the inspiration mode with other +players. Build with your friends and others in one world next to each other and see continuous progress.

⚠️ This mode is not fully stable and still in BETA

➕ Environment
➕ Neighbouring Plots @@ -70,17 +76,34 @@ Tutorial, which needs to be completed to use the Plot-System and other features, building process to understand how it works.

- ## Other Features -✔️ Support for **multiple cities** as well as for **continents** and **countries/states**
✔️ **User-friendly menus** and **commands**
✔️ Inbuilt **Get Started Tutorial** for beginners
✔️ **User-friendly menus** and **commands**
✔️ **Multi-Language** Support (currently up to 7 languages)
✔️ Plot **Group System** (Build together with up to 5 people on one plot)
✔️ **SFTP/FTP** Support
✔️ Detailed **review system** with individual feedback
✔️ Three plot **difficulty levels** (easy, medium and hard)
✔️ Building **Quality of Life tools**
✔️ Full **/tpll support** on plots
✔️ **Leaderboards** when using the Holograms extension
✔️ Automatic **abandoning of inactive plots**
✔️ Automatic **placement of completed plots** on the terra server
✔️ **Easy configuration** and **setup**
-# Installation -💻 To use this system, you currently need at least two servers.
One is running Terra+- with the **[Plot-System-Terra Plugin](https://github.com/AlpsBTE/Plot-System-Terra)** and the -other one is a Spigot Vanilla server for the Plot-System itself.
**For more information check out the [Wiki](https://github.com/AlpsBTE/Plot-System/wiki/Installation)**! +✔️ Support for **multiple cities** as well as for **continents** and **countries/states**
+✔️ **User-friendly menus** and **commands**
+✔️ Inbuilt **Get Started Tutorial** for beginners
+✔️ **User-friendly menus** and **commands**
+✔️ **Multi-Language** Support
+✔️ Plot **Group System** (Build together with up to 5 people on one plot)
+✔️ Detailed **review system** with individual feedback
+✔️ Three plot **difficulty levels** (easy, medium and hard)
+✔️ Building **Quality of Life tools**
+✔️ Full **/tpll support** on plots
+✔️ **Leaderboards** when using the Holograms extension
+✔️ Automatic **abandoning of inactive plots**
+✔️ Automatic **placement of completed plots** on the terra server
+✔️ **Easy configuration** and **setup**
+# Installation +💻 To use this system, you currently need at least two servers.
+One server runs [Terra++](https://github.com/BTE-Germany/TerraPlusMinus) together with the +**[Plot-System-Terra](https://github.com/AlpsBTE/Plot-System-Terra)** plugin, while the other is a Paper server +dedicated to the Plot-System itself.
+**For more information check out the [Wiki](https://github.com/AlpsBTE/Plot-System/wiki/Installation)**! - # Roadmap -📋 Web Interface
📋 Discord Integration
📋 Statistics
+📋 Web Interface
+📋 Discord Integration
+📋 Statistics
+ # Contributing 🔨 Any contributions you make are greatly appreciated. @@ -89,24 +112,21 @@ other one is a Spigot Vanilla server for the Plot-System itself.
**For more * Submitting a fix * Proposing new features - - # License - Distributed under the MIT License. See `LICENSE` for more information. - - # Libraries & APIs -* [Paper API](https://github.com/PaperMC/Paper) -* [FAWE API](https://github.com/IntellectualSites/FastAsyncWorldEdit) -* [WorldGuard API](https://github.com/EngineHub/WorldGuard) -* [Multiverse-Core API](https://github.com/Multiverse/Multiverse-Core) -* [Canvas Menu-Builder Library](https://github.com/IPVP-MC/canvas) -* [Head-DB API](https://github.com/Arcaniax-Development/HeadDatabase-API) -* [Holographic Displays API](https://github.com/filoghost/HolographicDisplays) -* [Maria-DB Library](https://mariadb.com/kb/en/about-mariadb-connector-j/) -* [Hikari-CP](https://github.com/brettwooldridge/HikariCP) -* [Apache Common VFS API](https://commons.apache.org/proper/commons-vfs/commons-vfs2/apidocs/index.html) +* [Paper](https://github.com/PaperMC/Paper) +* [FAWE](https://github.com/IntellectualSites/FastAsyncWorldEdit) +* [WorldGuard](https://github.com/EngineHub/WorldGuard) +* [Multiverse Core](https://github.com/Multiverse/Multiverse-Core) +* [Particle Native](https://github.com/Fierioziy/ParticleNativeAPI) +* [Canvas](https://github.com/IPVP-MC/canvas) +* [HeadDatabase](https://github.com/Arcaniax-Development/HeadDatabase-API) +* [DecentHolograms](https://github.com/DecentSoftware-eu/DecentHolograms) +* [MariaDB](https://mariadb.com/kb/en/about-mariadb-connector-j/) +* [HikariCP](https://github.com/brettwooldridge/HikariCP) * [ProtocolLIB](https://github.com/dmulloy2/ProtocolLib) * [Fancy NPCs](https://github.com/FancyMcPlugins/FancyNpcs) +* [AlpsLib](https://github.com/AlpsBTE/Alps-Lib) +* [LangLibs](https://github.com/Cinnazeyy/LangLibs) \ No newline at end of file From e5e9591cf95646aa5b658174bac41db888aca428 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 22 Jun 2025 01:31:25 +0200 Subject: [PATCH 104/175] use simpler database name instead of enum value for getting continent when creating country --- .../plotsystem/commands/admin/setup/CMD_Setup_Country.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 237b3360..3d131f80 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -141,7 +141,7 @@ public void onCommand(CommandSender sender, String[] args) { Continent continent; try { - continent = Continent.valueOf(args[2].toUpperCase()); + continent = Continent.fromDatabase(args[2].toUpperCase()); } catch (IllegalArgumentException e) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Unknown continent! " + Arrays.toString(Continent.values()))); return; From 086256a06e4969c85329de8298df112e1ab43886 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sun, 22 Jun 2025 16:41:07 +0200 Subject: [PATCH 105/175] =?UTF-8?q?=F0=9F=90=9B=20Improve=20region=20permi?= =?UTF-8?q?ssion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Don't set players to owner in protectedRegion (Outline) + remove flags build deny from that region (already set in the global region). Fixes #167. Hot tested but should work. Signed-off-by: Zoriot --- .../com/alpsbte/plotsystem/PlotSystem.java | 6 ++---- .../plot/generator/AbstractPlotGenerator.java | 19 ++++++++----------- .../plot/generator/TutorialPlotGenerator.java | 6 +++--- .../system/plot/utils/PlotPermissions.java | 7 ++----- 4 files changed, 15 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index dfb341a7..41800a3b 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -170,8 +170,6 @@ public void onEnable() { return; } - if (!DependencyManager.isWorldGuardExtraFlagsEnabled()) PlotSystem.getPlugin().getComponentLogger().warn(text("WorldGuardExtraFlags is not enabled!")); - // Check for updates Bukkit.getConsoleSender().sendMessage(empty()); Bukkit.getConsoleSender().sendMessage(text("Update-Checker:", GOLD)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 9900a3e9..f6b98810 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -92,7 +92,7 @@ public abstract class AbstractPlotGenerator { * @param plot - plot which should be generated * @param builder - builder of the plot */ - public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) { + protected AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder) { this(plot, builder, builder.getPlotType()); } @@ -103,7 +103,7 @@ public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builde * @param builder - builder of the plot * @param plotType - type of the plot */ - public AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder, @NotNull PlotType plotType) { + protected AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder builder, @NotNull PlotType plotType) { this(plot, builder, plotType, plot.getVersion() <= 2 || plotType.hasOnePlotPerWorld() ? new OnePlotWorld(plot) : new CityPlotWorld((Plot) plot)); } @@ -185,7 +185,6 @@ protected void createPlotProtection() throws StorageException { DefaultDomain owner = protectedBuildRegion.getOwners(); owner.addPlayer(builder.getUUID()); protectedBuildRegion.setOwners(owner); - protectedRegion.setOwners(owner); // Set protected build region permissions setBuildRegionPermissions(protectedBuildRegion); @@ -207,7 +206,7 @@ protected void createPlotProtection() throws StorageException { * * @param region build region */ - protected void setBuildRegionPermissions(ProtectedRegion region) { + protected void setBuildRegionPermissions(@NotNull ProtectedRegion region) { region.setFlag(Flags.BUILD, StateFlag.State.ALLOW); region.setFlag(Flags.BUILD.getRegionGroupFlag(), RegionGroup.OWNERS); if (PlotSystem.DependencyManager.isWorldGuardExtraFlagsEnabled()) @@ -219,9 +218,7 @@ protected void setBuildRegionPermissions(ProtectedRegion region) { * * @param region plot region */ - protected void setRegionPermissions(ProtectedRegion region) { - region.setFlag(Flags.BUILD, StateFlag.State.DENY); - region.setFlag(Flags.BUILD.getRegionGroupFlag(), RegionGroup.ALL); + protected void setRegionPermissions(@NotNull ProtectedRegion region) { region.setFlag(Flags.ENTRY, StateFlag.State.ALLOW); region.setFlag(Flags.ENTRY.getRegionGroupFlag(), RegionGroup.ALL); @@ -236,7 +233,7 @@ protected void setRegionPermissions(ProtectedRegion region) { * @param config commands.yml config * @return list of blocked commands */ - protected List getBlockedCommands(FileConfiguration config) { + protected List getBlockedCommands(@NotNull FileConfiguration config) { List blockedCommands = config.getStringList(ConfigPaths.BLOCKED_COMMANDS_BUILDERS); blockedCommands.removeIf(c -> c.equals("/cmd1")); return blockedCommands; @@ -290,7 +287,7 @@ public Builder getBuilder() { * @param world - world to paste in * @param clearArea - clears the plot area with air before pasting */ - public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, PlotWorld world, boolean clearArea) throws IOException { + public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, @NotNull PlotWorld world, boolean clearArea) throws IOException { // load world if (!world.loadWorld()) return; World weWorld = new BukkitWorld(world.getBukkitWorld()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java index 24a1c56d..fd309074 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -63,7 +63,7 @@ public void generateOutlines(int schematicId) throws IOException, WorldEditExcep } @Override - protected void setBuildRegionPermissions(ProtectedRegion region) { + protected void setBuildRegionPermissions(@NotNull ProtectedRegion region) { region.setFlag(Flags.BUILD, isBuildingEnabled() ? StateFlag.State.ALLOW : StateFlag.State.DENY); region.setFlag(Flags.BUILD.getRegionGroupFlag(), RegionGroup.OWNERS); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java index 9c85edd1..be605930 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2021-2022, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -37,21 +37,18 @@ public PlotPermissions(PlotWorld world) { } public PlotPermissions addBuilderPerms(UUID builder) { - if (world.getProtectedRegion() != null) world.getProtectedRegion().getOwners().addPlayer(builder); world.getProtectedBuildRegion().getOwners().addPlayer(builder); PlotUtils.Cache.clearCache(builder); return this; } public PlotPermissions removeBuilderPerms(UUID builder) { - if (world.getProtectedRegion() != null) world.getProtectedRegion().getOwners().removePlayer(builder); world.getProtectedBuildRegion().getOwners().removePlayer(builder); PlotUtils.Cache.clearCache(builder); return this; } public void clearAllPerms() { - if (world.getProtectedRegion() != null) world.getProtectedRegion().getOwners().removeAll(); world.getProtectedBuildRegion().getOwners().removeAll(); } From c9ae20dd8505e960fdd73e7981bfadc59615a5ab Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sun, 22 Jun 2025 17:11:06 +0200 Subject: [PATCH 106/175] =?UTF-8?q?=F0=9F=93=9D=20Replace=20HolographicDis?= =?UTF-8?q?play=20with=20DecentHolograms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- src/main/resources/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 6ae401f6..5ab09dd7 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -58,7 +58,7 @@ database: # ----------------------------------------------------- # | Leaderboards: Shows top plot and build scores / Are placed in the spawn world -# | NOTE: Requires the HolographicDisplays plugin to work +# | NOTE: Requires the DecentHolograms plugin to work # ----------------------------------------------------- holograms: # Displays the top 10 builders with the highest score @@ -111,4 +111,4 @@ tutorials: # NOTE: Do not change -config-version: 4.0 \ No newline at end of file +config-version: 4.1 \ No newline at end of file From 78cd1758548d6ff2f4b77d61e6796a39a4556719 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 22 Jun 2025 23:54:00 +0200 Subject: [PATCH 107/175] remove unused config.yml entries --- .../com/alpsbte/plotsystem/utils/io/ConfigPaths.java | 2 -- .../com/alpsbte/plotsystem/utils/io/ConfigUtil.java | 2 +- src/main/resources/config.yml | 10 +--------- 3 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java index 6f942d7c..a37a5dfe 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java @@ -60,8 +60,6 @@ public abstract class ConfigPaths { public static final String DISPLAY_OPTIONS_SHOW_MONTHLY = DISPLAY_OPTIONS + "show-monthly"; public static final String DISPLAY_OPTIONS_SHOW_YEARLY = DISPLAY_OPTIONS + "show-yearly"; public static final String DISPLAY_OPTIONS_SHOW_LIFETIME = DISPLAY_OPTIONS + "show-lifetime"; - public static final String DISPLAY_OPTIONS_ACTION_BAR_ENABLE = DISPLAY_OPTIONS + "action-bar-enable"; - public static final String DISPLAY_OPTIONS_ACTION_BAR_RADIUS = DISPLAY_OPTIONS + "action-bar-radius"; // FORMATTING private static final String CHAT_FORMAT = "chat-format."; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java index 8ac7d3be..69999648 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java @@ -44,7 +44,7 @@ private ConfigUtil() {} public static void init() throws ConfigNotImplementedException { if (configUtilInstance == null) { configUtilInstance = new ConfigurationUtil(new ConfigurationUtil.ConfigFile[]{ - new ConfigurationUtil.ConfigFile(Paths.get("config.yml"), 4.0, true), + new ConfigurationUtil.ConfigFile(Paths.get("config.yml"), 4.2, true), new ConfigurationUtil.ConfigFile(Paths.get("commands.yml"), 1.1, false), new ConfigurationUtil.ConfigFile(Paths.get("items.yml"), 1.3, false) }); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 5ab09dd7..c58e38ac 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -21,12 +21,6 @@ spawn-world: default # Prevents beginners from generating difficult plots enable-score-requirement: true -# Automatic synchronisation of schematic files from SFTP/FTP servers -# [interval] -> default: 3600 seconds (1 hour) -sync-ftp-files: - sff-enable: false - sync-interval: 3600 - # How many days of inactivity it will take before a claimed plot is automatically abandoned, -2 disables it inactivity-interval: 14 @@ -77,8 +71,6 @@ display-options: show-monthly: true show-yearly: false show-lifetime: false - action-bar-enable: true - action-bar-radius: 30 # ----------------------------------------------------- @@ -111,4 +103,4 @@ tutorials: # NOTE: Do not change -config-version: 4.1 \ No newline at end of file +config-version: 4.2 \ No newline at end of file From d8c342ad0849c51bb7a6423f9a218a84bd982e5c Mon Sep 17 00:00:00 2001 From: Zoriot Date: Tue, 24 Jun 2025 18:46:53 +0200 Subject: [PATCH 108/175] =?UTF-8?q?=F0=9F=90=9B=20Only=20send=20group=20sy?= =?UTF-8?q?stem=20msg=20when=20it's=20enabled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Thanks to 𝒇𝓇𝒚 | Thees |, Social Media Team from BTE Germany. --- .../alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index caf9d63d..7bc405fd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -611,7 +611,7 @@ public static void sendLinkMessages(AbstractPlot plot, Player player) { } public static void sendGroupTipMessage(@NotNull Plot plot, Player player) { - if (plot.getPlotMembers().isEmpty()) { + if (plot.getPlotMembers().isEmpty() && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { Component tc = text("» ", DARK_GRAY) .append(text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_PLAY_WITH_FRIENDS), GRAY)) .clickEvent(ClickEvent.runCommand("/plot members " + plot.getID())) From ea269bfb51ad2741608cea25fa5d3ef8ac5e849d Mon Sep 17 00:00:00 2001 From: Zoriot Date: Wed, 25 Jun 2025 14:57:34 +0200 Subject: [PATCH 109/175] =?UTF-8?q?=F0=9F=90=9B=20Make=20Plot-Type=20Nulla?= =?UTF-8?q?ble?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a plot is created, they won't have a plot-type. Use this statement if you upgraded manually before: ALTER TABLE plot MODIFY COLUMN plot_type INT NULL; Signed-off-by: Zoriot --- .../plotsystem/core/database/DatabaseConnection.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index f87c5369..7a0a983a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2021-2022, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -302,7 +302,7 @@ public static List getTables() { " is_pasted BOOLEAN NOT NULL DEFAULT 0," + " mc_version VARCHAR(8) NULL," + " plot_version DOUBLE NOT NULL," + - " plot_type INT NOT NULL," + + " plot_type INT NULL," + " created_by VARCHAR(36) NOT NULL," + " create_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + " PRIMARY KEY (plot_id)," + From 6639b44d6681d0b1dbc04f601321006248f0aeb2 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 00:56:46 +0200 Subject: [PATCH 110/175] =?UTF-8?q?=F0=9F=90=9B=20Make=20List=20mutable=20?= =?UTF-8?q?where=20needed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/database/providers/BuildTeamProvider.java | 2 +- .../java/com/alpsbte/plotsystem/core/system/BuildTeam.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index fad19583..c02d8a4c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -114,7 +114,7 @@ public boolean addBuildTeam(String name) { stmt.setString(1, name); try (ResultSet rs = stmt.executeQuery()) { rs.next(); // get the last inserted build team id - BUILD_TEAMS.add(new BuildTeam(rs.getInt(1), name, List.of(), List.of())); + BUILD_TEAMS.add(new BuildTeam(rs.getInt(1), name)); } } catch (SQLException ex) { Utils.logSqlException(ex); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index 08a5e085..b376dca3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -26,6 +26,7 @@ import com.alpsbte.plotsystem.core.database.DataProvider; +import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -44,6 +45,10 @@ public BuildTeam(int ID, String name, List cities, List re public int getID() { return ID; + public BuildTeam(int id, String name) { + this(id, name, new ArrayList<>(), new ArrayList<>()); + } + } public String getName() { From c7e83f2b484aaa51a164b33a4cdf4aeab988e624 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 00:58:25 +0200 Subject: [PATCH 111/175] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Improve=20structur?= =?UTF-8?q?e=20/=20clearness?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/setup/CMD_Setup_BuildTeam.java | 8 +-- .../database/providers/BuildTeamProvider.java | 6 +-- .../core/menus/BuilderUtilitiesMenu.java | 6 +-- .../plotsystem/core/menus/FeedbackMenu.java | 10 ++-- .../core/menus/PlayerPlotsMenu.java | 53 ++++++++++--------- .../core/menus/PlotActionsMenu.java | 8 +-- .../plotsystem/core/menus/PlotMemberMenu.java | 4 +- .../plotsystem/core/menus/PlotTypeMenu.java | 4 +- .../plotsystem/core/menus/SettingsMenu.java | 7 +-- .../core/menus/SpecialToolsMenu.java | 5 +- .../core/menus/companion/CityProjectMenu.java | 8 +-- .../core/menus/companion/ContinentMenu.java | 2 +- .../core/menus/companion/CountryMenu.java | 12 ++--- .../core/menus/review/ReviewMenu.java | 17 +++--- .../core/menus/review/ReviewPlotMenu.java | 16 +++--- .../menus/review/ReviewPlotTogglesMenu.java | 10 ++-- .../core/menus/tutorial/TutorialsMenu.java | 11 ++-- .../plotsystem/core/system/BuildTeam.java | 21 ++++---- .../com/alpsbte/plotsystem/utils/Utils.java | 5 +- 19 files changed, 110 insertions(+), 103 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 5a7024f1..20813273 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -102,7 +102,7 @@ public void onCommand(CommandSender sender, String[] args) { b.getCityProjects().forEach(c -> citiesAsString.add(c.getID())); b.getReviewers().forEach(r -> reviewersAsString.add(r.getName())); sender.sendMessage(text(" » ", DARK_GRAY) - .append(text(b.getID() + " (" + b.getName() + ") ", AQUA)) + .append(text(b.getId() + " (" + b.getName() + ") ", AQUA)) .append(text("- City Project IDs: " + (citiesAsString.length() == 0 ? "No City Projects" : citiesAsString) + " - Reviewers: " + (reviewersAsString.length() == 0 ? "No Reviewers" : reviewersAsString), WHITE))); } @@ -189,7 +189,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean successful = DataProvider.BUILD_TEAM.removeBuildTeam(buildTeam.get().getID()); + boolean successful = DataProvider.BUILD_TEAM.removeBuildTeam(buildTeam.get().getId()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -284,7 +284,7 @@ public void onCommand(CommandSender sender, String[] args) { } Builder builder = Builder.byName(args[2]); - if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getID() == buildTeam.get().getID())) { + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().anyMatch(b -> b.getId() == buildTeam.get().getId())) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is already reviewer for this build team!")); return; } @@ -332,7 +332,7 @@ public void onCommand(CommandSender sender, String[] args) { } Builder builder = Builder.byName(args[2]); - if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getID() == buildTeam.get().getID())) { + if (builder == null || DataProvider.BUILD_TEAM.getBuildTeamsByReviewer(builder.getUUID()).stream().noneMatch(b -> b.getId() == buildTeam.get().getId())) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Player could not be found or is not a reviewer for this build team!")); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index c02d8a4c..c4b34985 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -66,10 +66,10 @@ public BuildTeamProvider(BuilderProvider builderProvider, CityProjectProvider ci } public Optional getBuildTeam(int id) { - return BUILD_TEAMS.stream().filter(b -> b.getID() == id).findFirst(); + return BUILD_TEAMS.stream().filter(b -> b.getId() == id).findFirst(); } - public List getBuildTeamsByReviewer(UUID reviewerUUID) { + public List getBuildTeamsByReviewer(@NotNull UUID reviewerUUID) { List buildTeams = new ArrayList<>(); String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; @@ -192,7 +192,7 @@ public List getReviewerCities(UUID reviewerUUID) { List cities = new ArrayList<>(); for (BuildTeam buildTeam : buildTeams) { - cities.addAll(cityProjectProvider.getCityProjectsByBuildTeam(buildTeam.getID())); + cities.addAll(cityProjectProvider.getCityProjectsByBuildTeam(buildTeam.getId())); } return cities; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java index 76d8409a..144dba7b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java @@ -26,8 +26,8 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; -import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; @@ -102,8 +102,8 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) - .pattern("111111111") - .pattern("000000000") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 08af473b..1113caaa 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -32,10 +32,10 @@ import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.items.BaseItems; -import com.alpsbte.plotsystem.utils.items.MenuItems; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.BaseItems; +import com.alpsbte.plotsystem.utils.items.MenuItems; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -119,9 +119,9 @@ protected void setItemClickEventsAsync() {} protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) - .pattern("111111111") - .pattern("000000000") - .pattern("111111111") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.FULL_MASK) .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 991ddf31..334b7c01 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -25,24 +25,25 @@ package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; +import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.core.system.review.ReviewRating; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.items.BaseItems; -import com.alpsbte.plotsystem.utils.items.MenuItems; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.items.BaseItems; +import com.alpsbte.plotsystem.utils.items.MenuItems; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; +import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Optional; @@ -58,7 +59,7 @@ public class PlayerPlotsMenu extends AbstractMenu { private int plotDisplayCount = 0; - public PlayerPlotsMenu(Player menuPlayer, Builder builder) { + public PlayerPlotsMenu(Player menuPlayer, @NotNull Builder builder) { super(6, LangUtil.getInstance().get(menuPlayer.getPlayer(), LangPaths.MenuTitle.PLAYER_PLOTS, builder.getName() + "'"), menuPlayer); this.builder = builder; } @@ -128,10 +129,10 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) .pattern("111101111") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } @@ -143,22 +144,22 @@ protected Mask getMask() { * @param p player instance for language system * @return description lore for plot item */ - private LoreBuilder getLore(Plot plot, Player p) { - LoreBuilder builder = new LoreBuilder(); + private @NotNull LoreBuilder getLore(@NotNull Plot plot, Player p) { + LoreBuilder loreBuilder = new LoreBuilder(); Optional review = plot.getLatestReview(); int score = (review.isEmpty() || plot.isRejected()) ? 0 : review.get().getScore(); if (plot.getPlotMembers().isEmpty()) { // Plot is single player plot - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY) + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY) .append(text(score, WHITE))); } else { // Plot is multiplayer plot - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.OWNER) + ": ", GRAY) + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.OWNER) + ": ", GRAY) .append(text(plot.getPlotOwner().getName(), WHITE))); - builder.emptyLine(); + loreBuilder.emptyLine(); - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY) + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.TOTAL_SCORE) + ": ", GRAY) .append(text(score + " ", WHITE)) .append(text(LangUtil.getInstance().get(p, LangPaths.Plot.GroupSystem.SHARED_BY_MEMBERS, Integer.toString(plot.getPlotMembers().size() + 1)), DARK_GRAY))); @@ -166,8 +167,8 @@ private LoreBuilder getLore(Plot plot, Player p) { if (review.isPresent()) { ReviewRating rating = review.get().getRating(); - builder.emptyLine(); - builder.addLines( + loreBuilder.emptyLine(); + loreBuilder.addLines( text(LangUtil.getInstance().get(p, LangPaths.Review.Criteria.ACCURACY) + ": ", GRAY) .append(Utils.ItemUtils.getColoredPointsComponent(rating.getAccuracyPoints(), 5)) .append(text("/", DARK_GRAY)).append(text("5", GREEN)), @@ -176,34 +177,34 @@ private LoreBuilder getLore(Plot plot, Player p) { .append(text("/", DARK_GRAY)).append(text("5", GREEN)) ); if (plot.getVersion() > AbstractPlot.LEGACY_VERSION_THRESHOLD) { - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.TOGGLE_POINTS) + ": ", GRAY) + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.TOGGLE_POINTS) + ": ", GRAY) .append(Utils.ItemUtils.getColoredPointsComponent(rating.getTogglePoints(), 10)) .append(text("/", DARK_GRAY)).append(text("10", GREEN))); } - builder.emptyLine(); - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.FEEDBACK) + ":", GRAY)); + loreBuilder.emptyLine(); + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.FEEDBACK) + ":", GRAY)); String feedback = review.get().getFeedback() == null ? LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.NO_FEEDBACK) : review.get().getFeedback().replaceAll("//", " "); - builder.addLine(text(feedback, WHITE), true); + loreBuilder.addLine(text(feedback, WHITE), true); } - builder.emptyLine(); - if (plot.isRejected()) builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.REJECTED), RED, BOLD)); - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.STATUS) + ": ", GRAY) + loreBuilder.emptyLine(); + if (plot.isRejected()) loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.REJECTED), RED, BOLD)); + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Plot.STATUS) + ": ", GRAY) .append(text(plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), WHITE))); if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { - builder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Note.LEGACY), RED).decoration(BOLD, true)); + loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Note.LEGACY), RED).decoration(BOLD, true)); } - return builder; + return loreBuilder; } /** * @return Menu item */ - public static ItemStack getMenuItem(Player p) { + public static ItemStack getMenuItem(@NotNull Player p) { return new ItemBuilder(AlpsHeadUtils.getPlayerHead(p.getUniqueId())) .setName(text(LangUtil.getInstance().get(p, LangPaths.MenuTitle.SHOW_PLOTS), AQUA, BOLD)) .setLore(new LoreBuilder() diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index a4eaa68d..09a9ba32 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -27,11 +27,11 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; @@ -186,9 +186,9 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) - .pattern("111111111") - .pattern("000000000") - .pattern("111111111") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.FULL_MASK) .build(); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index 76ac91ab..b2ed00f7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -165,8 +165,8 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) - .pattern("111111111") - .pattern("000000000") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index 828c0c39..d7e57697 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -142,8 +142,8 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) - .pattern("111111111") - .pattern("000000000") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java index ad3d4128..67c1ec93 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; @@ -43,7 +44,7 @@ import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class SettingsMenu extends AbstractMenu { - private Consumer onBack = (player) -> player.performCommand("companion"); + private Consumer onBack = player -> player.performCommand("companion"); public SettingsMenu(Player player) { super(3, LangUtil.getInstance().get(player, LangPaths.MenuTitle.SETTINGS), player); @@ -94,8 +95,8 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) - .pattern("111111111") - .pattern("000000000") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java index 7b1f788e..2d904e19 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java @@ -26,6 +26,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LoreBuilder; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; @@ -74,8 +75,8 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) - .pattern("111111111") - .pattern("000000000") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 8937b437..0bccffc8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -170,10 +170,10 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) .pattern("001111001") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("100010001") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java index 79cf57e4..068d4c95 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java @@ -102,7 +102,7 @@ protected Mask getMask() { .pattern("011111111") .pattern("010101010") .pattern("111101111") - .pattern("111111111") + .pattern(Utils.FULL_MASK) .pattern("100010001") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index 67234fed..e6aa5cad 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -32,11 +32,11 @@ import com.alpsbte.plotsystem.core.menus.tutorial.TutorialsMenu; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.Country; -import com.alpsbte.plotsystem.utils.enums.Continent; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; @@ -142,10 +142,10 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) .pattern("001111001") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("100010001") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index df1cffed..63eebd08 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -44,6 +44,7 @@ import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; @@ -168,19 +169,19 @@ protected void setItemClickEventsAsync() { protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) - .pattern("111111111") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") + .pattern(Utils.FULL_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111101111") .build(); } - private List getFilteredPlots(List plots) { - List filteredPlots = plots.stream().map(p -> (Plot) p).collect(Collectors.toList()); + private List getFilteredPlots(@NotNull List plots) { + List filteredPlots = plots.stream().map(p -> (Plot) p).toList(); if (filteredCityProject != null) - filteredPlots = filteredPlots.stream().filter(p -> p.getCityProject().getID().equals(filteredCityProject.getID())).collect(Collectors.toList()); + filteredPlots = filteredPlots.stream().filter(p -> p.getCityProject().getID().equals(filteredCityProject.getID())).toList(); return filteredPlots; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index a3ff2ae2..7120d4e7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -30,14 +30,14 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; +import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.review.ReviewRating; +import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; -import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.items.MenuItems; -import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Status; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; @@ -70,7 +70,7 @@ public ReviewPlotMenu(Player player, Plot plot, ReviewRating rating) { public ReviewPlotMenu(Player player, Plot plot) { this(player, plot, - new ReviewRating(0, 0, List.of(), DataProvider.REVIEW.getBuildTeamToggleCriteria(plot.getCityProject().getBuildTeam().getID()))); + new ReviewRating(0, 0, List.of(), DataProvider.REVIEW.getBuildTeamToggleCriteria(plot.getCityProject().getBuildTeam().getId()))); } @Override @@ -203,10 +203,10 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) .pattern("111101111") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111010111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 3dc3b8b7..38a8ea22 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -82,7 +82,7 @@ protected void setMenuItemsAsync() { getMenu().getSlot(7).setItem(ReviewItems.getReviewInfoItem(getMenuPlayer())); // Set toggle items - buildTeamCriteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(plot.getCityProject().getBuildTeam().getID()); + buildTeamCriteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(plot.getCityProject().getBuildTeam().getId()); for (int i = 0; i < Math.min(buildTeamCriteria.size(), 36); i++) { ToggleCriteria criteria = buildTeamCriteria.get(i); boolean isChecked = rating.getCheckedToggles().stream() @@ -129,10 +129,10 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) .pattern("111101111") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) .pattern("111010111") .build(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index 9a7bf4cc..fa22481e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -126,11 +126,11 @@ protected Mask getMask() { return BinaryMask.builder(getMenu()) .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName(Component.empty()).build()) .pattern("111101111") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("000000000") - .pattern("111111111") + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.EMPTY_MASK) + .pattern(Utils.FULL_MASK) .build(); } @@ -143,7 +143,6 @@ protected Mask getMask() { private void setTutorialClickEvent(int tutorialId, ClickType clickType) { if (tutorialId >= 0 && tutorialId < TutorialCategory.values().length) { if (clickType == ClickType.LEFT) { - // TutorialPlot plot = getPlotById(tutorialId); try { if (plot == null || !plot.isComplete()) { getMenuPlayer().closeInventory(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index b376dca3..e9a5bd3e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -25,30 +25,33 @@ package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DataProvider; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class BuildTeam { - private final int ID; + private final int id; private String name; private final List cityProjects; private final List reviewers; - public BuildTeam(int ID, String name, List cities, List reviewers) { - this.ID = ID; + @Contract(pure = true) + public BuildTeam(int id, String name, List cities, List reviewers) { + this.id = id; this.name = name; this.cityProjects = cities; this.reviewers = reviewers; } - public int getID() { - return ID; public BuildTeam(int id, String name) { this(id, name, new ArrayList<>(), new ArrayList<>()); } + public int getId() { + return id; } public String getName() { @@ -64,7 +67,7 @@ public List getReviewers() { } public boolean setName(String newName) { - if (DataProvider.BUILD_TEAM.setBuildTeamName(ID, newName)) { + if (DataProvider.BUILD_TEAM.setBuildTeamName(id, newName)) { this.name = newName; return true; } @@ -74,15 +77,15 @@ public boolean setName(String newName) { public boolean removeReviewer(String reviewerUUID) { Optional removeReviewer = reviewers.stream().filter(r -> r.getUUID().toString().equals(reviewerUUID)).findFirst(); if (removeReviewer.isEmpty()) return false; - if (DataProvider.BUILD_TEAM.removeReviewer(ID, reviewerUUID)) { + if (DataProvider.BUILD_TEAM.removeReviewer(id, reviewerUUID)) { this.reviewers.remove(removeReviewer.get()); return true; } return false; } - public boolean addReviewer(Builder reviewer) { - if (DataProvider.BUILD_TEAM.addReviewer(ID, reviewer.getUUID().toString())) { + public boolean addReviewer(@NotNull Builder reviewer) { + if (DataProvider.BUILD_TEAM.addReviewer(id, reviewer.getUUID().toString())) { this.reviewers.add(reviewer); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 1831cc76..96d9e284 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -28,8 +28,8 @@ import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; +import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.chat.ChatInput; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; @@ -72,6 +72,7 @@ private Utils() {} private static Random random; public static final String EMPTY_MASK = "000000000"; + public static final String FULL_MASK = "111111111"; // Spawn Location public static Location getSpawnLocation() { @@ -100,7 +101,7 @@ public static void updatePlayerInventorySlots(Player player) { } // TODO: extract to alpsLibs? - public static ItemStack getConfiguredItem(String material, Object customModelData) { + public static ItemStack getConfiguredItem(@NotNull String material, Object customModelData) { ItemStack base; if (material.startsWith("head(") && material.endsWith(")")) { String headId = material.substring(material.indexOf("(") + 1, material.lastIndexOf(")")); From c36a874f9eff7c63adb9a9ace90fa9aa00069366 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 26 Jun 2025 11:23:04 +0200 Subject: [PATCH 112/175] add insert for system info table --- .../plotsystem/core/database/DatabaseConnection.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index f87c5369..5dbe2263 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -41,7 +41,7 @@ public class DatabaseConnection { - private final static HikariConfig config = new HikariConfig(); + private static final HikariConfig config = new HikariConfig(); private static HikariDataSource dataSource; private static String URL; @@ -114,6 +114,9 @@ private static void createTables() { Objects.requireNonNull(con).prepareStatement(table).executeUpdate(); } + con.prepareStatement("INSERT INTO system_info (system_id, db_version, current_plot_version, description) " + + "VALUES (1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0')").executeUpdate(); + try (ResultSet rs = con.prepareStatement("SELECT COUNT(difficulty_id) FROM plot_difficulty").executeQuery()) { if (rs.next()) { if (rs.getInt(1) == 0) { @@ -124,8 +127,6 @@ private static void createTables() { } } } - - } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while creating á database table"), ex); } From c83a84db587161cbafd4738dc5eb48d90724323b Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 11:40:14 +0200 Subject: [PATCH 113/175] =?UTF-8?q?=F0=9F=93=9D=20Add=20myself=20as=20a=20?= =?UTF-8?q?contact/author=20+=20update=20the=20links?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/commands.yml | 4 ++-- src/main/resources/config.yml | 4 ++-- src/main/resources/items.yml | 7 +++++++ src/main/resources/lang/de_DE.yml | 5 +++-- src/main/resources/lang/en_GB.yml | 5 +++-- src/main/resources/lang/fr_FR.yml | 5 +++-- src/main/resources/lang/he_IL.yml | 5 +++-- src/main/resources/lang/ko_KR.yml | 5 +++-- src/main/resources/lang/pt_PT.yml | 5 +++-- src/main/resources/lang/ru_RU.yml | 5 +++-- src/main/resources/lang/zh_CN.yml | 5 +++-- src/main/resources/lang/zh_TW.yml | 5 +++-- src/main/resources/plugin.yml | 2 +- src/main/resources/tutorial/tutorial_beginner.yml | 4 ++-- src/main/resources/tutorial/tutorial_template.yml | 4 ++-- 15 files changed, 43 insertions(+), 27 deletions(-) diff --git a/src/main/resources/commands.yml b/src/main/resources/commands.yml index 084fd476..8f59bd11 100644 --- a/src/main/resources/commands.yml +++ b/src/main/resources/commands.yml @@ -2,8 +2,8 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/Plot-System/wiki/commands.yml +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot # ----------------------------------------------------- # Allow /editplot on plots for reviewers diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index c58e38ac..5acfae8f 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -2,8 +2,8 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/Plot-System/wiki/config.yml +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot # ----------------------------------------------------- # Keep updated about newer versions diff --git a/src/main/resources/items.yml b/src/main/resources/items.yml index 2ca7ca3b..8185b795 100644 --- a/src/main/resources/items.yml +++ b/src/main/resources/items.yml @@ -1,3 +1,10 @@ +# ----------------------------------------------------- +# | Plot System - by Alps BTE +# ----------------------------------------------------- +# | [Github Repo] https://github.com/AlpsBTE/PlotSystem +# | [Documentation] https://github.com/AlpsBTE/Plot-System/wiki/items.yml +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# ----------------------------------------------------- companion-item: material: NETHER_STAR modelId: '' diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index 788ac2b1..1f031735 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -2,8 +2,9 @@ #| Plot System - by Alps BTE #----------------------------------------------------- #| [Github Repo] https://github.com/AlpsBTE/PlotSystem -#| [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -#| [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +#| [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +#| [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +#| [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system #| #| [Formatting] Use %newline% for a newline #| [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 26f364fe..5b171631 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index ab88b4ec..6f78c20b 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -2,8 +2,9 @@ #| Plot System - by Alps BTE #----------------------------------------------------- #| [Github Repo] https://github.com/AlpsBTE/PlotSystem -#| [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -#| [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +#| [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +#| [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +#| [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system #| #| [Formatting] Use %newline% for a newline #| [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/he_IL.yml b/src/main/resources/lang/he_IL.yml index 7c5b0513..e36261d4 100644 --- a/src/main/resources/lang/he_IL.yml +++ b/src/main/resources/lang/he_IL.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index 2090f462..fd271fe1 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index ae6d8ef1..4814dbbc 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index fde46d7a..9b4c5616 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index b67a6be4..202502a3 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index 10c4bb0d..96d37700 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -2,8 +2,9 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot +# | [Localisation Platform] https://crowdin.com/project/alps-bte-plot-system # | # | [Formatting] Use %newline% for a newline # | [Formatting] Words that are wrapped in the {number} tag are replaced afterward diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 5a5f48fd..b50b3e88 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -2,7 +2,7 @@ main: com.alpsbte.plotsystem.PlotSystem version: 5.0.0 api-version: "1.21" name: Plot-System -author: R3tuxn & Cinnazeyy +author: R3tuxn, Cinnazeyy & Zoriot softdepend: [ LangLibs, FancyNpcs, VoidGen, FastAsyncWorldEdit, Multiverse-Core, WorldEdit, DecentHolograms, WorldGuard, WorldGuardExtraFlags, HeadDatabase, ProtocolLib, ParticleNativeAPI ] diff --git a/src/main/resources/tutorial/tutorial_beginner.yml b/src/main/resources/tutorial/tutorial_beginner.yml index 8528b40c..e2f063f4 100644 --- a/src/main/resources/tutorial/tutorial_beginner.yml +++ b/src/main/resources/tutorial/tutorial_beginner.yml @@ -2,8 +2,8 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot # | # | [Tutorial Config - Beginner] # | diff --git a/src/main/resources/tutorial/tutorial_template.yml b/src/main/resources/tutorial/tutorial_template.yml index 69981a04..80514b19 100644 --- a/src/main/resources/tutorial/tutorial_template.yml +++ b/src/main/resources/tutorial/tutorial_template.yml @@ -2,8 +2,8 @@ # | Plot System - by Alps BTE # ----------------------------------------------------- # | [Github Repo] https://github.com/AlpsBTE/PlotSystem -# | [Config Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/Configuration -# | [Contacts - Discord] R3tuxn#7169, Cinnazeyy#2440 +# | [Documentation] https://github.com/AlpsBTE/PlotSystem/wiki/ +# | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot # | # | [Tutorial Config - XYZ] # | From a0f335cadde93384bb899f4b42bc60130b3b6fea Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 11:49:00 +0200 Subject: [PATCH 114/175] =?UTF-8?q?=F0=9F=94=A5=E2=99=BB=EF=B8=8F=20Remove?= =?UTF-8?q?=20useless=20dependency=20+=20auto=20inject=20current=20version?= =?UTF-8?q?=20to=20plugin.yml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 3 +- pom.xml | 30 ++++++------ .../com/alpsbte/plotsystem/PlotSystem.java | 15 ------ .../plotsystem/core/EventListener.java | 12 +++-- .../plotsystem/utils/PacketListener.java | 48 ------------------- src/main/resources/plugin.yml | 4 +- 6 files changed, 26 insertions(+), 86 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/utils/PacketListener.java diff --git a/README.md b/README.md index 5cdf251d..bc48c5b8 100644 --- a/README.md +++ b/README.md @@ -121,12 +121,11 @@ Distributed under the MIT License. See `LICENSE` for more information. * [WorldGuard](https://github.com/EngineHub/WorldGuard) * [Multiverse Core](https://github.com/Multiverse/Multiverse-Core) * [Particle Native](https://github.com/Fierioziy/ParticleNativeAPI) -* [Canvas](https://github.com/IPVP-MC/canvas) +* [Canvas](https://github.com/AlpsBTE/Canvas) * [HeadDatabase](https://github.com/Arcaniax-Development/HeadDatabase-API) * [DecentHolograms](https://github.com/DecentSoftware-eu/DecentHolograms) * [MariaDB](https://mariadb.com/kb/en/about-mariadb-connector-j/) * [HikariCP](https://github.com/brettwooldridge/HikariCP) -* [ProtocolLIB](https://github.com/dmulloy2/ProtocolLib) * [Fancy NPCs](https://github.com/FancyMcPlugins/FancyNpcs) * [AlpsLib](https://github.com/AlpsBTE/Alps-Lib) * [LangLibs](https://github.com/Cinnazeyy/LangLibs) \ No newline at end of file diff --git a/pom.xml b/pom.xml index 5f8eab91..ca475f5a 100644 --- a/pom.xml +++ b/pom.xml @@ -1,8 +1,8 @@ - - dmulloy2-repo - https://repo.dmulloy2.net/repository/public/ -
@@ -164,13 +159,6 @@ 4.0.3 compile - - - com.comphenix.protocol - ProtocolLib - 5.1.0 - provided - de.oliver @@ -205,6 +193,16 @@ ${basedir}/src/main/resources false + + plugin.yml + + + + ${basedir}/src/main/resources + true + + plugin.yml + ./lang @@ -225,7 +223,7 @@ src/main/java/ - ${project.artifactId}-${project.version}-${build.number} + ${project.artifactId}-${project.version}${build.number} org.apache.maven.plugins @@ -271,7 +269,7 @@ UTF-8 UTF-8 - + 21 \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 1ef86b42..ea895e1d 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -42,13 +42,10 @@ import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPCTurnTracker; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; -import com.alpsbte.plotsystem.utils.PacketListener; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.comphenix.protocol.ProtocolLibrary; -import com.comphenix.protocol.ProtocolManager; import com.onarandombox.MultiverseCore.MultiverseCore; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; @@ -189,13 +186,6 @@ public void onEnable() { Utils.ChatUtils.checkForChatInputExpiry(); PlotUtils.Effects.startTimer(); - try { - new PacketListener(); - } catch (NoClassDefFoundError ex) { - Bukkit.getConsoleSender().sendMessage(empty()); - Bukkit.getConsoleSender().sendMessage(text("Could not find Protocol-Lib! Consider installing it to avoid issues.", RED)); - } - // Register tutorials if (getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE)) { AbstractTutorial.registerTutorials(Collections.singletonList(BeginnerTutorial.class)); @@ -365,11 +355,6 @@ public static WorldGuardPlugin getWorldGuard() { public static String getWorldGuardConfigPath(String worldName) { return Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("WorldGuard")).getDataFolder() + "/worlds/" + worldName; } - - /** - * @return Protocol Lib Instance - */ - public static ProtocolManager getProtocolManager() {return ProtocolLibrary.getProtocolManager();} } public static class UpdateChecker { diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 117f8c62..ac9a5538 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,8 +26,8 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; +import com.alpsbte.plotsystem.core.menus.review.ReviewMenu; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -49,6 +49,7 @@ import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.destroystokyo.paper.event.player.PlayerClientOptionsChangeEvent; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.flags.Flags; @@ -243,6 +244,11 @@ public void onLanguageChange(@NotNull LanguageChangeEvent event) { Utils.updatePlayerInventorySlots(event.getPlayer()); } + @EventHandler + public void onPlayerClientOptionsChange(@NotNull PlayerClientOptionsChangeEvent e) { + Utils.updatePlayerInventorySlots(e.getPlayer()); + } + private void handleIronTrapdoorClick(@NotNull PlayerInteractEvent event) { if (!event.getAction().equals(Action.RIGHT_CLICK_AIR) && !event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return; if (event.getHand() == EquipmentSlot.OFF_HAND) return; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/PacketListener.java b/src/main/java/com/alpsbte/plotsystem/utils/PacketListener.java deleted file mode 100644 index debff202..00000000 --- a/src/main/java/com/alpsbte/plotsystem/utils/PacketListener.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.utils; - -import com.alpsbte.plotsystem.PlotSystem; -import com.comphenix.protocol.PacketType; -import com.comphenix.protocol.ProtocolManager; -import com.comphenix.protocol.events.ListenerPriority; -import com.comphenix.protocol.events.PacketAdapter; -import com.comphenix.protocol.events.PacketEvent; - -public class PacketListener { - public PacketListener() { - ProtocolManager protocolManager = PlotSystem.DependencyManager.getProtocolManager(); - if (protocolManager != null) { - // Update inventory slots of player after changing client game settings - protocolManager.addPacketListener(new PacketAdapter(PlotSystem.getPlugin(), - ListenerPriority.LOWEST, PacketType.Play.Client.SETTINGS) { - @Override - public void onPacketReceiving(PacketEvent event) { - Utils.updatePlayerInventorySlots(event.getPlayer()); - } - }); - } - } -} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index b50b3e88..1b02f169 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,10 +1,10 @@ main: com.alpsbte.plotsystem.PlotSystem -version: 5.0.0 +version: "${project.version}${build.number}" api-version: "1.21" name: Plot-System author: R3tuxn, Cinnazeyy & Zoriot softdepend: [ LangLibs, FancyNpcs, VoidGen, FastAsyncWorldEdit, Multiverse-Core, WorldEdit, - DecentHolograms, WorldGuard, WorldGuardExtraFlags, HeadDatabase, ProtocolLib, ParticleNativeAPI ] + DecentHolograms, WorldGuard, WorldGuardExtraFlags, HeadDatabase, ParticleNativeAPI ] commands: cancelchat: From 6160df7559e90056e13568fd630caff5dca260cb Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 12:26:16 +0200 Subject: [PATCH 115/175] =?UTF-8?q?=F0=9F=94=A5=20Remove=20updater?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Will be moved to the Alps Utils when we have time. --- .../com/alpsbte/plotsystem/PlotSystem.java | 48 ------------------- 1 file changed, 48 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index ea895e1d..77d081b3 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -51,7 +51,6 @@ import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import de.oliver.fancynpcs.api.FancyNpcsPlugin; import net.kyori.adventure.text.Component; -import org.apache.maven.artifact.versioning.ComparableVersion; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.plugin.PluginManager; @@ -59,12 +58,7 @@ import org.ipvp.canvas.MenuFunctionListener; import org.jetbrains.annotations.NotNull; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; import java.util.*; -import java.util.function.Consumer; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; @@ -165,21 +159,6 @@ public void onEnable() { return; } - // Check for updates - Bukkit.getConsoleSender().sendMessage(empty()); - Bukkit.getConsoleSender().sendMessage(text("Update-Checker:", GOLD)); - - UpdateChecker.getVersion(version -> { - if (new ComparableVersion(VERSION).compareTo(new ComparableVersion(version)) >= 0) { - Bukkit.getConsoleSender().sendMessage(text("You are using the latest stable version.", YELLOW)); - } else { - UpdateChecker.isUpdateAvailable = true; - Bukkit.getConsoleSender().sendMessage(text("You are using a outdated version!", RED)); - Bukkit.getConsoleSender().sendMessage(text("Latest version: ", GRAY).append(text(version, GREEN)).append(text(" | Your version: ", GRAY)).append(text(VERSION, RED))); - Bukkit.getConsoleSender().sendMessage(text("Update here: ", GRAY).append(text("https://github.com/AlpsBTE/Plot-System/releases", AQUA))); - } - }); - DecentHologramDisplay.registerPlugin(this); HologramRegister.init(); PlotUtils.checkPlotsForLastActivity(); @@ -356,31 +335,4 @@ public static String getWorldGuardConfigPath(String worldName) { return Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("WorldGuard")).getDataFolder() + "/worlds/" + worldName; } } - - public static class UpdateChecker { - private static final int RESOURCE_ID = 95757; - private static boolean isUpdateAvailable = false; - - /** - * Get the latest plugin version from SpigotMC - * - * @param version Returns latest stable version - */ - public static void getVersion(final Consumer version) { - try (InputStream inputStream = new URI("https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID).toURL().openStream(); Scanner scanner = new Scanner(inputStream)) { - if (scanner.hasNext()) { - version.accept(scanner.next()); - } - } catch (IOException | URISyntaxException ex) { - PlotSystem.getPlugin().getComponentLogger().warn(text("Cannot look for new updates:" + ex.getMessage())); - } - } - - /** - * @return True if an update is available - */ - public static boolean updateAvailable() { - return isUpdateAvailable; - } - } } \ No newline at end of file From fd3a8a5a73625a66aa87c71a440ccb1cffad0679 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 12:39:39 +0200 Subject: [PATCH 116/175] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Extract=20Dependen?= =?UTF-8?q?cyManager=20in=20seperate=20class=20+=20get=20the=20current=20v?= =?UTF-8?q?ersion=20dynamically.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Useless methods were removed & it was switched to using the logger. --- .../com/alpsbte/plotsystem/PlotSystem.java | 186 +++--------------- .../plotsystem/core/EventListener.java | 12 +- .../plot/generator/AbstractPlotGenerator.java | 3 +- .../plot/generator/PlotWorldGenerator.java | 9 +- .../plot/generator/TutorialPlotGenerator.java | 3 +- .../core/system/plot/utils/PlotUtils.java | 15 +- .../core/system/plot/world/PlotWorld.java | 9 +- .../plotsystem/utils/DependencyManager.java | 143 ++++++++++++++ .../com/alpsbte/plotsystem/utils/Utils.java | 8 +- 9 files changed, 199 insertions(+), 189 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 77d081b3..fa0c5527 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -42,67 +42,49 @@ import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPCTurnTracker; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangUtil; -import com.onarandombox.MultiverseCore.MultiverseCore; -import com.sk89q.worldedit.WorldEdit; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import de.oliver.fancynpcs.api.FancyNpcsPlugin; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.ipvp.canvas.MenuFunctionListener; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.Collections; +import java.util.UUID; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; public class PlotSystem extends JavaPlugin { - private static final String VERSION = "5.0.0"; - private static PlotSystem plugin; - private CommandManager commandManager; - private boolean pluginEnabled = false; @Override public void onEnable() { - System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog"); // Disable Logging YamlFileFactory.registerPlugin(this); plugin = this; Component successPrefix = text("[", DARK_GRAY).append(text("✔", DARK_GREEN)).append(text("]", DARK_GRAY)).append(text(" ", GRAY)); Component errorPrefix = text("[", DARK_GRAY).append(text("X", RED)).append(text("]", DARK_GRAY)).append(text(" ", GRAY)); - Bukkit.getConsoleSender().sendMessage(text("------------------ Plot-System V" + VERSION + " ------------------", GOLD)); - Bukkit.getConsoleSender().sendMessage(text("Starting plugin...", DARK_GREEN)); - Bukkit.getConsoleSender().sendMessage(empty()); + getComponentLogger().info(text("------------------ Plot-System V" + getPluginMeta().getVersion() + " ------------------", GOLD)); + getComponentLogger().info(text("Starting plugin...", DARK_GREEN).append(empty())); - // Check for required dependencies, if it returns false disable plugin - if (!DependencyManager.checkForRequiredDependencies()) { - Bukkit.getConsoleSender().sendMessage(errorPrefix.append(text("Could not load required dependencies."))); - Bukkit.getConsoleSender().sendMessage(text("Missing Dependencies:", YELLOW)); - DependencyManager.missingDependencies.forEach(dependency -> Bukkit.getConsoleSender().sendMessage(text(" - " + dependency, YELLOW))); - - this.getServer().getPluginManager().disablePlugin(this); - return; - } - Bukkit.getConsoleSender().sendMessage(successPrefix.append(text("Successfully loaded required dependencies."))); + if (!DependencyManager.notifyAndCheckIfContainsAllRequiredDependencies(successPrefix, errorPrefix)) return; // Load config, if it throws an exception disable plugin try { ConfigUtil.init(); - Bukkit.getConsoleSender().sendMessage(successPrefix.append(text("Successfully loaded configuration files."))); + getComponentLogger().info(successPrefix.append(text("Successfully loaded configuration files."))); } catch (ConfigNotImplementedException ex) { - Bukkit.getConsoleSender().sendMessage(errorPrefix.append(text("Could not load configuration file."))); - Bukkit.getConsoleSender().sendMessage(text("The config file must be configured!", YELLOW)); - + getComponentLogger().error(errorPrefix.append(text("Could not load configuration file."))); + getComponentLogger().info(text("The config file must be configured!", YELLOW)); this.getServer().getPluginManager().disablePlugin(this); return; } @@ -111,9 +93,9 @@ public void onEnable() { // Load language files try { LangUtil.init(); - Bukkit.getConsoleSender().sendMessage(successPrefix.append(text("Successfully loaded language files."))); + getComponentLogger().info(successPrefix.append(text("Successfully loaded language files."))); } catch (Exception ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not load language file."), ex); + getComponentLogger().error(errorPrefix.append(text("Could not load language file.")), ex); this.getServer().getPluginManager().disablePlugin(this); return; } @@ -121,11 +103,9 @@ public void onEnable() { // Initialize database connection try { DatabaseConnection.InitializeDatabase(); - Bukkit.getConsoleSender().sendMessage(successPrefix.append(text("Successfully initialized database connection."))); + getComponentLogger().info(successPrefix.append(text("Successfully initialized database connection."))); } catch (Exception ex) { - Bukkit.getConsoleSender().sendMessage(errorPrefix.append(text("Could not initialize database connection."))); - PlotSystem.getPlugin().getComponentLogger().error(text(ex.getMessage()), ex); - + getComponentLogger().error(errorPrefix.append(text("Could not initialize database connection.")), ex); this.getServer().getPluginManager().disablePlugin(this); return; } @@ -137,24 +117,20 @@ public void onEnable() { this.getServer().getPluginManager().registerEvents(new AlpsHeadEventListener(), this); if (getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE)) this.getServer().getPluginManager().registerEvents(new TutorialEventListener(), this); - Bukkit.getConsoleSender().sendMessage(successPrefix.append(text("Successfully registered event listeners."))); + getComponentLogger().info(successPrefix.append(text("Successfully registered event listeners."))); } catch (Exception ex) { - Bukkit.getConsoleSender().sendMessage(errorPrefix.append(text("Could not register event listeners."))); - PlotSystem.getPlugin().getComponentLogger().error(text(ex.getMessage()), ex); - + getComponentLogger().error(errorPrefix.append(text("Could not register event listeners.")), ex); this.getServer().getPluginManager().disablePlugin(this); return; } // Register commands try { - commandManager = new CommandManager(); + CommandManager commandManager = new CommandManager(); commandManager.init(); - Bukkit.getConsoleSender().sendMessage(successPrefix.append(text("Successfully registered commands."))); + getComponentLogger().info(successPrefix.append(text("Successfully registered commands."))); } catch (Exception ex) { - Bukkit.getConsoleSender().sendMessage(errorPrefix.append(text("Could not register commands."))); - PlotSystem.getPlugin().getComponentLogger().error(text(ex.getMessage()), ex); - + getComponentLogger().error(errorPrefix.append(text("Could not register commands.")), ex); this.getServer().getPluginManager().disablePlugin(this); return; } @@ -172,23 +148,21 @@ public void onEnable() { } pluginEnabled = true; - Bukkit.getConsoleSender().sendMessage(empty()); - Bukkit.getConsoleSender().sendMessage(text("Enabled Plot-System plugin.", DARK_GREEN)); - Bukkit.getConsoleSender().sendMessage(text("------------------------------------------------------", GOLD)); - Bukkit.getConsoleSender().sendMessage(text("> ", DARK_GRAY).append(text("Made by ", GRAY)).append(text("Alps BTE (AT/CH/LI)", RED))); - Bukkit.getConsoleSender().sendMessage(text("> ", DARK_GRAY).append(text("GitHub: ", GRAY)).append(text("https://github.com/AlpsBTE/Plot-System", WHITE))); - Bukkit.getConsoleSender().sendMessage(text("------------------------------------------------------", GOLD)); + getComponentLogger().info(text("Enabled Plot-System plugin.", DARK_GREEN)); + getComponentLogger().info(text("------------------------------------------------------", GOLD)); + getComponentLogger().info(text("> ", DARK_GRAY).append(text("Made by ", GRAY)).append(text("Alps BTE (AT/CH/LI)", RED))); + getComponentLogger().info(text("> ", DARK_GRAY).append(text("GitHub: ", GRAY)).append(text("https://github.com/AlpsBTE/Plot-System", WHITE))); + getComponentLogger().info(text("------------------------------------------------------", GOLD)); } @Override public void onDisable() { if (!pluginEnabled) { - Bukkit.getConsoleSender().sendMessage(empty()); - Bukkit.getConsoleSender().sendMessage(text("Disabling plugin...", RED)); - Bukkit.getConsoleSender().sendMessage(text("------------------------------------------------------", GOLD)); - Bukkit.getConsoleSender().sendMessage(text("> ", DARK_GRAY).append(text("Made by ", GRAY)).append(text("Alps BTE (AT/CH/LI)", RED))); - Bukkit.getConsoleSender().sendMessage(text("> ", DARK_GRAY).append(text("GitHub: ", GRAY)).append(text("https://github.com/AlpsBTE/Plot-System", WHITE))); - Bukkit.getConsoleSender().sendMessage(text("------------------------------------------------------", GOLD)); + getComponentLogger().info(text("Disabling plugin...", RED)); + getComponentLogger().info(text("------------------------------------------------------", GOLD)); + getComponentLogger().info(text("> ", DARK_GRAY).append(text("Made by ", GRAY)).append(text("Alps BTE (AT/CH/LI)", RED))); + getComponentLogger().info(text("> ", DARK_GRAY).append(text("GitHub: ", GRAY)).append(text("https://github.com/AlpsBTE/Plot-System", WHITE))); + getComponentLogger().info(text("------------------------------------------------------", GOLD)); DecentHologramDisplay.activeDisplays.forEach(DecentHologramDisplay::delete); } else { @@ -231,108 +205,4 @@ public void saveConfig() { public static PlotSystem getPlugin() { return plugin; } - public CommandManager getCommandManager() { - return commandManager; - } - - - public static class DependencyManager { - - // List with all missing dependencies - private static final List missingDependencies = new ArrayList<>(); - - /** - * Check for all required dependencies and inform in console about missing dependencies - * - * @return True if all dependencies are present - */ - private static boolean checkForRequiredDependencies() { - PluginManager pluginManager = plugin.getServer().getPluginManager(); - if (!pluginManager.isPluginEnabled("DecentHolograms")) { - missingDependencies.add("DecentHolograms"); - } - - if (!pluginManager.isPluginEnabled("Multiverse-Core")) { - missingDependencies.add("Multiverse-Core"); - } - - if (!pluginManager.isPluginEnabled("FastAsyncWorldEdit")) { - missingDependencies.add("FastAsyncWorldEdit"); - } - - if (!pluginManager.isPluginEnabled("WorldGuard")) { - missingDependencies.add("WorldGuard"); - } - - if (!pluginManager.isPluginEnabled("HeadDatabase")) { - missingDependencies.add("HeadDatabase"); - } - - if (!pluginManager.isPluginEnabled("VoidGen")) { - missingDependencies.add("VoidGen"); - } - - if (!pluginManager.isPluginEnabled("LangLibs")) { - missingDependencies.add("LangLibs"); - } - - if (!pluginManager.isPluginEnabled("FancyNpcs")) { - missingDependencies.add("FancyNpcs"); - } - - return missingDependencies.isEmpty(); - } - - /** - * @return True if ParticleNativeAPI is present - */ - public static boolean isParticleNativeAPIEnabled() { - return plugin.getServer().getPluginManager().isPluginEnabled("ParticleNativeAPI"); - } - - public static boolean isMultiverseInventoriesEnabled() { - return plugin.getServer().getPluginManager().isPluginEnabled("Multiverse-Inventories"); - } - - public static boolean isWorldGuardExtraFlagsEnabled() { - return plugin.getServer().getPluginManager().isPluginEnabled("WorldGuardExtraFlags"); - } - - /** - * @param worldName Name of the world - * @return Config path for the world - */ - public static String getMultiverseInventoriesConfigPath(String worldName) { - return PlotSystem.DependencyManager.isMultiverseInventoriesEnabled() ? Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("Multiverse-Inventories")).getDataFolder() + "/worlds/" + worldName : ""; - } - - /** - * @return Multiverse-Core instance - */ - public static MultiverseCore getMultiverseCore() { - return (MultiverseCore) plugin.getServer().getPluginManager().getPlugin("Multiverse-Core"); - } - - /** - * @return World Edit instance - */ - public static WorldEdit getWorldEdit() { - return WorldEdit.getInstance(); - } - - /** - * @return World Guard instance - */ - public static WorldGuardPlugin getWorldGuard() { - return WorldGuardPlugin.inst(); - } - - /** - * @param worldName Name of the world - * @return Config path for the world - */ - public static String getWorldGuardConfigPath(String worldName) { - return Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("WorldGuard")).getDataFolder() + "/worlds/" + worldName; - } - } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index ac9a5538..1f1d5b15 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -40,6 +40,7 @@ import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; import com.alpsbte.plotsystem.core.system.tutorial.Tutorial; import com.alpsbte.plotsystem.core.system.tutorial.TutorialCategory; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.alpsbte.plotsystem.utils.PlotMemberInvitation; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.chat.ChatInput; @@ -258,7 +259,7 @@ private void handleIronTrapdoorClick(@NotNull PlayerInteractEvent event) { RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); RegionQuery query = regionContainer.createQuery(); - if (!query.testBuild(BukkitAdapter.adapt(event.getPlayer().getLocation()), PlotSystem.DependencyManager.getWorldGuard().wrapPlayer(event.getPlayer()), Flags.INTERACT)) return; + if (!query.testBuild(BukkitAdapter.adapt(event.getPlayer().getLocation()), DependencyManager.getWorldGuard().wrapPlayer(event.getPlayer()), Flags.INTERACT)) return; BlockState state = event.getClickedBlock().getState(); Openable tp = (Openable) state.getBlockData(); @@ -273,7 +274,6 @@ private void handleIronTrapdoorClick(@NotNull PlayerInteractEvent event) { } private void sendNotices(@NotNull Player player, Builder builder) { - sendAdminNotices(player); sendReviewNotices(player, builder); // Start or notify the player if he has not completed the beginner tutorial yet (only if required) @@ -288,14 +288,6 @@ private void sendNotices(@NotNull Player player, Builder builder) { } } - private void sendAdminNotices(@NotNull Player player) { - // Inform player about update - if (player.hasPermission("plotsystem.admin") && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.CHECK_FOR_UPDATES) && PlotSystem.UpdateChecker.updateAvailable()) { - player.sendMessage(Utils.ChatUtils.getInfoFormat("There is a new update for the Plot-System available. Check your console for more information!")); - player.playSound(player.getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); - } - } - private void sendReviewNotices(@NotNull Player player, Builder builder) { // Informing player about new feedback List notifications = DataProvider.REVIEW.getReviewNotifications(player.getUniqueId()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index f6b98810..f85c53ac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -33,6 +33,7 @@ import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; @@ -209,7 +210,7 @@ protected void createPlotProtection() throws StorageException { protected void setBuildRegionPermissions(@NotNull ProtectedRegion region) { region.setFlag(Flags.BUILD, StateFlag.State.ALLOW); region.setFlag(Flags.BUILD.getRegionGroupFlag(), RegionGroup.OWNERS); - if (PlotSystem.DependencyManager.isWorldGuardExtraFlagsEnabled()) + if (DependencyManager.isWorldGuardExtraFlagsEnabled()) region.setFlag(new StateFlag("worldedit", true, RegionGroup.OWNERS), StateFlag.State.ALLOW); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java index 2b4079d0..2482bb4a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -25,6 +25,7 @@ package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.onarandombox.MultiverseCore.api.MVWorldManager; import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -46,7 +47,7 @@ import static net.kyori.adventure.text.Component.text; public class PlotWorldGenerator { - private final MVWorldManager worldManager = PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager(); + private final MVWorldManager worldManager = DependencyManager.getMultiverseCore().getMVWorldManager(); private WorldCreator worldCreator; private final String worldName; @@ -127,7 +128,7 @@ protected void createGlobalProtection() throws StorageException { globalRegion.setFlag(Flags.PASSTHROUGH.getRegionGroupFlag(), RegionGroup.ALL); globalRegion.setFlag(Flags.TNT, StateFlag.State.DENY); globalRegion.setFlag(Flags.TNT.getRegionGroupFlag(), RegionGroup.ALL); - if (PlotSystem.DependencyManager.isWorldGuardExtraFlagsEnabled()) + if (DependencyManager.isWorldGuardExtraFlagsEnabled()) globalRegion.setFlag(new StateFlag("worldedit", true, RegionGroup.ALL), StateFlag.State.DENY); if (regionManager.hasRegion(regionName)) regionManager.removeRegion(regionName); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java index fd309074..1b3028e2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java @@ -29,6 +29,7 @@ import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldguard.WorldGuard; @@ -67,7 +68,7 @@ protected void setBuildRegionPermissions(@NotNull ProtectedRegion region) { region.setFlag(Flags.BUILD, isBuildingEnabled() ? StateFlag.State.ALLOW : StateFlag.State.DENY); region.setFlag(Flags.BUILD.getRegionGroupFlag(), RegionGroup.OWNERS); - if (PlotSystem.DependencyManager.isWorldGuardExtraFlagsEnabled()) + if (DependencyManager.isWorldGuardExtraFlagsEnabled()) region.setFlag(new StateFlag("worldedit", false, RegionGroup.OWNERS), isWorldEditEnabled() ? StateFlag.State.ALLOW : StateFlag.State.DENY); try { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 7bc405fd..3ab7c971 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -37,6 +37,7 @@ import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.core.system.review.ReviewNotification; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.alpsbte.plotsystem.utils.ShortLink; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; @@ -44,7 +45,7 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.github.fierioziy.particlenativeapi.api.ParticleNativeAPI; -import com.github.fierioziy.particlenativeapi.api.Particles_1_8; +import com.github.fierioziy.particlenativeapi.api.Particles_1_13; import com.github.fierioziy.particlenativeapi.plugin.ParticleNativePlugin; import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -172,7 +173,7 @@ public static boolean isPlayerOnPlot(@NotNull AbstractPlot plot, Player player) } public static boolean isPlotWorld(World world) { - return PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().isMVWorld(world) && (PlotWorld.isOnePlotWorld(world.getName()) || PlotWorld.isCityPlotWorld(world.getName())); + return DependencyManager.getMultiverseCore().getMVWorldManager().isMVWorld(world) && (PlotWorld.isOnePlotWorld(world.getName()) || PlotWorld.isCityPlotWorld(world.getName())); } public static byte @Nullable [] getOutlinesSchematicBytes(@NotNull AbstractPlot plot, World world) throws IOException { @@ -482,24 +483,24 @@ private Effects() {} private static int time; private static boolean particleAPIEnabled = false; - private static Particles_1_8 particles; + private static Particles_1_13 particles; public static void loadParticleNativeAPI() { - particleAPIEnabled = PlotSystem.DependencyManager.isParticleNativeAPIEnabled(); + particleAPIEnabled = DependencyManager.isParticleNativeAPIEnabled(); // get API ParticleNativeAPI api = ParticleNativePlugin.getAPI(); // choose particle list you want to use - particles = api.getParticles_1_8(); + particles = api.getParticles_1_13(); } public static void startTimer() { - if (PlotSystem.DependencyManager.isParticleNativeAPIEnabled()) + if (DependencyManager.isParticleNativeAPIEnabled()) loadParticleNativeAPI(); Bukkit.getScheduler().scheduleSyncDelayedTask(PlotSystem.getPlugin(), () -> { - if (PlotSystem.DependencyManager.isParticleNativeAPIEnabled()) + if (DependencyManager.isParticleNativeAPIEnabled()) loadParticleNativeAPI(); }, 20 * 10L); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index 9137002a..ce0ccadb 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.generator.AbstractPlotGenerator; +import com.alpsbte.plotsystem.utils.DependencyManager; import com.alpsbte.plotsystem.utils.Utils; import com.onarandombox.MultiverseCore.MultiverseCore; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -60,7 +61,7 @@ public class PlotWorld implements IWorld { public static final int MAX_WORLD_HEIGHT = 256; public static final int MIN_WORLD_HEIGHT = 5; - private final MultiverseCore mvCore = PlotSystem.DependencyManager.getMultiverseCore(); + private final MultiverseCore mvCore = DependencyManager.getMultiverseCore(); private final String worldName; private final AbstractPlot plot; @@ -84,8 +85,8 @@ public boolean deleteWorld() { if (isWorldGenerated() && loadWorld()) { if (mvCore.getMVWorldManager().deleteWorld(getWorldName(), true, true) && mvCore.saveWorldConfig()) { try { - File multiverseInventoriesConfig = new File(PlotSystem.DependencyManager.getMultiverseInventoriesConfigPath(getWorldName())); - File worldGuardConfig = new File(PlotSystem.DependencyManager.getWorldGuardConfigPath(getWorldName())); + File multiverseInventoriesConfig = new File(DependencyManager.getMultiverseInventoriesConfigPath(getWorldName())); + File worldGuardConfig = new File(DependencyManager.getWorldGuardConfigPath(getWorldName())); if (multiverseInventoriesConfig.exists()) FileUtils.deleteDirectory(multiverseInventoriesConfig); if (worldGuardConfig.exists()) FileUtils.deleteDirectory(worldGuardConfig); } catch (IOException ex) { @@ -145,7 +146,7 @@ public Location getSpawnPoint(BlockVector3 plotVector) { } // Set spawn point 1 block above the highest block at the spawn location - spawnLocation.setY(getBukkitWorld().getHighestBlockYAt((int) spawnLocation.getX(), (int) spawnLocation.getZ()) + 1); + spawnLocation.setY(getBukkitWorld().getHighestBlockYAt((int) spawnLocation.getX(), (int) spawnLocation.getZ()) + 1d); return spawnLocation; } return null; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java b/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java new file mode 100644 index 00000000..d8ef2288 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java @@ -0,0 +1,143 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.alpsbte.plotsystem.utils; + +import com.alpsbte.plotsystem.PlotSystem; +import com.onarandombox.MultiverseCore.MultiverseCore; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import net.kyori.adventure.text.Component; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; + +public class DependencyManager { + private DependencyManager() {} + + /** + * Check for all required dependencies and inform in console about missing dependencies + * + * @return True if all dependencies are present + */ + public static boolean notifyAndCheckIfContainsAllRequiredDependencies(Component successPrefix, Component errorPrefix) { + PlotSystem plugin = PlotSystem.getPlugin(); + PluginManager pluginManager = plugin.getServer().getPluginManager(); + // List with all missing dependencies + List missingDependencies = new ArrayList<>(); + if (!pluginManager.isPluginEnabled("DecentHolograms")) { + missingDependencies.add("DecentHolograms"); + } + + if (!pluginManager.isPluginEnabled("Multiverse-Core")) { + missingDependencies.add("Multiverse-Core"); + } + + if (!pluginManager.isPluginEnabled("FastAsyncWorldEdit")) { + missingDependencies.add("FastAsyncWorldEdit"); + } + + if (!pluginManager.isPluginEnabled("WorldGuard")) { + missingDependencies.add("WorldGuard"); + } + + if (!pluginManager.isPluginEnabled("HeadDatabase")) { + missingDependencies.add("HeadDatabase"); + } + + if (!pluginManager.isPluginEnabled("VoidGen")) { + missingDependencies.add("VoidGen"); + } + + if (!pluginManager.isPluginEnabled("LangLibs")) { + missingDependencies.add("LangLibs"); + } + + if (!pluginManager.isPluginEnabled("FancyNpcs")) { + missingDependencies.add("FancyNpcs"); + } + + if (missingDependencies.isEmpty()) { + plugin.getComponentLogger().info(successPrefix.append(text("Successfully loaded required dependencies."))); + } else { + plugin.getComponentLogger().error(errorPrefix.append(text("Could not load required dependencies."))); + plugin.getComponentLogger().error(text("Missing Dependencies:", YELLOW)); + missingDependencies.forEach(dependency -> plugin.getComponentLogger().error(text(" - " + dependency, YELLOW))); + PlotSystem.getPlugin().getServer().getPluginManager().disablePlugin(PlotSystem.getPlugin()); + } + + return missingDependencies.isEmpty(); + } + + /** + * @return True if ParticleNativeAPI is present + */ + public static boolean isParticleNativeAPIEnabled() { + return PlotSystem.getPlugin().getServer().getPluginManager().isPluginEnabled("ParticleNativeAPI"); + } + + public static boolean isMultiverseInventoriesEnabled() { + return PlotSystem.getPlugin().getServer().getPluginManager().isPluginEnabled("Multiverse-Inventories"); + } + + public static boolean isWorldGuardExtraFlagsEnabled() { + return PlotSystem.getPlugin().getServer().getPluginManager().isPluginEnabled("WorldGuardExtraFlags"); + } + + /** + * @param worldName Name of the world + * @return Config path for the world + */ + public static @NotNull String getMultiverseInventoriesConfigPath(String worldName) { + return DependencyManager.isMultiverseInventoriesEnabled() ? Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("Multiverse-Inventories")).getDataFolder() + "/worlds/" + worldName : ""; + } + + /** + * @return Multiverse-Core instance + */ + public static MultiverseCore getMultiverseCore() { + return (MultiverseCore) PlotSystem.getPlugin().getServer().getPluginManager().getPlugin("Multiverse-Core"); + } + + /** + * @return World Guard instance + */ + public static WorldGuardPlugin getWorldGuard() { + return WorldGuardPlugin.inst(); + } + + /** + * @param worldName Name of the world + * @return Config path for the world + */ + public static @NotNull String getWorldGuardConfigPath(String worldName) { + return Objects.requireNonNull(Bukkit.getPluginManager().getPlugin("WorldGuard")).getDataFolder() + "/worlds/" + worldName; + } +} diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 96d9e284..19735831 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -80,14 +80,14 @@ public static Location getSpawnLocation() { if (!Objects.requireNonNull(config.getString(ConfigPaths.SPAWN_WORLD)).equalsIgnoreCase("default")) { try { - MultiverseWorld spawnWorld = PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().getMVWorld(config.getString(ConfigPaths.SPAWN_WORLD)); + MultiverseWorld spawnWorld = DependencyManager.getMultiverseCore().getMVWorldManager().getMVWorld(config.getString(ConfigPaths.SPAWN_WORLD)); return spawnWorld.getSpawnLocation(); } catch (Exception ignore) { PlotSystem.getPlugin().getComponentLogger().warn(text("Could not find %s in multiverse config!"), ConfigPaths.SPAWN_WORLD); } } - return PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().getSpawnWorld().getSpawnLocation(); + return DependencyManager.getMultiverseCore().getMVWorldManager().getSpawnWorld().getSpawnLocation(); } public static void updatePlayerInventorySlots(Player player) { From 2712746961756e440e1935f3c1047228aa92caca Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 12:44:58 +0200 Subject: [PATCH 117/175] =?UTF-8?q?=F0=9F=94=A5=20Remove=20manuel=20hard?= =?UTF-8?q?=20required=20dependency=20checking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It doesn't make sense to do the exact same thing like Paper already does. Maybe it will come back in Alps Lib with more Features. Moved to required things as depend so it will be resolved correctly. --- .../com/alpsbte/plotsystem/PlotSystem.java | 7 --- .../plotsystem/utils/DependencyManager.java | 61 ------------------- src/main/resources/plugin.yml | 5 +- 3 files changed, 3 insertions(+), 70 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index fa0c5527..ec10248a 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -42,7 +42,6 @@ import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPCTurnTracker; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; -import com.alpsbte.plotsystem.utils.DependencyManager; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; @@ -58,7 +57,6 @@ import java.util.Collections; import java.util.UUID; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.*; @@ -73,11 +71,6 @@ public void onEnable() { Component successPrefix = text("[", DARK_GRAY).append(text("✔", DARK_GREEN)).append(text("]", DARK_GRAY)).append(text(" ", GRAY)); Component errorPrefix = text("[", DARK_GRAY).append(text("X", RED)).append(text("]", DARK_GRAY)).append(text(" ", GRAY)); - getComponentLogger().info(text("------------------ Plot-System V" + getPluginMeta().getVersion() + " ------------------", GOLD)); - getComponentLogger().info(text("Starting plugin...", DARK_GREEN).append(empty())); - - if (!DependencyManager.notifyAndCheckIfContainsAllRequiredDependencies(successPrefix, errorPrefix)) return; - // Load config, if it throws an exception disable plugin try { ConfigUtil.init(); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java b/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java index d8ef2288..65edb5c7 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java @@ -27,75 +27,14 @@ import com.alpsbte.plotsystem.PlotSystem; import com.onarandombox.MultiverseCore.MultiverseCore; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; -import org.bukkit.plugin.PluginManager; import org.jetbrains.annotations.NotNull; -import java.util.ArrayList; -import java.util.List; import java.util.Objects; -import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; - public class DependencyManager { private DependencyManager() {} - /** - * Check for all required dependencies and inform in console about missing dependencies - * - * @return True if all dependencies are present - */ - public static boolean notifyAndCheckIfContainsAllRequiredDependencies(Component successPrefix, Component errorPrefix) { - PlotSystem plugin = PlotSystem.getPlugin(); - PluginManager pluginManager = plugin.getServer().getPluginManager(); - // List with all missing dependencies - List missingDependencies = new ArrayList<>(); - if (!pluginManager.isPluginEnabled("DecentHolograms")) { - missingDependencies.add("DecentHolograms"); - } - - if (!pluginManager.isPluginEnabled("Multiverse-Core")) { - missingDependencies.add("Multiverse-Core"); - } - - if (!pluginManager.isPluginEnabled("FastAsyncWorldEdit")) { - missingDependencies.add("FastAsyncWorldEdit"); - } - - if (!pluginManager.isPluginEnabled("WorldGuard")) { - missingDependencies.add("WorldGuard"); - } - - if (!pluginManager.isPluginEnabled("HeadDatabase")) { - missingDependencies.add("HeadDatabase"); - } - - if (!pluginManager.isPluginEnabled("VoidGen")) { - missingDependencies.add("VoidGen"); - } - - if (!pluginManager.isPluginEnabled("LangLibs")) { - missingDependencies.add("LangLibs"); - } - - if (!pluginManager.isPluginEnabled("FancyNpcs")) { - missingDependencies.add("FancyNpcs"); - } - - if (missingDependencies.isEmpty()) { - plugin.getComponentLogger().info(successPrefix.append(text("Successfully loaded required dependencies."))); - } else { - plugin.getComponentLogger().error(errorPrefix.append(text("Could not load required dependencies."))); - plugin.getComponentLogger().error(text("Missing Dependencies:", YELLOW)); - missingDependencies.forEach(dependency -> plugin.getComponentLogger().error(text(" - " + dependency, YELLOW))); - PlotSystem.getPlugin().getServer().getPluginManager().disablePlugin(PlotSystem.getPlugin()); - } - - return missingDependencies.isEmpty(); - } - /** * @return True if ParticleNativeAPI is present */ diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 1b02f169..e7703628 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -3,8 +3,9 @@ version: "${project.version}${build.number}" api-version: "1.21" name: Plot-System author: R3tuxn, Cinnazeyy & Zoriot -softdepend: [ LangLibs, FancyNpcs, VoidGen, FastAsyncWorldEdit, Multiverse-Core, WorldEdit, - DecentHolograms, WorldGuard, WorldGuardExtraFlags, HeadDatabase, ParticleNativeAPI ] +depend: [ LangLibs, FancyNpcs, VoidGen, FastAsyncWorldEdit, Multiverse-Core, + DecentHolograms, WorldGuard, HeadDatabase ] +softdepend: [ WorldGuardExtraFlags, ParticleNativeAPI ] commands: cancelchat: From cdbc265d14d94182753e661082720ca13a1d720d Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 13:24:03 +0200 Subject: [PATCH 118/175] =?UTF-8?q?=F0=9F=90=9B=20Create=20the=20initial?= =?UTF-8?q?=20system=5Finfo=20entry=20only=20once?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/database/DatabaseConnection.java | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index 87c41c26..a7f138a8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -31,7 +31,6 @@ import org.bukkit.configuration.file.FileConfiguration; import java.sql.*; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -114,18 +113,18 @@ private static void createTables() { Objects.requireNonNull(con).prepareStatement(table).executeUpdate(); } - con.prepareStatement("INSERT INTO system_info (system_id, db_version, current_plot_version, description) " + - "VALUES (1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0')").executeUpdate(); + con.prepareStatement("INSERT INTO system_info (system_id, db_version, current_plot_version, description)" + + "SELECT 1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0'" + + "WHERE NOT EXISTS (SELECT 1 FROM system_info);").executeUpdate(); try (ResultSet rs = con.prepareStatement("SELECT COUNT(difficulty_id) FROM plot_difficulty").executeQuery()) { - if (rs.next()) { - if (rs.getInt(1) == 0) { + if (rs.next() && rs.getInt(1) == 0) { con.prepareStatement("INSERT INTO plot_difficulty (difficulty_id, multiplier)" + "VALUES ('EASY', 1.0)," + " ('MEDIUM', 1.5)," + " ('HARD', 2);").executeUpdate(); } - } + } } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while creating á database table"), ex); @@ -198,14 +197,14 @@ private PreparedStatement iterateValues(PreparedStatement ps) throws SQLExceptio } private static class Tables { - private final static List tables; + private static final List tablesSql; public static List getTables() { - return tables; + return tablesSql; } static { - tables = Arrays.asList( + tablesSql = Arrays.asList( // System Info "CREATE TABLE IF NOT EXISTS system_info" + "(" + From b0d2838840c597def62465cb3c66599e64b257df Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 26 Jun 2025 20:49:23 +0200 Subject: [PATCH 119/175] =?UTF-8?q?=F0=9F=94=A5=F0=9F=90=9B=20Remove=20spl?= =?UTF-8?q?it=5Fscore=20column?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../database/providers/ReviewProvider.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index bc542d31..8e417de0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -34,7 +34,10 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.*; public class ReviewProvider { @@ -181,8 +184,8 @@ public PlotReview createReview(Plot plot, ReviewRating rating, int score, UUID r if (!result) return null; // Create Review - String query = "INSERT INTO plot_review (plot_id, rating, score, split_score, reviewed_by) " + - "VALUES (?, ?, ?, ?, ?);"; + String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) " + + "VALUES (?, ?, ?, ?);"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, plot.getID()); @@ -298,16 +301,15 @@ public boolean addReviewToggleCriteria(int reviewId, ToggleCriteria toggle, bool return false; } - public boolean removeCheckedToggleCriteria(int reviewId) { + public void removeCheckedToggleCriteria(int reviewId) { String query = "DELETE FROM review_contains_toggle_criteria WHERE review_id = ?;"; try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, reviewId); - return stmt.executeUpdate() > 0; + stmt.executeUpdate(); } catch (SQLException ex) { Utils.logSqlException(ex); } - return false; } // --- Review Notification --- @@ -323,9 +325,9 @@ public List getReviewNotifications(UUID uuid) { return NOTIFICATIONS.stream().filter(n -> n.getUuid() == uuid).toList(); } - public boolean removeReviewNotification(int reviewId, UUID uuid) { + public void removeReviewNotification(int reviewId, UUID uuid) { Optional notification = getReviewNotification(reviewId, uuid); - if (notification.isEmpty()) return false; + if (notification.isEmpty()) return; String query = "DELETE FROM builder_has_review_notification WHERE review_id = ? AND uuid = ?;"; try (Connection conn = DatabaseConnection.getConnection(); @@ -334,11 +336,9 @@ public boolean removeReviewNotification(int reviewId, UUID uuid) { stmt.setString(2, uuid.toString()); boolean result = stmt.executeUpdate() > 0; if (result) NOTIFICATIONS.remove(notification.get()); - return result; } catch (SQLException ex) { Utils.logSqlException(ex); } - return false; } public void createReviewNotification(int reviewId, UUID uuid) { From 5fa08a0485a34a649b0e23adfa80437394077599 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Fri, 27 Jun 2025 11:06:17 +0200 Subject: [PATCH 120/175] =?UTF-8?q?=F0=9F=90=9B=20Fix=20and=20improve=20de?= =?UTF-8?q?fault=20sql=20statements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- .../core/database/DatabaseConnection.java | 40 +++++++++++++------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java index a7f138a8..fdbc062a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java @@ -109,22 +109,36 @@ private static void createDatabase() throws SQLException { private static void createTables() { try (Connection con = dataSource.getConnection()) { - for (String table : Tables.getTables()) { - Objects.requireNonNull(con).prepareStatement(table).executeUpdate(); - } + try (Statement statement = con.createStatement()) { - con.prepareStatement("INSERT INTO system_info (system_id, db_version, current_plot_version, description)" + - "SELECT 1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0'" + - "WHERE NOT EXISTS (SELECT 1 FROM system_info);").executeUpdate(); - try (ResultSet rs = con.prepareStatement("SELECT COUNT(difficulty_id) FROM plot_difficulty").executeQuery()) { - if (rs.next() && rs.getInt(1) == 0) { - con.prepareStatement("INSERT INTO plot_difficulty (difficulty_id, multiplier)" + - "VALUES ('EASY', 1.0)," + - " ('MEDIUM', 1.5)," + - " ('HARD', 2);").executeUpdate(); - } + for (String table : Tables.getTables()) { + statement.addBatch(table); + } + statement.addBatch("INSERT INTO system_info (system_id, db_version, current_plot_version, description)" + + "SELECT 1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0' FROM DUAL " + + "WHERE NOT EXISTS (SELECT 1 FROM system_info);"); + + statement.addBatch("INSERT INTO review_toggle_criteria (criteria_name, is_optional) " + + "VALUES" + + " ('built_on_outlines',0)," + + " ('correct_amount_windows_doors',0)," + + " ('correct_facade_colour',0)," + + " ('correct_height',0)," + + " ('correct_roof_colour',1)," + + " ('correct_roof_shape',0)," + + " ('correct_window_type',1)," + + " ('windows_blacked_out',0)" + + "ON DUPLICATE KEY UPDATE criteria_name = VALUES(criteria_name);"); + + statement.addBatch("INSERT INTO plot_difficulty (difficulty_id, multiplier)" + + "VALUES ('EASY', 1.0)," + + " ('MEDIUM', 1.5)," + + " ('HARD', 2)" + + "ON DUPLICATE KEY UPDATE difficulty_id = VALUES(difficulty_id);"); + + statement.executeBatch(); } } catch (SQLException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while creating á database table"), ex); From 47edde689ab6e71cf77a59e071af296f921348f8 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 27 Jun 2025 18:15:31 +0200 Subject: [PATCH 121/175] update langlibs dependency --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5f8eab91..4f1dfff4 100644 --- a/pom.xml +++ b/pom.xml @@ -180,7 +180,7 @@ li.cinnazeyy - LangLibs + LangLibs-API 1.5 provided From f2d3279925fe6a4d5cbf980ec3372b865cffa9f4 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 4 Jul 2025 19:06:32 +0200 Subject: [PATCH 122/175] fix undoreview deleting completedSchematic data and abandon not resetting it. --- .../core/system/plot/utils/PlotUtils.java | 2 ++ .../core/system/review/PlotReview.java | 22 ++++++++++++------- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 3ab7c971..6838ce05 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -432,6 +432,8 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { && dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); } + successful = successful && DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!")); }); return true; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index f40b3764..79b47b7a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -27,6 +27,7 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.enums.Slot; import com.alpsbte.plotsystem.utils.enums.Status; import org.jetbrains.annotations.Nullable; @@ -39,7 +40,8 @@ public class PlotReview { private final int score; private final int splitScore; private final UUID reviewedBy; - @Nullable private String feedback; + @Nullable + private String feedback; public PlotReview(int reviewId, int plotId, ReviewRating rating, int score, @Nullable String feedback, UUID reviewedBy) { this(reviewId, DataProvider.PLOT.getPlotById(plotId), rating, score, feedback, reviewedBy); @@ -67,7 +69,7 @@ public int getScore() { return score; } - public int getSplitScore() { return splitScore; } + public int getSplitScore() {return splitScore;} public @Nullable String getFeedback() { return feedback; @@ -96,21 +98,25 @@ public boolean updateFeedback(String feedback) { public boolean undoReview() { // remove owner score and remove plot from slot if (!plot.getPlotOwner().addScore(splitScore == -1 ? -score : -splitScore)) return false; - if (plot.getPlotOwner().getSlotByPlotId(plot.getID()) != null - && !plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plot.getID()), plot.getID())) - return false; + + Slot slot = plot.getPlotOwner().getSlotByPlotId(plot.getID()); // get slot if plot is still in slots (rejected) + if (slot == null) slot = plot.getPlotOwner().getFreeSlot(); // get new slot otherwise (completed) + if (slot == null) return false; + + if (!plot.getPlotOwner().setSlot(slot, plot.getID())) return false; // remove members score and remove plot from slot for (Builder member : plot.getPlotMembers()) { if (!member.addScore(-splitScore)) return false; - if (member.getSlotByPlotId(plot.getID()) != null && !member.setSlot(member.getSlotByPlotId(plot.getID()), plot.getID())) - return false; + + Slot memberSlot = member.getSlotByPlotId(plot.getID()); + if (memberSlot == null) memberSlot = member.getFreeSlot(); + if (memberSlot == null || member.setSlot(memberSlot, plot.getID())) return false; } plot.setStatus(Status.unreviewed); plot.setPasted(false); - DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); return DataProvider.REVIEW.removeReview(reviewId); } } From 6bb6cb593f9055d9e4367197fa4f3aa57813881e Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Fri, 4 Jul 2025 23:28:44 +0200 Subject: [PATCH 123/175] add toggle criteria to pss commands --- .../admin/setup/CMD_Setup_BuildTeam.java | 153 +++++++++- .../commands/admin/setup/CMD_Setup_City.java | 24 +- .../admin/setup/CMD_Setup_ReviewCriteria.java | 261 ++++++++++++++++++ .../database/providers/ReviewProvider.java | 91 ++++++ 4 files changed, 515 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 20813273..87786a62 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.command.CommandSender; @@ -53,6 +54,9 @@ private void register() { registerSubCommand(new CMD_Setup_BuildTeam_SetName(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_AddReviewer(getBaseCommand(), this)); registerSubCommand(new CMD_Setup_BuildTeam_RemoveReviewer(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_BuildTeam_Criteria(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_BuildTeam_AssignCriteria(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_BuildTeam_RemoveCriteria(getBaseCommand(), this)); } @Override @@ -226,7 +230,7 @@ public void onCommand(CommandSender sender, String[] args) { Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); - // Check if build team exits + // Check if build team exists if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; @@ -276,7 +280,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - // Check if build team exits + // Check if build team exists Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); @@ -323,7 +327,7 @@ public CMD_Setup_BuildTeam_RemoveReviewer(BaseCommand baseCommand, SubCommand su public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - // Check if build team exits + // Check if build team exists Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); if (buildTeam.isEmpty()) { @@ -362,4 +366,147 @@ public String getPermission() { return "plotsystem.admin.pss.buildteam.removereviewer"; } } + + public static class CMD_Setup_BuildTeam_Criteria extends SubCommand { + public CMD_Setup_BuildTeam_Criteria(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + List criteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(Integer.parseInt(args[1])); + if (criteria.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no toggle criteria assigned to the build team " + args[1] + " in the database!")); + return; + } + + sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + criteria.size() + " toggle criteria associated to this build team:")); + sender.sendMessage(text("--------------------------", DARK_GRAY)); + for (ToggleCriteria c : criteria) { + sender.sendMessage(text(" » ", DARK_GRAY) + .append(text(c.getCriteriaName() + " (" + (c.isOptional() ? "optional" : "required") + ")"))); + } + sender.sendMessage(text("--------------------------", DARK_GRAY)); + } + + @Override + public String[] getNames() { + return new String[]{"criteria"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"Build-Team-ID"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.buildteam.criteria"; + } + } + + public static class CMD_Setup_BuildTeam_AssignCriteria extends SubCommand { + public CMD_Setup_BuildTeam_AssignCriteria(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + + // Check if build team exists + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + if (buildTeam.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); + return; + } + + // Check if toggle criteria exists + Optional criteria = DataProvider.REVIEW.getToggleCriteria(args[2]); + if (criteria.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Toggle criteria could not be found!")); + return; + } + + boolean successful = DataProvider.REVIEW.assignBuildTeamToggleCriteria(buildTeam.get().getId(), criteria.get()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully assigned criteria '" + criteria.get().getCriteriaName() + "' to build team with ID '" + args[1] + "'!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + } + + @Override + public String[] getNames() { + return new String[]{"assigncriteria"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"Build-Team-ID", "Criteria-Name"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.buildteam.assigncriteria"; + } + } + + public static class CMD_Setup_BuildTeam_RemoveCriteria extends SubCommand { + public CMD_Setup_BuildTeam_RemoveCriteria(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + + // Check if build team exists + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + if (buildTeam.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); + return; + } + + // Check if toggle criteria exists + Optional criteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(buildTeam.get().getId()) + .stream().filter(t -> t.getCriteriaName().equalsIgnoreCase(args[2])).findFirst(); + if (criteria.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Toggle criteria could not be found or is not assigned!")); + return; + } + + boolean successful = DataProvider.REVIEW.removeBuildTeamToggleCriteria(buildTeam.get().getId(), criteria.get()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed criteria '" + criteria.get().getCriteriaName() + "' from build team with ID '" + args[1] + "'!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + } + + @Override + public String[] getNames() { + return new String[]{"removecriteria"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"Build-Team-ID", "Criteria-Name"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.buildteam.removecriteria"; + } + } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 8cec0ba6..b1cbe858 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -173,18 +173,20 @@ public void onCommand(CommandSender sender, String[] args) { } boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, buildTeamId, country.get().getCode(), serverName); - if (added) { - try { - LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".name", cityProjectId); - LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".description", ""); - } catch (Exception e) { - PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for City Project " + cityProjectId + "!").color(RED), e); - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for City Project " + cityProjectId + "!")); - } - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be the ID of the City & no description will be present!")); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); + if (!added) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); + return; + } + + try { + LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".name", cityProjectId); + LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".description", ""); + } catch (Exception e) { + PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for City Project " + cityProjectId + "!").color(RED), e); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for City Project " + cityProjectId + "!")); } - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be the ID of the City & no description will be present!")); + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java new file mode 100644 index 00000000..283a3153 --- /dev/null +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -0,0 +1,261 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.alpsbte.plotsystem.commands.admin.setup; + +import com.alpsbte.plotsystem.PlotSystem; +import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.commands.SubCommand; +import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; +import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import org.bukkit.command.CommandSender; + +import java.util.List; +import java.util.Optional; + +import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.RED; + +public class CMD_Setup_ReviewCriteria extends SubCommand { + public CMD_Setup_ReviewCriteria(BaseCommand baseCommand) { + super(baseCommand); + registerSubCommand(new CMD_Setup_ReviewCriteria_List(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_ReviewCriteria_Add(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_ReviewCriteria_Remove(getBaseCommand(), this)); + registerSubCommand(new CMD_Setup_ReviewCriteria_SetOptional(getBaseCommand(), this)); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + sendInfo(sender); + } + + @Override + public String[] getNames() { + return new String[]{"review"}; + } + + @Override + public String getDescription() { + return "Configure review criteria"; + } + + @Override + public String[] getParameter() { + return new String[0]; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.review"; + } + + public static class CMD_Setup_ReviewCriteria_List extends SubCommand { + + public CMD_Setup_ReviewCriteria_List(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + List criteria = DataProvider.REVIEW.getAllToggleCriteria(); + if (criteria.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no toggle criteria registered in the database!")); + return; + } + + sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + criteria.size() + " toggle criteria registered in the database:")); + sender.sendMessage(text("--------------------------", DARK_GRAY)); + for (ToggleCriteria c : criteria) { + sender.sendMessage(text(" » ", DARK_GRAY) + .append(text(c.getCriteriaName() + " (" + (c.isOptional() ? "optional" : "required") + ")"))); + } + sender.sendMessage(text("--------------------------", DARK_GRAY)); + } + + @Override + public String[] getNames() { + return new String[]{"list"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[0]; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.review.list"; + } + } + + public static class CMD_Setup_ReviewCriteria_Add extends SubCommand { + public CMD_Setup_ReviewCriteria_Add(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 2) {sendInfo(sender); return;} + + String name = args[1]; + if (name.length() > 255) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Toggle criteria name cannot be longer than 255 characters!")); + return; + } + + boolean isOptional = args[2].equalsIgnoreCase("true"); + + boolean successful = DataProvider.REVIEW.addToggleCriteria(name, isOptional); + if (!successful) sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else { + try { + LangUtil.getInstance().setDynamicKey(LangPaths.Database.TOGGLE_CRITERIA + "." + name, name.replace("-", " ").replace("_", " ")); + } catch (Exception e) { + PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for Toggle Criteria " + name + "!").color(RED), e); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for Toggle Criteria " + name + "!")); + } + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added toggle criteria with name '" + name + "'!")); + } + } + + @Override + public String[] getNames() { + return new String[]{"add"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"Name","Is-Optional"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.review.add"; + } + } + + public static class CMD_Setup_ReviewCriteria_Remove extends SubCommand { + public CMD_Setup_ReviewCriteria_Remove(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 1) {sendInfo(sender); return;} + + // Check if criteria exists + Optional criteria = DataProvider.REVIEW.getToggleCriteria(args[1]); + if (criteria.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any toggle criteria with name " + args[1] + "!")); + sendInfo(sender); + return; + } + + boolean successful = DataProvider.REVIEW.removeToggleCriteria(criteria.get().getCriteriaName()); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + } + + @Override + public String[] getNames() { + return new String[]{"remove"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"Name"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.review.remove"; + } + } + + public static class CMD_Setup_ReviewCriteria_SetOptional extends SubCommand { + public CMD_Setup_ReviewCriteria_SetOptional(BaseCommand baseCommand, SubCommand subCommand) { + super(baseCommand, subCommand); + } + + @Override + public void onCommand(CommandSender sender, String[] args) { + if (args.length <= 2) {sendInfo(sender); return;} + + // Check if criteria exits + Optional criteria = DataProvider.REVIEW.getToggleCriteria(args[1]); + if (criteria.isEmpty()) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Toggle criteria could not be found!")); + return; + } + + String name = args[1]; + boolean isOptional = args[2].equalsIgnoreCase("true"); + + boolean successful = DataProvider.REVIEW.setToggleCriteriaOptional(name, isOptional); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed optionality of toggle criteria with name " + name + " to '" + isOptional + "'!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + } + + @Override + public String[] getNames() { + return new String[]{"setoptional"}; + } + + @Override + public String getDescription() { + return null; + } + + @Override + public String[] getParameter() { + return new String[]{"Name", "Is-Optional"}; + } + + @Override + public String getPermission() { + return "plotsystem.admin.pss.buildteam.setoptional"; + } + } + +} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 8e417de0..35a87616 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -263,10 +263,101 @@ public Optional getToggleCriteria(String criteriaName) { return TOGGLE_CRITERIA.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst(); } + public boolean addToggleCriteria(String criteriaName, boolean isOptional) { + Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); + if (criteria.isPresent()) return false; + + String query = "INSERT INTO review_toggle_criteria (criteria_name, is_optional) " + + "VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, criteriaName); + stmt.setBoolean(2, isOptional); + boolean successful = stmt.executeUpdate() > 0; + if (successful) TOGGLE_CRITERIA.add(new ToggleCriteria(criteriaName, isOptional)); + return successful; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + + public boolean removeToggleCriteria(String criteriaName) { + Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); + if (criteria.isEmpty()) return false; + + String query = "DELETE FROM review_toggle_criteria WHERE criteria_name = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, criteriaName); + boolean successful = stmt.executeUpdate() > 0; + if (successful) TOGGLE_CRITERIA.remove(criteria.get()); + return successful; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + + public boolean setToggleCriteriaOptional(String criteriaName, boolean isOptional) { + Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); + if (criteria.isEmpty()) return false; + + String query = "UPDATE review_toggle_criteria SET is_optional = ? WHERE criteria_name = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setBoolean(1, isOptional); + stmt.setString(1, criteriaName); + return stmt.executeUpdate() > 0; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + + public List getAllToggleCriteria() {return TOGGLE_CRITERIA.stream().toList();} + public List getBuildTeamToggleCriteria(int buildTeamId) { return BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); } + public boolean assignBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { + Optional existingCriteria = getBuildTeamToggleCriteria(buildTeamId).stream().filter(t -> + t.getCriteriaName().equals(criteria.getCriteriaName())).findFirst(); + if (existingCriteria.isPresent()) return false; + String query = "INSERT INTO build_team_uses_toggle_criteria (build_team_id, criteria_name) " + + "VALUES (?, ?);"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, buildTeamId); + stmt.setString(2, criteria.getCriteriaName()); + boolean successful = stmt.executeUpdate() > 0; + if (successful) BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(buildTeamId, criteria)); + return successful; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + + public boolean removeBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { + Optional existingCriteria = BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(btc -> + btc.getBuildTeamId() == buildTeamId && btc.getCriteria().getCriteriaName().equals(criteria.getCriteriaName())).findFirst(); + if (existingCriteria.isEmpty()) return false; + String query = "DELETE FROM build_team_uses_toggle_criteria WHERE build_team_id = ? AND criteria_name = ?;"; + try (Connection conn = DatabaseConnection.getConnection(); + PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, buildTeamId); + stmt.setString(2, criteria.getCriteriaName()); + boolean successful = stmt.executeUpdate() > 0; + if (successful) BUILD_TEAM_TOGGLE_CRITERIA.remove(existingCriteria.get()); + return successful; + } catch (SQLException ex) { + Utils.logSqlException(ex); + } + return false; + } + public Map getReviewToggleCriteria(int reviewId) { HashMap toggleCriteriaList = new HashMap<>(); String query = "SELECT criteria_name, is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; From 50498c4398f31e6642797e9fd39adb9425c2dfcb Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 5 Jul 2025 21:07:04 +0200 Subject: [PATCH 124/175] check if continent is null --- .../plotsystem/commands/admin/setup/CMD_Setup_City.java | 2 +- .../plotsystem/commands/admin/setup/CMD_Setup_Country.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index b1cbe858..477a7d41 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -140,7 +140,7 @@ public CMD_Setup_City_Add(BaseCommand baseCommand, SubCommand subCommand) { public void onCommand(CommandSender sender, String[] args) { if (args.length <= 4) {sendInfo(sender); return;} - String cityProjectId = args[1]; + String cityProjectId = args[1].toLowerCase(); String countryCode = args[2]; Optional country = DataProvider.COUNTRY.getCountryByCode(countryCode); if (country.isEmpty()) { diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 3d131f80..63fd3ee5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -147,6 +147,11 @@ public void onCommand(CommandSender sender, String[] args) { return; } + if (continent == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Unknown continent! " + Arrays.toString(Continent.values()))); + return; + } + String material = args[3]; String customModelData = args.length > 4 ? args[4] : null; From 18714f9d5dba84dd209d1496b1821738d20903bf Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 5 Jul 2025 22:55:47 +0200 Subject: [PATCH 125/175] remove dynamic language key setting on pss commands due to breaking issues. (will reimplement later, once configurate issues are resolved) --- .../commands/admin/setup/CMD_Setup_City.java | 10 +--------- .../commands/admin/setup/CMD_Setup_Country.java | 13 +------------ .../admin/setup/CMD_Setup_ReviewCriteria.java | 10 +--------- 3 files changed, 3 insertions(+), 30 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 477a7d41..3608b264 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -35,6 +35,7 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.CommandSender; +import org.yaml.snakeyaml.DumperOptions; import java.util.List; import java.util.Optional; @@ -177,15 +178,6 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); return; } - - try { - LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".name", cityProjectId); - LangUtil.getInstance().setDynamicKey(LangPaths.Database.CITY_PROJECT + "." + cityProjectId + ".description", ""); - } catch (Exception e) { - PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for City Project " + cityProjectId + "!").color(RED), e); - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for City Project " + cityProjectId + "!")); - } - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be the ID of the City & no description will be present!")); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 63fd3ee5..5ec73d8a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -156,18 +156,7 @@ public void onCommand(CommandSender sender, String[] args) { String customModelData = args.length > 4 ? args[4] : null; boolean successful = DataProvider.COUNTRY.addCountry(code, continent, material, customModelData); - if (successful) - { - try { - LangUtil.getInstance().setDynamicKey(LangPaths.Database.COUNTRY + "." + code + ".name", code); - } catch (Exception e) { - PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for country " + code + "!").color(RED), e); - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for country " + code + "!")); - } - - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + code + " language config setting, otherwise the name will be the ID of the Country & no description will be present!")); - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); - } + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java index 283a3153..630c49b4 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -138,15 +138,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = DataProvider.REVIEW.addToggleCriteria(name, isOptional); if (!successful) sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - else { - try { - LangUtil.getInstance().setDynamicKey(LangPaths.Database.TOGGLE_CRITERIA + "." + name, name.replace("-", " ").replace("_", " ")); - } catch (Exception e) { - PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while saving the language file for Toggle Criteria " + name + "!").color(RED), e); - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while saving the language file for Toggle Criteria " + name + "!")); - } - sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added toggle criteria with name '" + name + "'!")); - } + else sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added toggle criteria with name '" + name + "'!")); } @Override From b555c41351bea90f5a16992d2cc857a1f972cd9f Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 6 Jul 2025 17:24:44 +0200 Subject: [PATCH 126/175] add back reminders to change language file after adding city,country or toggle criteria --- .../commands/admin/setup/CMD_Setup_City.java | 1 + .../commands/admin/setup/CMD_Setup_Country.java | 8 ++++++-- .../commands/admin/setup/CMD_Setup_ReviewCriteria.java | 10 ++++++++-- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 3608b264..5db8db3f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -178,6 +178,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); return; } + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be the ID of the City & no description will be present!")); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 5ec73d8a..118c1cab 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -156,8 +156,12 @@ public void onCommand(CommandSender sender, String[] args) { String customModelData = args.length > 4 ? args[4] : null; boolean successful = DataProvider.COUNTRY.addCountry(code, continent, material, customModelData); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + if (!successful) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + return; + } + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.COUNTRY + "." + code + " language config setting, otherwise the name will be the ID of the Country & no description will be present!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java index 630c49b4..f90ac7b2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -137,8 +137,14 @@ public void onCommand(CommandSender sender, String[] args) { boolean isOptional = args[2].equalsIgnoreCase("true"); boolean successful = DataProvider.REVIEW.addToggleCriteria(name, isOptional); - if (!successful) sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - else sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added toggle criteria with name '" + name + "'!")); + if (!successful) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + return; + } + + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.TOGGLE_CRITERIA + "." + name + " language config setting, otherwise the name will be the ID of the Toggle Criteria & no description will be present!")); + sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added toggle criteria with name '" + name + "'!")); } @Override From 7648ebad2617f54a2ad5822d25cacaf9ba3b015a Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sun, 6 Jul 2025 17:38:07 +0200 Subject: [PATCH 127/175] =?UTF-8?q?=E2=9C=A8=20=E2=99=BB=EF=B8=8F=20Improv?= =?UTF-8?q?e=20database=20handling=20(#173)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ ♻️ Improve database handling Use the alpslib-io package so our plugin will share it. Also use just a plain sql file for the initialisation. Removes much overhead & the additional properties will improve performance. The (bad) StatementBuilder logic was also removed. Now it should use proper pooling. ♻️ Use new utility functions & close connections correctly Signed-off-by: Zoriot Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- pom.xml | 2 +- .../com/alpsbte/plotsystem/PlotSystem.java | 20 +- .../commands/admin/CMD_PReload.java | 13 +- .../commands/review/CMD_EditFeedback.java | 6 +- .../commands/review/CMD_EditPlot.java | 12 +- .../commands/review/CMD_Review.java | 6 +- .../commands/review/CMD_UndoReview.java | 6 +- .../core/database/DatabaseConnection.java | 429 ------------------ .../database/providers/BuildTeamProvider.java | 164 +++---- .../database/providers/BuilderProvider.java | 275 +++++------ .../providers/CityProjectProvider.java | 136 ++---- .../database/providers/CountryProvider.java | 73 ++- .../providers/DifficultyProvider.java | 58 +-- .../core/database/providers/PlotProvider.java | 393 ++++++---------- .../database/providers/ReviewProvider.java | 385 ++++++---------- .../database/providers/ServerProvider.java | 54 +-- .../providers/TutorialPlotProvider.java | 108 ++--- .../plotsystem/core/system/plot/Plot.java | 28 +- .../com/alpsbte/plotsystem/utils/Utils.java | 19 + .../plotsystem/utils/io/ConfigPaths.java | 14 +- src/main/resources/DATABASE.sql | 276 +++++++++++ src/main/resources/config.yml | 7 +- 22 files changed, 990 insertions(+), 1494 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java create mode 100644 src/main/resources/DATABASE.sql diff --git a/pom.xml b/pom.xml index 9b87b58e..77e855ea 100644 --- a/pom.xml +++ b/pom.xml @@ -131,7 +131,7 @@ com.alpsbte.alpslib alpslib-io - 1.0.38 + 1.2.0 com.alpsbte.alpslib diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index ec10248a..cacd4c3b 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -27,11 +27,12 @@ import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.alpslib.io.YamlFileFactory; import com.alpsbte.alpslib.io.config.ConfigNotImplementedException; +import com.alpsbte.alpslib.io.database.DatabaseConfigPaths; +import com.alpsbte.alpslib.io.database.DatabaseConnection; import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.alpslib.utils.head.AlpsHeadEventListener; import com.alpsbte.plotsystem.commands.CommandManager; import com.alpsbte.plotsystem.core.EventListener; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.holograms.HologramRegister; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -46,6 +47,7 @@ import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.google.common.io.CharStreams; import de.oliver.fancynpcs.api.FancyNpcsPlugin; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; @@ -54,7 +56,10 @@ import org.ipvp.canvas.MenuFunctionListener; import org.jetbrains.annotations.NotNull; +import java.io.IOException; +import java.sql.SQLException; import java.util.Collections; +import java.util.Objects; import java.util.UUID; import static net.kyori.adventure.text.Component.text; @@ -95,7 +100,7 @@ public void onEnable() { // Initialize database connection try { - DatabaseConnection.InitializeDatabase(); + initDatabase(); getComponentLogger().info(successPrefix.append(text("Successfully initialized database connection."))); } catch (Exception ex) { getComponentLogger().error(errorPrefix.append(text("Could not initialize database connection.")), ex); @@ -159,6 +164,9 @@ public void onDisable() { DecentHologramDisplay.activeDisplays.forEach(DecentHologramDisplay::delete); } else { + // Close database connection + DatabaseConnection.shutdown(); + // Unload plots for (UUID player : PlotUtils.Cache.getCachedInProgressPlots().keySet()) { Builder builder = Builder.byUUID(player); @@ -198,4 +206,12 @@ public void saveConfig() { public static PlotSystem getPlugin() { return plugin; } + + public void initDatabase() throws IOException, SQLException, ClassNotFoundException { + DatabaseConnection.initializeDatabase(DatabaseConfigPaths.getConfig(getConfig()), true); + var initScript = CharStreams.toString(Objects.requireNonNull(getTextResource("DATABASE.sql"))); + try (var con = DatabaseConnection.getConnection(); var s = con.createStatement()) { + s.execute(initScript); + } + } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java index 4c09f0b1..1ef9ed0a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -27,7 +27,6 @@ import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.holograms.HologramConfiguration; import com.alpsbte.plotsystem.core.holograms.HologramRegister; import com.alpsbte.plotsystem.utils.Utils; @@ -41,24 +40,24 @@ public class CMD_PReload extends BaseCommand { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { + PlotSystem plugin = PlotSystem.getPlugin(); if (!sender.hasPermission(getPermission())) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("You don't have permission to use this command!")); return true; } try { - PlotSystem.getPlugin().reloadConfig(); + plugin.reloadConfig(); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully reloaded config!")); DecentHologramDisplay.activeDisplays.forEach(leaderboard -> leaderboard.setLocation(HologramRegister .getLocation((HologramConfiguration) leaderboard))); HologramRegister.reload(); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully reloaded leaderboards!")); - - DatabaseConnection.InitializeDatabase(); + plugin.initDatabase(); } catch (Exception ex) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); + plugin.getComponentLogger().error(text("An error occurred!"), ex); } return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index d750c3c2..1db181db 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -81,7 +81,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { + if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_SEND_FEEDBACK))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 57f16bdc..8a51b596 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -28,13 +28,13 @@ import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.core.database.DataProvider; +import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; +import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.alpsbte.plotsystem.core.system.Builder; -import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -97,7 +97,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N Builder builder = Builder.byUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { + if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 97f257d2..6751eaa1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -83,7 +83,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { + if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index 1344530f..d5a9a90c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -82,7 +82,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (!DataProvider.BUILDER.canReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { + if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java b/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java deleted file mode 100644 index fdbc062a..00000000 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DatabaseConnection.java +++ /dev/null @@ -1,429 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -package com.alpsbte.plotsystem.core.database; - -import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.bukkit.configuration.file.FileConfiguration; - -import java.sql.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import static net.kyori.adventure.text.Component.text; - -public class DatabaseConnection { - - private static final HikariConfig config = new HikariConfig(); - private static HikariDataSource dataSource; - - private static String URL; - private static String name; - private static String username; - private static String password; - - private static int connectionClosed, connectionOpened; - - public static void InitializeDatabase() throws ClassNotFoundException, SQLException { - Class.forName("org.mariadb.jdbc.Driver"); - - FileConfiguration configFile = PlotSystem.getPlugin().getConfig(); - URL = configFile.getString(ConfigPaths.DATABASE_URL); - name = configFile.getString(ConfigPaths.DATABASE_NAME); - username = configFile.getString(ConfigPaths.DATABASE_USERNAME); - password = configFile.getString(ConfigPaths.DATABASE_PASSWORD); - - createDatabase(); - - config.setJdbcUrl(URL + name); - config.setUsername(username); - config.setPassword(password); - config.addDataSourceProperty("cachePrepStmts", "true"); - config.addDataSourceProperty("prepStmtCacheSize", "250"); - config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); - - dataSource = new HikariDataSource(config); - - createTables(); - } - - public static Connection getConnection() throws SQLException { - return dataSource.getConnection(); - } - - public static StatementBuilder createStatement(String sql) { - return new StatementBuilder(sql); - } - - public static void closeResultSet(ResultSet resultSet) throws SQLException { - if (resultSet.isClosed() - && resultSet.getStatement().isClosed() - && resultSet.getStatement().getConnection().isClosed()) - return; - - resultSet.close(); - resultSet.getStatement().close(); - resultSet.getStatement().getConnection().close(); - - connectionClosed++; - - if (connectionOpened > connectionClosed + 5) { - PlotSystem.getPlugin().getComponentLogger().error(text("There are multiple database connections opened. Please report this issue.")); - PlotSystem.getPlugin().getComponentLogger().error(text("Connections Open: " + (connectionOpened - connectionClosed))); - } - } - - private static void createDatabase() throws SQLException { - try (Connection con = DriverManager.getConnection(URL, username, password)) { - try (Statement statement = con.createStatement()) { - statement.executeUpdate("CREATE DATABASE IF NOT EXISTS `" + name + "`"); - } - } - } - - private static void createTables() { - try (Connection con = dataSource.getConnection()) { - try (Statement statement = con.createStatement()) { - - - for (String table : Tables.getTables()) { - statement.addBatch(table); - } - - statement.addBatch("INSERT INTO system_info (system_id, db_version, current_plot_version, description)" + - "SELECT 1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0' FROM DUAL " + - "WHERE NOT EXISTS (SELECT 1 FROM system_info);"); - - statement.addBatch("INSERT INTO review_toggle_criteria (criteria_name, is_optional) " + - "VALUES" + - " ('built_on_outlines',0)," + - " ('correct_amount_windows_doors',0)," + - " ('correct_facade_colour',0)," + - " ('correct_height',0)," + - " ('correct_roof_colour',1)," + - " ('correct_roof_shape',0)," + - " ('correct_window_type',1)," + - " ('windows_blacked_out',0)" + - "ON DUPLICATE KEY UPDATE criteria_name = VALUES(criteria_name);"); - - statement.addBatch("INSERT INTO plot_difficulty (difficulty_id, multiplier)" + - "VALUES ('EASY', 1.0)," + - " ('MEDIUM', 1.5)," + - " ('HARD', 2)" + - "ON DUPLICATE KEY UPDATE difficulty_id = VALUES(difficulty_id);"); - - statement.executeBatch(); - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while creating á database table"), ex); - } - } - - /** - * Returns a missing auto increment id - * - * @param table in the database - * @return smallest missing auto increment id in the table - */ - public static int getTableID(String table) { - try { - String query = "SELECT id + 1 available_id FROM $table t WHERE NOT EXISTS (SELECT * FROM $table WHERE $table.id = t.id + 1) ORDER BY id LIMIT 1" - .replace("$table", table); - try (ResultSet rs = DatabaseConnection.createStatement(query).executeQuery()) { - if (rs.next()) { - int i = rs.getInt(1); - DatabaseConnection.closeResultSet(rs); - return i; - } - - DatabaseConnection.closeResultSet(rs); - return 1; - } - } catch (SQLException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); - return 1; - } - } - - public static class StatementBuilder { - private final String sql; - private final List values = new ArrayList<>(); - - public StatementBuilder(String sql) { - this.sql = sql; - } - - public StatementBuilder setValue(Object value) { - values.add(value instanceof Boolean ? ((boolean) value ? 1 : 0) : value); - return this; - } - - public ResultSet executeQuery() throws SQLException { - Connection con = dataSource.getConnection(); - PreparedStatement ps = Objects.requireNonNull(con).prepareStatement(sql); - ResultSet rs = iterateValues(ps).executeQuery(); - - connectionOpened++; - - return rs; - } - - public void executeUpdate() throws SQLException { - try (Connection con = dataSource.getConnection()) { - try (PreparedStatement ps = Objects.requireNonNull(con).prepareStatement(sql)) { - iterateValues(ps).executeUpdate(); - } - } - } - - private PreparedStatement iterateValues(PreparedStatement ps) throws SQLException { - for (int i = 0; i < values.size(); i++) { - ps.setObject(i + 1, values.get(i)); - } - return ps; - } - } - - private static class Tables { - private static final List tablesSql; - - public static List getTables() { - return tablesSql; - } - - static { - tablesSql = Arrays.asList( - // System Info - "CREATE TABLE IF NOT EXISTS system_info" + - "(" + - " system_id INT NOT NULL AUTO_INCREMENT," + - " db_version DOUBLE NOT NULL," + - " current_plot_version DOUBLE NOT NULL," + - " last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP," + - " description TEXT NULL," + - " PRIMARY KEY (system_id)" + - ");", - - // Build Team - "CREATE TABLE IF NOT EXISTS build_team" + - "(" + - " build_team_id INT NOT NULL AUTO_INCREMENT," + - " name VARCHAR(255) NOT NULL," + - " api_key VARCHAR(255) NULL UNIQUE," + - " api_create_date DATETIME NULL," + - " PRIMARY KEY (build_team_id)" + - ");", - - // Server - "CREATE TABLE IF NOT EXISTS server" + - "(" + - " build_team_id INT NOT NULL," + - " server_name VARCHAR(255) NOT NULL UNIQUE," + - " PRIMARY KEY (build_team_id, server_name)," + - " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + - " ON DELETE RESTRICT ON UPDATE CASCADE" + - ");", - - // Countries - "CREATE TABLE IF NOT EXISTS country" + - "(" + - " country_code VARCHAR(2) NOT NULL," + - " continent ENUM ('EU','AS','AF','OC','SA','NA') NOT NULL," + - " material VARCHAR(255) NOT NULL," + - " custom_model_data VARCHAR(255) NULL," + - " PRIMARY KEY (country_code)" + - ");", - - // City Projects - "CREATE TABLE IF NOT EXISTS city_project" + - "(" + - " city_project_id VARCHAR(255) NOT NULL," + - " build_team_id INT NOT NULL," + - " country_code VARCHAR(2) NOT NULL," + - " server_name VARCHAR(255) NOT NULL," + - " is_visible BOOLEAN NOT NULL DEFAULT 1," + - " PRIMARY KEY (city_project_id)," + - " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + - " ON DELETE RESTRICT ON UPDATE CASCADE," + - " FOREIGN KEY (country_code) REFERENCES country (country_code)" + - " ON DELETE RESTRICT ON UPDATE CASCADE," + - " FOREIGN KEY (server_name) REFERENCES server (server_name)" + - " ON DELETE RESTRICT ON UPDATE CASCADE" + - ");", - - // Builders - "CREATE TABLE IF NOT EXISTS builder" + - "(" + - " uuid VARCHAR(36) NOT NULL," + - " name VARCHAR(255) NOT NULL UNIQUE," + - " score INT NOT NULL DEFAULT 0," + - " first_slot INT NULL," + - " second_slot INT NULL," + - " third_slot INT NULL," + - " plot_type INT NOT NULL," + - " PRIMARY KEY (uuid)" + - ");", - - // Difficulty - "CREATE TABLE IF NOT EXISTS plot_difficulty" + - "(" + - " difficulty_id VARCHAR(255) NOT NULL," + - " multiplier DECIMAL(4, 2) DEFAULT 1.00," + - " score_requirement INT NOT NULL DEFAULT 0," + - " PRIMARY KEY (difficulty_id)," + - " CHECK ( multiplier > 0 )," + - " CHECK ( score_requirement >= 0 )" + - ");", - - // Plot - "CREATE TABLE IF NOT EXISTS plot" + - "(" + - " plot_id INT NOT NULL AUTO_INCREMENT," + - " city_project_id VARCHAR(255) NOT NULL," + - " difficulty_id VARCHAR(255) NOT NULL," + - " owner_uuid VARCHAR(36) NULL," + - " status ENUM ('unclaimed','unfinished','unreviewed','completed') NOT NULL DEFAULT 'unclaimed'," + - " outline_bounds TEXT NOT NULL," + - " initial_schematic MEDIUMBLOB NOT NULL," + - " complete_schematic MEDIUMBLOB NULL," + - " last_activity_date DATETIME NULL," + - " is_pasted BOOLEAN NOT NULL DEFAULT 0," + - " mc_version VARCHAR(8) NULL," + - " plot_version DOUBLE NOT NULL," + - " plot_type INT NULL," + - " created_by VARCHAR(36) NOT NULL," + - " create_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + - " PRIMARY KEY (plot_id)," + - " FOREIGN KEY (city_project_id) REFERENCES city_project (city_project_id)" + - " ON DELETE RESTRICT ON UPDATE CASCADE," + - " FOREIGN KEY (difficulty_id) REFERENCES plot_difficulty (difficulty_id)" + - " ON DELETE RESTRICT ON UPDATE CASCADE," + - " FOREIGN KEY (owner_uuid) REFERENCES builder (uuid)" + - " ON DELETE RESTRICT ON UPDATE CASCADE" + - ");", - - // Tutorial - "CREATE TABLE IF NOT EXISTS tutorial" + - "(" + - " tutorial_id INT NOT NULL," + - " uuid VARCHAR(36) NOT NULL," + - " stage_id INT NOT NULL DEFAULT 0," + - " is_complete BOOLEAN NOT NULL DEFAULT 0," + - " first_stage_start_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + - " last_stage_complete_date DATETIME NULL," + - " PRIMARY KEY (tutorial_id, uuid)" + - ");", - - // Review - "CREATE TABLE IF NOT EXISTS plot_review" + - "(" + - " review_id INT NOT NULL AUTO_INCREMENT," + - " plot_id INT NOT NULL," + - " rating VARCHAR(7) NOT NULL," + - " score INT NOT NULL DEFAULT 0," + - " feedback VARCHAR(256) NULL," + - " reviewed_by VARCHAR(36) NOT NULL," + - " review_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP," + - " PRIMARY KEY (review_id)," + - " FOREIGN KEY (plot_id) REFERENCES plot (plot_id)" + - " ON DELETE CASCADE ON UPDATE CASCADE" + - ");", - - // Toggle Criteria - "CREATE TABLE IF NOT EXISTS review_toggle_criteria" + - "(" + - " criteria_name VARCHAR(255) NOT NULL," + - " is_optional BOOLEAN NOT NULL," + - " PRIMARY KEY (criteria_name)" + - ");", - - // Build team uses toggle criteria - "CREATE TABLE IF NOT EXISTS build_team_uses_toggle_criteria" + - "(" + - " build_team_id INT NOT NULL," + - " criteria_name VARCHAR(255) NOT NULL," + - " PRIMARY KEY (build_team_id, criteria_name)," + - " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + - " ON DELETE CASCADE ON UPDATE CASCADE," + - " FOREIGN KEY (criteria_name) REFERENCES review_toggle_criteria (criteria_name)" + - " ON DELETE CASCADE ON UPDATE CASCADE" + - ");", - - // Review contains toggle criteria - "CREATE TABLE IF NOT EXISTS review_contains_toggle_criteria" + - "(" + - " review_id INT NOT NULL," + - " criteria_name VARCHAR(255) NOT NULL," + - " is_checked BOOLEAN NOT NULL," + - " PRIMARY KEY (review_id, criteria_name)," + - " FOREIGN KEY (review_id) REFERENCES plot_review (review_id)" + - " ON DELETE CASCADE ON UPDATE CASCADE," + - " FOREIGN KEY (criteria_name) REFERENCES review_toggle_criteria (criteria_name)" + - " ON DELETE CASCADE ON UPDATE CASCADE" + - ");", - - // Build team has reviewer - "CREATE TABLE IF NOT EXISTS build_team_has_reviewer" + - "(" + - " build_team_id INT NOT NULL," + - " uuid VARCHAR(36) NOT NULL," + - " PRIMARY KEY (build_team_id, uuid)," + - " FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id)" + - " ON DELETE CASCADE ON UPDATE CASCADE," + - " FOREIGN KEY (uuid) REFERENCES builder (uuid)" + - " ON DELETE CASCADE ON UPDATE CASCADE" + - ");", - - // Builder is plot member - "CREATE TABLE IF NOT EXISTS builder_is_plot_member" + - "(" + - " plot_id INT NOT NULL," + - " uuid VARCHAR(36) NOT NULL," + - " PRIMARY KEY (plot_id, uuid)," + - " FOREIGN KEY (plot_id) REFERENCES plot (plot_id)" + - " ON DELETE CASCADE ON UPDATE CASCADE," + - " FOREIGN KEY (uuid) REFERENCES builder (uuid)" + - " ON DELETE CASCADE ON UPDATE CASCADE" + - ");", - - // Builder has review notification - "CREATE TABLE IF NOT EXISTS builder_has_review_notification" + - "(" + - " review_id INT NOT NULL," + - " uuid VARCHAR(36) NOT NULL," + - " PRIMARY KEY (review_id, uuid)," + - " FOREIGN KEY (review_id) REFERENCES plot_review (review_id)" + - " ON DELETE CASCADE ON UPDATE CASCADE," + - " FOREIGN KEY (uuid) REFERENCES builder (uuid)" + - " ON DELETE CASCADE ON UPDATE CASCADE" + - ");" - ); - } - } -} diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index c4b34985..5935a4b6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,17 +24,14 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.system.BuildTeam; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; import org.jetbrains.annotations.NotNull; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -47,22 +44,17 @@ public class BuildTeamProvider { public BuildTeamProvider(BuilderProvider builderProvider, CityProjectProvider cityProjectProvider) { this.cityProjectProvider = cityProjectProvider; + String qBuildTeams = "SELECT build_team_id, name FROM build_team;"; // cache all build teams - String query = "SELECT build_team_id, name FROM build_team;"; - try (Connection connection = DatabaseConnection.getConnection(); - PreparedStatement stmt = connection.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - int buildTeamId = rs.getInt(1); - - List cityProjects = cityProjectProvider.getCityProjectsByBuildTeam(buildTeamId); - List reviewers = builderProvider.getReviewersByBuildTeam(buildTeamId); - BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), cityProjects, reviewers)); - } + Utils.handleSqlException(() -> SqlHelper.runQuery(qBuildTeams, ps -> { + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + int buildTeamId = rs.getInt(1); + List cityProjects = cityProjectProvider.getCityProjectsByBuildTeam(buildTeamId); + List reviewers = builderProvider.getReviewersByBuildTeam(buildTeamId); + BUILD_TEAMS.add(new BuildTeam(buildTeamId, rs.getString(2), cityProjects, reviewers)); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); } public Optional getBuildTeam(int id) { @@ -70,24 +62,24 @@ public Optional getBuildTeam(int id) { } public List getBuildTeamsByReviewer(@NotNull UUID reviewerUUID) { - List buildTeams = new ArrayList<>(); - - String query = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, reviewerUUID.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - Optional buildTeam = getBuildTeam(rs.getInt(1)); - if (buildTeam.isEmpty()) continue; - buildTeams.add(buildTeam.get()); - } + var l = BUILD_TEAMS.stream() + .filter(b -> b.getReviewers().stream() + .anyMatch(r -> r.getUUID().equals(reviewerUUID))) + .toList(); + if (!l.isEmpty()) return l; + + String qIdByUuid = "SELECT build_team_id FROM build_team_has_reviewer WHERE uuid = ?;"; + return Utils.handleSqlException(new ArrayList<>(), () -> SqlHelper.runQuery(qIdByUuid, ps -> { + ps.setString(1, reviewerUUID.toString()); + ResultSet rs = ps.executeQuery(); + List buildTeams = new ArrayList<>(); + while (rs.next()) { + Optional buildTeam = getBuildTeam(rs.getInt(1)); + if (buildTeam.isEmpty()) continue; + buildTeams.add(buildTeam.get()); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return buildTeams; + return buildTeams; + })); } public List getBuildTeams() { @@ -95,88 +87,66 @@ public List getBuildTeams() { } public boolean addBuildTeam(String name) { - boolean result = false; if (BUILD_TEAMS.stream().anyMatch(b -> b.getName().equals(name))) return false; - String query = "INSERT INTO build_team (name) VALUES (?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, name); - result = stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - - if (result) { - String resultQuery = "SELECT build_team_id FROM build_team WHERE name = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(resultQuery)) { - stmt.setString(1, name); - try (ResultSet rs = stmt.executeQuery()) { + String qInsert = "INSERT INTO build_team (name) VALUES (?);"; + String qByName = "SELECT build_team_id FROM build_team WHERE name = ?;"; + // get the last inserted build team id + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { + ps.setString(1, name); + boolean result = ps.executeUpdate() > 0; + + if (result) { + Utils.handleSqlException(() -> SqlHelper.runQuery(qByName, ps.getConnection(), ps2 -> { + ps2.setString(1, name); + ResultSet rs = ps2.executeQuery(); rs.next(); // get the last inserted build team id BUILD_TEAMS.add(new BuildTeam(rs.getInt(1), name)); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); + return null; // no need to return anything + })); } - } - return result; + return result; + }))); } public boolean removeBuildTeam(int id) { Optional cachedBuildTeam = getBuildTeam(id); if (cachedBuildTeam.isEmpty()) return false; - String query = "DELETE FROM build_team WHERE build_team_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, id); - boolean result = stmt.executeUpdate() > 0; + String qDeleteById = "DELETE FROM build_team WHERE build_team_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDeleteById, ps -> { + ps.setInt(1, id); + boolean result = ps.executeUpdate() > 0; if (result) BUILD_TEAMS.remove(cachedBuildTeam.get()); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } public boolean setBuildTeamName(int id, String newName) { - String query = "UPDATE build_team SET name = ? WHERE build_team_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, newName); - stmt.setInt(2, id); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetNameById = "UPDATE build_team SET name = ? WHERE build_team_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetNameById, ps -> { + ps.setString(1, newName); + ps.setInt(2, id); + return ps.executeUpdate() > 0; + }))); } public boolean addReviewer(int id, String reviewerUUID) { - String query = "INSERT INTO build_team_has_reviewer (build_team_id, uuid) VALUES (?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, id); - stmt.setString(2, reviewerUUID); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qInsertReviewer = "INSERT INTO build_team_has_reviewer (build_team_id, uuid) VALUES (?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runInsertQuery(qInsertReviewer, ps -> { + ps.setInt(1, id); + ps.setString(2, reviewerUUID); + return ps.executeUpdate() > 0; + }))); } public boolean removeReviewer(int id, String reviewerUUID) { - String query = "DELETE FROM build_team_has_reviewer WHERE build_team_id = ? AND uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, id); - stmt.setString(2, reviewerUUID); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qDeleteReviewer = "DELETE FROM build_team_has_reviewer WHERE build_team_id = ? AND uuid = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDeleteReviewer, ps -> { + ps.setInt(1, id); + ps.setString(2, reviewerUUID); + return ps.executeUpdate() > 0; + }))); } public boolean isAnyReviewer(@NotNull UUID reviewerUUID) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index b2cb893b..6f114997 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -24,220 +24,173 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.holograms.leaderboards.LeaderboardTimeframe; -import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Slot; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.*; public class BuilderProvider { protected static final Map BUILDERS = new HashMap<>(); + private static final String Q_SLOTS_BY_UUID = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; public Builder getBuilderByUUID(UUID uuid) { if (BUILDERS.containsKey(uuid)) return BUILDERS.get(uuid); - String query = "SELECT name, score, first_slot, second_slot, third_slot, plot_type FROM builder WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, uuid.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - return new Builder(uuid, rs.getString(1), rs.getInt(2), rs.getInt(3), + String qByUuid = "SELECT name, score, first_slot, second_slot, third_slot, plot_type FROM builder WHERE uuid = ?;"; + return Utils.handleSqlException(null, () -> SqlHelper.runQuery(qByUuid, ps -> { + ps.setString(1, uuid.toString()); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + Builder builder = new Builder(uuid, rs.getString(1), rs.getInt(2), rs.getInt(3), rs.getInt(4), rs.getInt(5), rs.getInt(6)); - } + BUILDERS.put(uuid, builder); // cache the builder + return builder; } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null; + return null; + })); } public Builder getBuilderByName(String name) { - String query = "SELECT uuid FROM builder WHERE name = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, name); + for (var i : BUILDERS.values()) { + if (i.getName().equalsIgnoreCase(name)) { + return i; // return cached builder if name matches + } + } - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return null; + String qUuidByName = "SELECT uuid FROM builder WHERE name = ?;"; + return Utils.handleSqlException(null, () -> SqlHelper.runQuery(qUuidByName, ps -> { + ps.setString(1, name); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { String uuid = rs.getString(1); if (uuid != null) return getBuilderByUUID(UUID.fromString(uuid)); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null; + return null; + })); } public boolean addBuilderIfNotExists(UUID uuid, String name) { if (BUILDERS.containsKey(uuid)) return true; - String selectQuery = "SELECT 1 FROM builder WHERE uuid = ?;"; - String insertQuery = "INSERT INTO builder (uuid, name, plot_type) VALUES (?, ?, 1);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement selectStmt = conn.prepareStatement(selectQuery)) { - selectStmt.setString(1, uuid.toString()); - try (ResultSet rs = selectStmt.executeQuery()) { - if (rs.next()) return true; - } + String qExistsByUuid = "SELECT 1 FROM builder WHERE uuid = ?;"; + String qInsert = "INSERT INTO builder (uuid, name, plot_type) VALUES (?, ?, 1);"; + // builder already exists + // insert new builder + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qExistsByUuid, ps -> { + ps.setString(1, uuid.toString()); + ResultSet rs = ps.executeQuery(); + if (rs.next()) return true; // builder already exists - try (PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) { + SqlHelper.runQuery(qInsert, ps.getConnection(), insertStmt -> { insertStmt.setString(1, uuid.toString()); insertStmt.setString(2, name); - return insertStmt.executeUpdate() > 0; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + return insertStmt.executeUpdate() > 0; // insert new builder + }); + return false; + }))); } public boolean setName(@NotNull UUID uuid, String name) { - String query = "UPDATE builder SET name = ? WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, name); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - return true; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetNameByUuid = "UPDATE builder SET name = ? WHERE uuid = ?;"; + // update builder name + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetNameByUuid, ps -> { + ps.setString(1, name); + ps.setString(2, uuid.toString()); + return ps.executeUpdate() > 0; // update builder name + }))); } public boolean addScore(@NotNull UUID uuid, int score) { - String query = "UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, score); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - return true; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qIncreaseScoreByUuid = "UPDATE builder b SET score = (b.score + ?) WHERE uuid = ?;"; + // increase score by given value + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qIncreaseScoreByUuid, ps -> { + ps.setInt(1, score); + ps.setString(2, uuid.toString()); + return ps.executeUpdate() > 0; // increase score by given value + }))); } public boolean setSlot(UUID uuid, int plotID, @NotNull Slot slot) { - String query = "UPDATE builder b SET " + slot.name().toLowerCase() + "_slot = " + - (plotID > 0 ? "?" : "DEFAULT(first_slot)") + " WHERE uuid = ?;"; - - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - if (plotID > 0) stmt.setInt(1, plotID); - stmt.setString(plotID > 0 ? 2 : 1, uuid.toString()); - stmt.executeUpdate(); - return true; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qBuilderSetSlotByUuid = "UPDATE builder b SET " + slot.name().toLowerCase() + "_slot = " + (plotID > 0 ? "?" : "DEFAULT(first_slot)") + " WHERE uuid = ?;"; + // update builder slot + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qBuilderSetSlotByUuid, ps -> { + if (plotID > 0) ps.setInt(1, plotID); + ps.setString(plotID > 0 ? 2 : 1, uuid.toString()); + return ps.executeUpdate() > 0; // update builder slot + }))); } public boolean setPlotType(@NotNull UUID uuid, int plotTypeId) { - String query = "UPDATE builder b SET plot_type = ? WHERE uuid = ?;"; - - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotTypeId); - stmt.setString(2, uuid.toString()); - stmt.executeUpdate(); - return true; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetPlotTypeByUuid = "UPDATE builder b SET plot_type = ? WHERE uuid = ?;"; + // update plot type + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetPlotTypeByUuid, ps -> { + ps.setInt(1, plotTypeId); + ps.setString(2, uuid.toString()); + return ps.executeUpdate() > 0; // update plot type + }))); } public int getCompletedBuildsCount(@NotNull UUID uuid) { - String query = "SELECT COUNT(p.plot_id) AS completed_plots FROM plot p INNER JOIN builder_is_plot_member " + + String qBuilderCompletedBuildsCountByUuid = "SELECT COUNT(p.plot_id) AS completed_plots FROM plot p INNER JOIN builder_is_plot_member " + "bipm ON p.plot_id = bipm.plot_id WHERE p.status = 'completed' AND (p.owner_uuid = ? OR bipm.uuid = ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, uuid.toString()); - stmt.setString(2, uuid.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) return rs.getInt(1); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return 0; + Integer result = Utils.handleSqlException(0, () -> SqlHelper.runQuery(qBuilderCompletedBuildsCountByUuid, ps -> { + ps.setString(1, uuid.toString()); + ps.setString(2, uuid.toString()); + ResultSet rs = ps.executeQuery(); + if (rs.next()) return rs.getInt(1); + return 0; + })); + return result != null ? result : 0; } public Slot getFreeSlot(@NotNull UUID uuid) { - String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, uuid.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return null; - for (int i = 1; i <= 3; i++) { - if (rs.getString(i) == null) return Slot.values()[i - 1]; - } + return Utils.handleSqlException(null, () -> SqlHelper.runQuery(Q_SLOTS_BY_UUID, ps -> { + ps.setString(1, uuid.toString()); + ResultSet rs = ps.executeQuery(); + if (!rs.next()) return null; // no slots found + for (int i = 1; i <= 3; i++) { + if (rs.getString(i) == null) return Slot.values()[i - 1]; // return first free slot } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null; + return null; // no free slots found + })); } public Slot getSlot(@NotNull UUID uuid, int plotId) { - String query = "SELECT first_slot, second_slot, third_slot FROM builder WHERE uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, uuid.toString()); - - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return null; - if (rs.getInt(1) == plotId) return Slot.FIRST; - if (rs.getInt(2) == plotId) return Slot.SECOND; - if (rs.getInt(3) == plotId) return Slot.THIRD; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null; + return Utils.handleSqlException(null, () -> SqlHelper.runQuery(Q_SLOTS_BY_UUID, ps -> { + ps.setString(1, uuid.toString()); + ResultSet rs = ps.executeQuery(); + if (!rs.next()) return null; // no slots found + if (rs.getInt(1) == plotId) return Slot.FIRST; // first slot + if (rs.getInt(2) == plotId) return Slot.SECOND; // second slot + if (rs.getInt(3) == plotId) return Slot.THIRD; // third slot + return null; // no matching slot found + })); } - @SuppressWarnings("BooleanMethodIsAlwaysInverted") - public boolean canReviewPlot(@NotNull UUID uuid, Plot plot) { - return DataProvider.BUILD_TEAM.getReviewerCities(uuid).stream().anyMatch(c -> c.getID().equals(plot.getCityProject().getID())); + public boolean canNotReviewPlot(@NotNull UUID uuid, Plot plot) { + return DataProvider.BUILD_TEAM.getReviewerCities(uuid).stream().noneMatch(c -> c.getID().equals(plot.getCityProject().getID())); } public List getReviewersByBuildTeam(int buildTeamId) { - List builders = new ArrayList<>(); - String query = "SELECT uuid FROM build_team_has_reviewer WHERE build_team_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, buildTeamId); - try (ResultSet rs = stmt.executeQuery()) { - stmt.setInt(1, buildTeamId); - - while (rs.next()) { - Builder builder = getBuilderByUUID(UUID.fromString(rs.getString(1))); - if (builder != null) builders.add(builder); - } + String qReviewerUuidByBtId = "SELECT uuid FROM build_team_has_reviewer WHERE build_team_id = ?;"; + return Utils.handleSqlException(new ArrayList<>(), () -> SqlHelper.runQuery(qReviewerUuidByBtId, ps -> { + ps.setInt(1, buildTeamId); + ResultSet rs = ps.executeQuery(); + List builders = new ArrayList<>(); + while (rs.next()) { + Builder builder = getBuilderByUUID(UUID.fromString(rs.getString(1))); + if (builder != null) builders.add(builder); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return builders; + return builders; + })); } /** @@ -247,18 +200,14 @@ public List getReviewersByBuildTeam(int buildTeamId) { * @return provides a map of player names and their scores, or an empty map if no data is found. */ public Map getLeaderboardEntries(LeaderboardTimeframe sortBy) { - LinkedHashMap playerEntries = new LinkedHashMap<>(); - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(getLeaderboardQuery(sortBy))) { - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) playerEntries.put(rs.getString(1), rs.getInt(2)); - return playerEntries; + return Utils.handleSqlException(new LinkedHashMap<>(), () -> SqlHelper.runQuery(getLeaderboardQuery(sortBy), ps -> { + ResultSet rs = ps.executeQuery(); + LinkedHashMap playerEntries = new LinkedHashMap<>(); + while (rs.next()) { + playerEntries.put(rs.getString(1), rs.getInt(2)); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return playerEntries; + return playerEntries; + })); } /** diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 7c371891..6fea3bcf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -24,14 +24,11 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.utils.Utils; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -40,18 +37,14 @@ public class CityProjectProvider { protected static final List CITY_PROJECTS = new ArrayList<>(); public CityProjectProvider() { - String query = "SELECT city_project_id, country_code, server_name, is_visible, build_team_id FROM city_project;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - CITY_PROJECTS.add(new CityProject(rs.getString(1), // cache all city projects - rs.getString(2), rs.getString(3), rs.getBoolean(4), rs.getInt(5))); - } + String qCityProjects = "SELECT city_project_id, country_code, server_name, is_visible, build_team_id FROM city_project;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qCityProjects, ps -> { + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + CITY_PROJECTS.add(new CityProject(rs.getString(1), // cache all city projects + rs.getString(2), rs.getString(3), rs.getBoolean(4), rs.getInt(5))); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); } public Optional getById(String id) { @@ -68,98 +61,69 @@ public List get(boolean onlyVisible) { } public List getCityProjectsByBuildTeam(int buildTeamId) { - List cityProjects = new ArrayList<>(); - - String query = "SELECT city_project_id FROM city_project WHERE build_team_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, buildTeamId); - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - Optional city = getById(rs.getString(1)); - city.ifPresent(cityProjects::add); - } + String qIdByBtId = "SELECT city_project_id FROM city_project WHERE build_team_id = ?;"; + return Utils.handleSqlException(new ArrayList<>(), () -> SqlHelper.runQuery(qIdByBtId, ps -> { + ps.setInt(1, buildTeamId); + ResultSet rs = ps.executeQuery(); + List cityProjects = new ArrayList<>(); + while (rs.next()) { + Optional city = getById(rs.getString(1)); + city.ifPresent(cityProjects::add); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return cityProjects; + return cityProjects; + })); } public boolean add(String id, int buildTeamId, String countryCode, String serverName) { if (getById(id).isPresent()) return true; - String query = "INSERT INTO city_project (city_project_id, build_team_id, country_code, server_name) " + - "VALUES (?, ?, ?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, id); - stmt.setInt(2, buildTeamId); - stmt.setString(3, countryCode); - stmt.setString(4, serverName); - boolean result = stmt.executeUpdate() > 0; + String qInsert = "INSERT INTO city_project (city_project_id, build_team_id, country_code, server_name) VALUES (?, ?, ?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { + ps.setString(1, id); + ps.setInt(2, buildTeamId); + ps.setString(3, countryCode); + ps.setString(4, serverName); + boolean result = ps.executeUpdate() > 0; if (result) CITY_PROJECTS.add(new CityProject(id, countryCode, serverName, true, buildTeamId)); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } public boolean remove(String id) { Optional cityProject = getById(id); - if (cityProject.isEmpty()) return false; - - String query = "DELETE FROM city_project WHERE city_project_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, id); - boolean result = stmt.executeUpdate() > 0; - if (result) CITY_PROJECTS.remove(cityProject.get()); + String qDelete = "DELETE FROM city_project WHERE city_project_id = ?;"; + return cityProject.filter(project -> Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDelete, ps -> { + ps.setString(1, id); + boolean result = ps.executeUpdate() > 0; + if (result) CITY_PROJECTS.remove(project); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + })))).isPresent(); } public boolean setVisibility(String id, boolean isVisible) { - String query = "UPDATE city_project SET is_visible = ? WHERE city_project_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setBoolean(1, isVisible); - stmt.setString(2, id); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qUpdateVisible = "UPDATE city_project SET is_visible = ? WHERE city_project_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qUpdateVisible, ps -> { + ps.setBoolean(1, isVisible); + ps.setString(2, id); + return ps.executeUpdate() > 0; + }))); } public boolean setServer(String id, String serverName) { - String query = "UPDATE city_project SET server_name = ? WHERE city_project_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, serverName); - stmt.setString(2, id); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qUpdateServerName = "UPDATE city_project SET server_name = ? WHERE city_project_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qUpdateServerName, ps -> { + ps.setString(1, serverName); + ps.setString(2, id); + return ps.executeUpdate() > 0; + }))); } public boolean setBuildTeam(String id, int buildTeamId) { - String query = "UPDATE city_project SET build_team_id = ? WHERE city_project_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, buildTeamId); - stmt.setString(2, id); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qUpdateBuildTeamId = "UPDATE city_project SET build_team_id = ? WHERE city_project_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qUpdateBuildTeamId, ps -> { + ps.setInt(1, buildTeamId); + ps.setString(2, id); + return ps.executeUpdate() > 0; + }))); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index 57e33b9a..7c9e32ff 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,16 +24,13 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; import org.jetbrains.annotations.Nullable; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -42,20 +39,16 @@ public class CountryProvider { protected static final List COUNTRIES = new ArrayList<>(); public CountryProvider() { - String query = "SELECT country_code, continent, material, custom_model_data FROM country;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { + String qAll = "SELECT country_code, continent, material, custom_model_data FROM country;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qAll, ps -> { + ResultSet rs = ps.executeQuery(); while (rs.next()) { Continent continent = Continent.fromDatabase(rs.getString(2)); Country country = new Country(rs.getString(1), continent, rs.getString(3), rs.getString(4)); COUNTRIES.add(country); // cache all countries } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); } public List getCountries() { @@ -71,52 +64,40 @@ public Optional getCountryByCode(String code) { } public boolean setMaterialAndCustomModelData(String code, String material, @Nullable String customModelData) { - String query = "UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, material); - stmt.setString(2, customModelData); - stmt.setString(3, code); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetItem = "UPDATE country SET material = ?, custom_model_data = ? WHERE country_code = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetItem, ps -> { + ps.setString(1, material); + ps.setString(2, customModelData); + ps.setString(3, code); + return ps.executeUpdate() > 0; + }))); } public boolean addCountry(String code, Continent continent, String material, @Nullable String customModelData) { if (getCountryByCode(code).isPresent()) return true; - String query = "INSERT INTO country (country_code, continent, material, custom_model_data) VALUES (?, ?, ?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, code); - stmt.setString(2, continent.databaseEnum); - stmt.setString(3, material); - stmt.setString(4, customModelData); - boolean result = stmt.executeUpdate() > 0; + String qInsert = "INSERT INTO country (country_code, continent, material, custom_model_data) VALUES (?, ?, ?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { + ps.setString(1, code); + ps.setString(2, continent.databaseEnum); + ps.setString(3, material); + ps.setString(4, customModelData); + boolean result = ps.executeUpdate() > 0; if (result) COUNTRIES.add(new Country(code, continent, material, customModelData)); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } public boolean removeCountry(String code) { Optional cachedCountry = getCountryByCode(code); if (cachedCountry.isEmpty()) return false; - String query = "DELETE FROM country WHERE country_code = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, code); - boolean result = stmt.executeUpdate() > 0; + String qDelete = "DELETE FROM country WHERE country_code = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDelete, ps -> { + ps.setString(1, code); + boolean result = ps.executeUpdate() > 0; if (result) COUNTRIES.remove(cachedCountry.get()); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index c48abf4f..1acd026e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,17 +24,14 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.PlotSystem; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.Difficulty; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -46,23 +43,18 @@ public class DifficultyProvider { public DifficultyProvider() { // cache all difficulties - String query = "SELECT difficulty_id, multiplier, score_requirement FROM plot_difficulty;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { + String qAll = "SELECT difficulty_id, multiplier, score_requirement FROM plot_difficulty;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qAll, ps -> { + ResultSet rs = ps.executeQuery(); while (rs.next()) { String id = rs.getString(1); double multiplier = rs.getDouble(2); int scoreRequirement = rs.getInt(3); - PlotDifficulty plotDifficulty = PlotDifficulty.valueOf(id); - Difficulty difficulty = new Difficulty(plotDifficulty, id, multiplier, scoreRequirement); - DIFFICULTIES.add(difficulty); + Difficulty difficulty = new Difficulty(PlotDifficulty.valueOf(id), id, multiplier, scoreRequirement); + DIFFICULTIES.add(difficulty); // cache all difficulties } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); } public List getDifficulties() { @@ -79,29 +71,21 @@ public Optional getDifficultyByEnum(PlotDifficulty difficulty) { } public boolean setMultiplier(String id, double multiplier) { - String query = "UPDATE plot_difficulty SET multiplier = ? WHERE difficulty_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setDouble(1, multiplier); - stmt.setString(2, id); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetMulti = "UPDATE plot_difficulty SET multiplier = ? WHERE difficulty_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetMulti, ps -> { + ps.setDouble(1, multiplier); + ps.setString(2, id); + return ps.executeUpdate() > 0; + }))); } public boolean setScoreRequirement(String id, int scoreRequirement) { - String query = "UPDATE plot_difficulty SET score_requirement = ? WHERE difficulty_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, scoreRequirement); - stmt.setString(2, id); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetScoreRequirement = "UPDATE plot_difficulty SET score_requirement = ? WHERE difficulty_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetScoreRequirement, ps -> { + ps.setInt(1, scoreRequirement); + ps.setString(2, id); + return ps.executeUpdate() > 0; + }))); } public boolean builderMeetsRequirements(Builder builder, PlotDifficulty plotDifficulty) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 2b21578a..c0320f72 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,17 +24,22 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; -import com.alpsbte.plotsystem.core.system.*; +import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.Plot; -import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; +import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; +import com.alpsbte.plotsystem.utils.enums.Status; import org.bukkit.Bukkit; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.sql.*; +import java.sql.Date; +import java.sql.ResultSet; +import java.sql.SQLException; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @@ -46,138 +51,94 @@ public class PlotProvider { "plot.plot_version, plot.plot_type"; public Plot getPlotById(int plotId) { - String query = "SELECT city_project_id, difficulty_id, owner_uuid, status, " + - "outline_bounds, last_activity_date, plot_version, plot_type FROM plot WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return null; - CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString(1)).orElseThrow(); - PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString(2)).orElseThrow().getDifficulty(); - String ownerUUIDString = rs.getString(3); - UUID ownerUUID = ownerUUIDString != null ? UUID.fromString(ownerUUIDString) : null; - Status status = Status.valueOf(rs.getString(4)); - String outlineBounds = rs.getString(5); - Date lastActivityDate = rs.getDate(6); - LocalDate lastActivity = lastActivityDate != null ? lastActivityDate.toLocalDate() : null; - double version = rs.getDouble(7); - PlotType type = PlotType.byId(rs.getInt(8)); - - return new Plot(plotId, cityProject, difficulty, ownerUUID, status, outlineBounds, - lastActivity, version, type, getPlotMembers(plotId)); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null; + String qGet = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE plot_id = ?;"; + return Utils.handleSqlException(null, () -> SqlHelper.runQuery(qGet, ps -> { + ps.setInt(1, plotId); + ResultSet rs = ps.executeQuery(); + if (!rs.next()) return null; // No plot found + return extractPlot(rs); + })); } - public List getPlots(Status status) { - String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE status = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, status.name()); - - try (ResultSet rs = stmt.executeQuery()) { - List plots = new ArrayList<>(); - while (rs.next()) { - plots.add(extractPlot(rs)); - } - return plots; + public List getPlots(@NotNull Status status) { + String qAllByStatus = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE status = ?;"; + return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qAllByStatus, ps -> { + ps.setString(1, status.name()); + ResultSet rs = ps.executeQuery(); + List plots = new ArrayList<>(); + while (rs.next()) { + plots.add(extractPlot(rs)); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return List.of(); + return plots; + })); } - public List getPlots(CityProject city, Status... statuses) { + public List getPlots(@NotNull CityProject city, Status @NotNull ... statuses) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ?"; query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, city.getID()); - for (int i = 0; i < statuses.length; i++) stmt.setString(i + 2, statuses[i].name()); - - try (ResultSet rs = stmt.executeQuery()) { - List plots = new ArrayList<>(); - while (rs.next()) plots.add(extractPlot(rs)); - return plots; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return List.of(); + String qPlotsWithCityAndStatuses = query; + return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qPlotsWithCityAndStatuses, ps -> { + ps.setString(1, city.getID()); + for (int i = 0; i < statuses.length; i++) ps.setString(i + 2, statuses[i].name()); + ResultSet rs = ps.executeQuery(); + List plots = new ArrayList<>(); + while (rs.next()) plots.add(extractPlot(rs)); + return plots; + })); } - public List getPlots(CityProject city, PlotDifficulty plotDifficulty, Status status) { - String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ? AND difficulty_id = ? " + - "AND status = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - - stmt.setString(1, city.getID()); - stmt.setString(2, plotDifficulty.name()); - stmt.setString(3, status.name()); - - try (ResultSet rs = stmt.executeQuery()) { - List plots = new ArrayList<>(); - while (rs.next()) plots.add(extractPlot(rs)); - return plots; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return List.of(); + public List getPlots(@NotNull CityProject city, @NotNull PlotDifficulty plotDifficulty, @NotNull Status status) { + String qAllByCityDifficultyStatus = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ? AND difficulty_id = ? AND status = ?;"; + return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qAllByCityDifficultyStatus, ps -> { + ps.setString(1, city.getID()); + ps.setString(2, plotDifficulty.name()); + ps.setString(3, status.name()); + ResultSet rs = ps.executeQuery(); + List plots = new ArrayList<>(); + while (rs.next()) plots.add(extractPlot(rs)); + return plots; + })); } - public List getPlots(List cities, Status... statuses) { + public List getPlots(@NotNull List cities, Status... statuses) { if (cities.isEmpty()) return List.of(); String cityPlaceholders = "?,".repeat(cities.size() - 1) + "?"; String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id IN (" + cityPlaceholders + ")"; query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { + String qPlotsWithCitiesAndStatuses = query; + + return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qPlotsWithCitiesAndStatuses, ps -> { int index = 1; - for (CityProject city : cities) stmt.setString(index++, city.getID()); - for (Status status : statuses) stmt.setString(index++, status.name()); + for (CityProject city : cities) ps.setString(index++, city.getID()); + for (Status status : statuses) ps.setString(index++, status.name()); - try (ResultSet rs = stmt.executeQuery()) { + ResultSet rs = ps.executeQuery(); List plots = new ArrayList<>(); while (rs.next()) plots.add(extractPlot(rs)); return plots; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return List.of(); + })); } - public List getPlots(Builder builder, Status... statuses) { + public List getPlots(@NotNull Builder builder, Status @NotNull ... statuses) { String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot LEFT JOIN builder_is_plot_member pm ON " + "plot.plot_id = pm.plot_id WHERE (plot.owner_uuid = ? OR pm.uuid = ?)"; query += statuses.length > 0 ? "AND plot.status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { + String qPlotsWithBuilderAndStatuses = query; + return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qPlotsWithBuilderAndStatuses, ps -> { String builderUUID = builder.getUUID().toString(); - stmt.setString(1, builderUUID); - stmt.setString(2, builderUUID); - for (int i = 0; i < statuses.length; i++) stmt.setString(i + 3, statuses[i].name()); + ps.setString(1, builderUUID); + ps.setString(2, builderUUID); + for (int i = 0; i < statuses.length; i++) ps.setString(i + 3, statuses[i].name()); - try (ResultSet rs = stmt.executeQuery()) { + ResultSet rs = ps.executeQuery(); List plots = new ArrayList<>(); while (rs.next()) plots.add(extractPlot(rs)); return plots; - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return List.of(); + })); } - private Plot extractPlot(ResultSet rs) throws SQLException { + private @NotNull Plot extractPlot(@NotNull ResultSet rs) throws SQLException { int plotId = rs.getInt("plot_id"); CityProject cityProject = DataProvider.CITY_PROJECT.getById(rs.getString("city_project_id")).orElseThrow(); PlotDifficulty difficulty = DataProvider.DIFFICULTY.getDifficultyById(rs.getString("difficulty_id")).orElseThrow().getDifficulty(); @@ -206,21 +167,16 @@ private Plot extractPlot(ResultSet rs) throws SQLException { } public List getPlotMembers(int plotId) { - String query = "SELECT uuid FROM builder_is_plot_member WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - + String qAllMembers = "SELECT uuid FROM builder_is_plot_member WHERE plot_id = ?;"; + return Utils.handleSqlException(new ArrayList<>(), () -> SqlHelper.runQuery(qAllMembers, ps -> { + ps.setInt(1, plotId); + ResultSet rs = ps.executeQuery(); List members = new ArrayList<>(); - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) + while (rs.next()) { members.add(Builder.byUUID(UUID.fromString(rs.getString(1)))); } return members; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return new ArrayList<>(); + })); } public byte[] getInitialSchematic(int plotId) { @@ -231,161 +187,106 @@ public byte[] getCompletedSchematic(int plotId) { return getSchematic(plotId, "complete_schematic"); } - private byte[] getSchematic(int plotId, String name) { - String query = "SELECT " + name + " FROM plot WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - try (ResultSet rs = stmt.executeQuery()) { + private byte @Nullable [] getSchematic(int plotId, String name) { + String qName = "SELECT " + name + " FROM plot WHERE plot_id = ?;"; + return Utils.handleSqlException(null, () -> SqlHelper.runQuery(qName, ps -> { + ps.setInt(1, plotId); + ResultSet rs = ps.executeQuery(); if (!rs.next()) return null; return rs.getBytes(1); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return null; + })); } public boolean setCompletedSchematic(int plotId, byte[] completedSchematic) { - String query = "UPDATE plot SET complete_schematic = ? WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setBytes(1, completedSchematic); - stmt.setInt(2, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetCompleteSchematic = "UPDATE plot SET complete_schematic = ? WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetCompleteSchematic, ps -> { + ps.setBytes(1, completedSchematic); + ps.setInt(2, plotId); + return ps.executeUpdate() > 0; + }))); } public boolean setPlotOwner(int plotId, UUID ownerUUID) { - String updateQuery = "UPDATE plot SET owner_uuid = ? WHERE plot_id = ?;"; - String defaultUpdateQuery = "UPDATE plot SET owner_uuid = DEFAULT(owner_uuid) WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(ownerUUID == null ? defaultUpdateQuery : updateQuery)) { + String qSetOwner = "UPDATE plot SET owner_uuid = " + (ownerUUID == null ? "DEFAULT(owner_uuid)" : "?") + " WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetOwner, ps -> { if (ownerUUID == null) { - stmt.setInt(1, plotId); + ps.setInt(1, plotId); } else { - stmt.setString(1, ownerUUID.toString()); - stmt.setInt(2, plotId); + ps.setString(1, ownerUUID.toString()); + ps.setInt(2, plotId); } - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + return ps.executeUpdate() > 0; + }))); } public boolean setLastActivity(int plotId, LocalDate activityDate) { - String query = "UPDATE plot SET last_activity_date = ? WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setDate(1, activityDate == null ? null : Date.valueOf(activityDate)); - stmt.setInt(2, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetLastActivityDate = "UPDATE plot SET last_activity_date = ? WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetLastActivityDate, ps -> { + ps.setDate(1, activityDate == null ? null : Date.valueOf(activityDate)); + ps.setInt(2, plotId); + return ps.executeUpdate() > 0; + }))); } - public boolean setStatus(int plotId, Status status) { - String query = "UPDATE plot SET status = ? WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, status.name()); - stmt.setInt(2, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + public boolean setStatus(int plotId, @NotNull Status status) { + String qSetStatus = "UPDATE plot SET status = ? WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetStatus, ps -> { + ps.setString(1, status.name()); + ps.setInt(2, plotId); + return ps.executeUpdate() > 0; + }))); } public boolean setMcVersion(int plotId) { - String query = "UPDATE plot SET mc_version = ? WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, Bukkit.getMinecraftVersion()); - stmt.setInt(2, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; - } - - public boolean setPlotMembers(int plotId, List members) { - String deleteQuery = "DELETE FROM builder_is_plot_member WHERE plot_id = ?;"; - String insertQuery = "INSERT INTO builder_is_plot_member (plot_id, uuid) VALUES (?, ?);"; - - try (Connection conn = DatabaseConnection.getConnection()) { - conn.setAutoCommit(false); - try (PreparedStatement deleteStmt = conn.prepareStatement(deleteQuery); - PreparedStatement insertStmt = conn.prepareStatement(insertQuery)) { - - // Delete existing members - deleteStmt.setInt(1, plotId); - deleteStmt.executeUpdate(); - - // Insert new members if list is not empty - if (!members.isEmpty()) { - for (Builder member : members) { - insertStmt.setInt(1, plotId); - insertStmt.setString(2, member.getUUID().toString()); - insertStmt.addBatch(); - } - insertStmt.executeBatch(); - } - - conn.commit(); // Commit transaction - return true; - } catch (SQLException ex) { - conn.rollback(); // Rollback if anything fails - Utils.logSqlException(ex); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetMcVersion = "UPDATE plot SET mc_version = ? WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetMcVersion, ps -> { + ps.setString(1, Bukkit.getMinecraftVersion()); + ps.setInt(2, plotId); + return ps.executeUpdate() > 0; + }))); } - public boolean setPlotType(int plotId, PlotType type) { - String query = "UPDATE plot SET plot_type = ? WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, type.getId()); - stmt.setInt(2, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + public boolean setPlotType(int plotId, @NotNull PlotType type) { + String qSetType = "UPDATE plot SET plot_type = ? WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetType, ps -> { + ps.setInt(1, type.getId()); + ps.setInt(2, plotId); + return ps.executeUpdate() > 0; + }))); } public boolean setPasted(int plotId, boolean pasted) { - String query = "UPDATE plot SET is_pasted = ? WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setBoolean(1, pasted); - stmt.setInt(2, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetPasted = "UPDATE plot SET is_pasted = ? WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetPasted, ps -> { + ps.setBoolean(1, pasted); + ps.setInt(2, plotId); + return ps.executeUpdate() > 0; + }))); } public boolean deletePlot(int plotId) { - String query = "DELETE FROM plot WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qDelete = "DELETE FROM plot WHERE plot_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDelete, ps -> { + ps.setInt(1, plotId); + return ps.executeUpdate() > 0; + }))); + } + + public boolean addPlotMember(int id, Builder member) { + String qInsertPlotMember = "INSERT INTO builder_is_plot_member (plot_id, uuid) VALUES (?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsertPlotMember, ps -> { + ps.setInt(1, id); + ps.setString(2, member.getUUID().toString()); + return ps.executeUpdate() > 0; + }))); + } + + public boolean removePlotMember(int id, Builder member) { + String qDeletePlotMember = "DELETE FROM builder_is_plot_member WHERE plot_id = ? AND uuid = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDeletePlotMember, ps -> { + ps.setInt(1, id); + ps.setString(2, member.getUUID().toString()); + return ps.executeUpdate() > 0; + }))); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 35a87616..0f2e44f8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -24,8 +24,8 @@ package com.alpsbte.plotsystem.core.database.providers; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; @@ -33,11 +33,9 @@ import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.*; public class ReviewProvider { @@ -47,119 +45,89 @@ public class ReviewProvider { public ReviewProvider() { // cache all review notifications - String query = "SELECT review_id, uuid FROM builder_has_review_notification;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { + String qAllNotifys = "SELECT review_id, uuid FROM builder_has_review_notification;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qAllNotifys, ps -> { + ResultSet rs = ps.executeQuery(); while (rs.next()) { NOTIFICATIONS.add(new ReviewNotification(rs.getInt(1), UUID.fromString(rs.getString(2)))); } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); // cache all toggle criteria - query = "SELECT criteria_name, is_optional FROM review_toggle_criteria;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { + String qAllToggleCriterias = "SELECT criteria_name, is_optional FROM review_toggle_criteria;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qAllToggleCriterias, ps -> { + ResultSet rs = ps.executeQuery(); while (rs.next()) { TOGGLE_CRITERIA.add(new ToggleCriteria(rs.getString(1), rs.getBoolean(2))); } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); // cache all build team toggle criteria - query = "SELECT criteria_name, build_team_id FROM build_team_uses_toggle_criteria;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { + String qAllBuildteamCriteria = "SELECT criteria_name, build_team_id FROM build_team_uses_toggle_criteria;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qAllBuildteamCriteria, ps -> { + ResultSet rs = ps.executeQuery(); while (rs.next()) { String criteriaName = rs.getString(1); ToggleCriteria toggle = TOGGLE_CRITERIA.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst().orElseThrow(); BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(rs.getInt(2), toggle)); } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); } public Optional getReview(int reviewId) { - String query = "SELECT plot_id, rating, score, feedback, reviewed_by FROM plot_review WHERE review_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return Optional.empty(); - - int plotId = rs.getInt(1); - ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); - int score = rs.getInt(3); - String feedback = rs.getString(4); - UUID reviewedBy = UUID.fromString(rs.getString(5)); - - return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return Optional.empty(); + String qById = "SELECT plot_id, rating, score, feedback, reviewed_by FROM plot_review WHERE review_id = ?;"; + return Utils.handleSqlException(Optional.empty(), () -> SqlHelper.runQuery(qById, ps -> { + ps.setInt(1, reviewId); + ResultSet rs = ps.executeQuery(); + if (!rs.next()) return Optional.empty(); + + int plotId = rs.getInt(1); + ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); + int score = rs.getInt(3); + String feedback = rs.getString(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); + + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + })); } public Optional getLatestReview(int plotId) { - String query = "SELECT review_id, rating, score, feedback, reviewed_by FROM plot_review " + - "WHERE plot_id = ? ORDER BY review_date DESC LIMIT 1;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - - try (ResultSet rs = stmt.executeQuery()) { - if (!rs.next()) return Optional.empty(); + String qLatestByPlotId = "SELECT review_id, rating, score, feedback, reviewed_by FROM plot_review WHERE plot_id = ? ORDER BY review_date DESC LIMIT 1;"; + return Utils.handleSqlException(Optional.empty(), () -> SqlHelper.runQuery(qLatestByPlotId, ps -> { + ps.setInt(1, plotId); + ResultSet rs = ps.executeQuery(); + if (!rs.next()) return Optional.empty(); + + int reviewId = rs.getInt(1); + ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); + int score = rs.getInt(3); + String feedback = rs.getString(4); + UUID reviewedBy = UUID.fromString(rs.getString(5)); + + return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); + })); + } + public List getPlotReviewHistory(int plotId) { + String qByPlotId = "SELECT review_id, rating, score, feedback, reviewed_by FROM plot_review WHERE plot_id = ?;"; + return Utils.handleSqlException(new ArrayList<>(), () -> SqlHelper.runQuery(qByPlotId, ps -> { + ps.setInt(1, plotId); + ResultSet rs = ps.executeQuery(); + List reviews = new ArrayList<>(); + while (rs.next()) { int reviewId = rs.getInt(1); ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); int score = rs.getInt(3); String feedback = rs.getString(4); UUID reviewedBy = UUID.fromString(rs.getString(5)); - return Optional.of(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); - } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return Optional.empty(); - } - - public List getPlotReviewHistory(int plotId) { - List reviews = new ArrayList<>(); - String query = "SELECT review_id, rating, score, feedback, reviewed_by FROM plot_review WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - int reviewId = rs.getInt(1); - ReviewRating rating = getReviewRating(reviewId, rs.getString(2)); - int score = rs.getInt(3); - String feedback = rs.getString(4); - UUID reviewedBy = UUID.fromString(rs.getString(5)); - - reviews.add(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); - } + reviews.add(new PlotReview(reviewId, plotId, rating, score, feedback, reviewedBy)); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return reviews; + return reviews; + })); } - private ReviewRating getReviewRating(int reviewId, String ratingString) { + private @NotNull ReviewRating getReviewRating(int reviewId, @NotNull String ratingString) { int accuracyPoints = Integer.parseInt(ratingString.split(",")[0]); int blockPalettePoints = Integer.parseInt(ratingString.split(",")[1]); Map toggleCriteria = getReviewToggleCriteria(reviewId); @@ -167,35 +135,27 @@ private ReviewRating getReviewRating(int reviewId, String ratingString) { } public boolean updateFeedback(int reviewId, String newFeedback) { - String query = "UPDATE plot_review SET feedback = ? WHERE review_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, newFeedback); - stmt.setInt(2, reviewId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetFeedback = "UPDATE plot_review SET feedback = ? WHERE review_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetFeedback, ps -> { + ps.setString(1, newFeedback); + ps.setInt(2, reviewId); + return ps.executeUpdate() > 0; + }))); } - public PlotReview createReview(Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { + public PlotReview createReview(@NotNull Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { boolean result = DataProvider.PLOT.setMcVersion(plot.getID()); if (!result) return null; // Create Review - String query = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) " + - "VALUES (?, ?, ?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plot.getID()); - stmt.setString(2, rating.getRatingDatabaseString()); - stmt.setInt(3, score); - stmt.setString(4, reviewerUUID.toString()); - result = stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + String qInsert = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) VALUES (?, ?, ?, ?);"; + result = Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { + ps.setInt(1, plot.getID()); + ps.setString(2, rating.getRatingDatabaseString()); + ps.setInt(3, score); + ps.setString(4, reviewerUUID.toString()); + return ps.executeUpdate() > 0; + }))); if (!result) return null; @@ -226,30 +186,23 @@ public boolean removeReview(int reviewId) { removeCheckedToggleCriteria(reviewId); // remove review - String query = "DELETE FROM plot_review WHERE review_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qDelete = "DELETE FROM plot_review WHERE review_id = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDelete, ps -> { + ps.setInt(1, reviewId); + return ps.executeUpdate() > 0; + }))); } public boolean removeAllReviewsOfPlot(int plotId) { + String qIdsByPlotId = "SELECT review_id FROM plot_review WHERE plot_id = ?;"; List reviewIds = new ArrayList<>(); - String query = "SELECT review_id FROM plot_review WHERE plot_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, plotId); - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) reviewIds.add(rs.getInt(1)); + Utils.handleSqlException(() -> SqlHelper.runQuery(qIdsByPlotId, ps -> { + ps.setInt(1, plotId); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + reviewIds.add(rs.getInt(1)); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); boolean successful = true; for (int reviewId : reviewIds) { @@ -267,52 +220,39 @@ public boolean addToggleCriteria(String criteriaName, boolean isOptional) { Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); if (criteria.isPresent()) return false; - String query = "INSERT INTO review_toggle_criteria (criteria_name, is_optional) " + - "VALUES (?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, criteriaName); - stmt.setBoolean(2, isOptional); - boolean successful = stmt.executeUpdate() > 0; - if (successful) TOGGLE_CRITERIA.add(new ToggleCriteria(criteriaName, isOptional)); - return successful; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qInsertToggleCriteria = "INSERT INTO review_toggle_criteria (criteria_name, is_optional) VALUES (?, ?);"; + if (!Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsertToggleCriteria, ps -> { + ps.setString(1, criteriaName); + ps.setBoolean(2, isOptional); + return ps.executeUpdate() > 0; + })))) return false; + TOGGLE_CRITERIA.add(new ToggleCriteria(criteriaName, isOptional)); + return true; } public boolean removeToggleCriteria(String criteriaName) { Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); if (criteria.isEmpty()) return false; - String query = "DELETE FROM review_toggle_criteria WHERE criteria_name = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, criteriaName); - boolean successful = stmt.executeUpdate() > 0; + String qDeleteToggleCriteria = "DELETE FROM review_toggle_criteria WHERE criteria_name = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDeleteToggleCriteria, ps -> { + ps.setString(1, criteriaName); + boolean successful = ps.executeUpdate() > 0; if (successful) TOGGLE_CRITERIA.remove(criteria.get()); return successful; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } public boolean setToggleCriteriaOptional(String criteriaName, boolean isOptional) { Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); if (criteria.isEmpty()) return false; - String query = "UPDATE review_toggle_criteria SET is_optional = ? WHERE criteria_name = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setBoolean(1, isOptional); - stmt.setString(1, criteriaName); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetToggleCriteriaOptional = "UPDATE review_toggle_criteria SET is_optional = ? WHERE criteria_name = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetToggleCriteriaOptional, ps -> { + ps.setBoolean(1, isOptional); + ps.setString(2, criteriaName); + return ps.executeUpdate() > 0; + }))); } public List getAllToggleCriteria() {return TOGGLE_CRITERIA.stream().toList();} @@ -325,82 +265,57 @@ public boolean assignBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria cri Optional existingCriteria = getBuildTeamToggleCriteria(buildTeamId).stream().filter(t -> t.getCriteriaName().equals(criteria.getCriteriaName())).findFirst(); if (existingCriteria.isPresent()) return false; - String query = "INSERT INTO build_team_uses_toggle_criteria (build_team_id, criteria_name) " + - "VALUES (?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, buildTeamId); - stmt.setString(2, criteria.getCriteriaName()); - boolean successful = stmt.executeUpdate() > 0; - if (successful) BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(buildTeamId, criteria)); - return successful; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qInsertCriteriaToBuildteam = "INSERT INTO build_team_uses_toggle_criteria (build_team_id, criteria_name) VALUES (?, ?);"; + if (!Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsertCriteriaToBuildteam, ps -> { + ps.setInt(1, buildTeamId); + ps.setString(2, criteria.getCriteriaName()); + return ps.executeUpdate() > 0; + })))) return false; + BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(buildTeamId, criteria)); + return true; } public boolean removeBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { Optional existingCriteria = BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(btc -> btc.getBuildTeamId() == buildTeamId && btc.getCriteria().getCriteriaName().equals(criteria.getCriteriaName())).findFirst(); if (existingCriteria.isEmpty()) return false; - String query = "DELETE FROM build_team_uses_toggle_criteria WHERE build_team_id = ? AND criteria_name = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, buildTeamId); - stmt.setString(2, criteria.getCriteriaName()); - boolean successful = stmt.executeUpdate() > 0; + String qDeleteCriteriaToBuildteam = "DELETE FROM build_team_uses_toggle_criteria WHERE build_team_id = ? AND criteria_name = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDeleteCriteriaToBuildteam, ps -> { + ps.setInt(1, buildTeamId); + ps.setString(2, criteria.getCriteriaName()); + boolean successful = ps.executeUpdate() > 0; if (successful) BUILD_TEAM_TOGGLE_CRITERIA.remove(existingCriteria.get()); return successful; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } public Map getReviewToggleCriteria(int reviewId) { - HashMap toggleCriteriaList = new HashMap<>(); - String query = "SELECT criteria_name, is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - boolean isChecked = rs.getBoolean(2); - toggleCriteriaList.put(getToggleCriteria(rs.getString(1)).orElseThrow(), isChecked); - } + String qReviewToggleCriteriasByReviewId = "SELECT criteria_name, is_checked FROM review_contains_toggle_criteria WHERE review_id = ?;"; + return Utils.handleSqlException(new HashMap<>(), () -> SqlHelper.runQuery(qReviewToggleCriteriasByReviewId, ps -> { + ps.setInt(1, reviewId); + ResultSet rs = ps.executeQuery(); + HashMap toggleCriteriaList = new HashMap<>(); + while (rs.next()) { + boolean isChecked = rs.getBoolean(2); + toggleCriteriaList.put(getToggleCriteria(rs.getString(1)).orElseThrow(), isChecked); } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return toggleCriteriaList; + return toggleCriteriaList; + })); } - public boolean addReviewToggleCriteria(int reviewId, ToggleCriteria toggle, boolean isChecked) { - String query = "INSERT INTO review_contains_toggle_criteria (review_id, criteria_name, is_checked) " + - "VALUES (?, ?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - stmt.setString(2, toggle.getCriteriaName()); - stmt.setBoolean(3, isChecked); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + public boolean addReviewToggleCriteria(int reviewId, @NotNull ToggleCriteria toggle, boolean isChecked) { + String qInsertToggleCriteriaToReview = "INSERT INTO review_contains_toggle_criteria (review_id, criteria_name, is_checked) VALUES (?, ?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsertToggleCriteriaToReview, ps -> { + ps.setInt(1, reviewId); + ps.setString(2, toggle.getCriteriaName()); + ps.setBoolean(3, isChecked); + return ps.executeUpdate() > 0; + }))); } public void removeCheckedToggleCriteria(int reviewId) { - String query = "DELETE FROM review_contains_toggle_criteria WHERE review_id = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - stmt.executeUpdate(); - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + String qDeleteToggleCriteriaToReview = "DELETE FROM review_contains_toggle_criteria WHERE review_id = ?;"; + Utils.handleSqlException(() -> SqlHelper.runStatement(qDeleteToggleCriteriaToReview, ps -> ps.setInt(1, reviewId))); } // --- Review Notification --- @@ -420,16 +335,12 @@ public void removeReviewNotification(int reviewId, UUID uuid) { Optional notification = getReviewNotification(reviewId, uuid); if (notification.isEmpty()) return; - String query = "DELETE FROM builder_has_review_notification WHERE review_id = ? AND uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - stmt.setString(2, uuid.toString()); - boolean result = stmt.executeUpdate() > 0; - if (result) NOTIFICATIONS.remove(notification.get()); - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + String qDeleteReviewNotify = "DELETE FROM builder_has_review_notification WHERE review_id = ? AND uuid = ?;"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qDeleteReviewNotify, ps -> { + ps.setInt(1, reviewId); + ps.setString(2, uuid.toString()); + if (ps.executeUpdate() > 0) NOTIFICATIONS.remove(notification.get()); + })); } public void createReviewNotification(int reviewId, UUID uuid) { @@ -439,15 +350,11 @@ public void createReviewNotification(int reviewId, UUID uuid) { return; } - String query = "INSERT INTO builder_has_review_notification (review_id, uuid) VALUES (?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, reviewId); - stmt.setString(2, uuid.toString()); - boolean result = stmt.executeUpdate() > 0; - if (result) NOTIFICATIONS.add(new ReviewNotification(reviewId, uuid)); - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + String qInsertReviewNotify = "INSERT INTO builder_has_review_notification (review_id, uuid) VALUES (?, ?);"; + Utils.handleSqlException(() -> SqlHelper.runQuery(qInsertReviewNotify, ps -> { + ps.setInt(1, reviewId); + ps.setString(2, uuid.toString()); + if (ps.executeUpdate() > 0) NOTIFICATIONS.add(new ReviewNotification(reviewId, uuid)); + })); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java index 212f4f66..fcb884dc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,13 +24,10 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.utils.Utils; -import java.sql.Connection; -import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -38,15 +35,14 @@ public class ServerProvider { protected static final List SERVERS = new ArrayList<>(); public ServerProvider() { - String query = "SELECT server_name FROM server;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) SERVERS.add(rs.getString(1)); // cache all servers + String qAll = "SELECT server_name FROM server;"; + + Utils.handleSqlException(() -> SqlHelper.runQuery(qAll, ps -> { + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + SERVERS.add(rs.getString(1)); // cache all servers } - } catch (SQLException ex) { - Utils.logSqlException(ex); - } + })); } public boolean serverExists(String serverName) { @@ -60,33 +56,25 @@ public List getServers() { public boolean addServer(String name, int buildTeamId) { if (serverExists(name)) return true; - String query = "INSERT INTO server (server_name, build_team_id) VALUES (?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, name); - stmt.setInt(2, buildTeamId); - boolean result = stmt.executeUpdate() > 0; + String qInsert = "INSERT INTO server (server_name, build_team_id) VALUES (?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { + ps.setString(1, name); + ps.setInt(2, buildTeamId); + boolean result = ps.executeUpdate() > 0; if (result) SERVERS.add(name); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } public boolean removeServer(String name) { if (!serverExists(name)) return false; - String query = "DELETE FROM server WHERE server_name = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setString(1, name); - boolean result = stmt.executeUpdate() > 0; + String qDelete = "DELETE FROM server WHERE server_name = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDelete, ps -> { + ps.setString(1, name); + boolean result = ps.executeUpdate() > 0; if (result) SERVERS.remove(name); return result; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + }))); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index dc75471e..d79acae4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -24,19 +24,20 @@ package com.alpsbte.plotsystem.core.database.providers; -import com.alpsbte.plotsystem.core.database.DatabaseConnection; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.utils.Utils; -import java.sql.*; import java.sql.Date; +import java.sql.ResultSet; +import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.*; public class TutorialPlotProvider { public static final Map tutorialPlots = new HashMap<>(); - public static final LinkedList freeTutorialPlotIds = new LinkedList<>(); + public static final Deque freeTutorialPlotIds = new LinkedList<>(); public Optional getById(int id) { return tutorialPlots.keySet().stream().filter(t -> tutorialPlots.get(t) == id).findFirst(); @@ -46,76 +47,59 @@ public Optional getByTutorialId(int tutorialId, String playerUUID) Optional tutorialPlot = tutorialPlots.keySet().stream() .filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString().equals(playerUUID)).findFirst(); - if (tutorialPlot.isEmpty()) { - String query = "SELECT stage_id, is_complete, last_stage_complete_date FROM " + - "tutorial WHERE tutorial_id = ? AND uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, tutorialId); - stmt.setString(2, playerUUID); + if (!tutorialPlot.isEmpty()) return tutorialPlot; - try (ResultSet rs = stmt.executeQuery()) { - if (rs.next()) { - int plotId = freeTutorialPlotIds.isEmpty() ? 0 : freeTutorialPlotIds.poll(); - int stageId = rs.getInt(1); - boolean isComplete = rs.getBoolean(2); - Date lastStageCompleteDate = rs.getDate(3); - TutorialPlot newTutorialPlot = new TutorialPlot(plotId, tutorialId, playerUUID, stageId, - isComplete, lastStageCompleteDate != null ? lastStageCompleteDate.toLocalDate() : null); - tutorialPlots.put(newTutorialPlot, plotId); + String qGet = "SELECT stage_id, is_complete, last_stage_complete_date FROM tutorial WHERE tutorial_id = ? AND uuid = ?;"; + return Utils.handleSqlException(tutorialPlot, () -> SqlHelper.runQuery(qGet, ps -> { + ps.setInt(1, tutorialId); + ps.setString(2, playerUUID); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + int plotId = freeTutorialPlotIds.isEmpty() ? 0 : freeTutorialPlotIds.poll(); + int stageId = rs.getInt(1); + boolean isComplete = rs.getBoolean(2); + Date lastStageCompleteDate = rs.getDate(3); + TutorialPlot newTutorialPlot = new TutorialPlot(plotId, tutorialId, playerUUID, stageId, + isComplete, lastStageCompleteDate != null ? lastStageCompleteDate.toLocalDate() : null); + tutorialPlots.put(newTutorialPlot, plotId); - return Optional.of(newTutorialPlot); - } - } - } catch (SQLException ex) { - Utils.logSqlException(ex); + return Optional.of(newTutorialPlot); } - } - return tutorialPlot; + return Optional.empty(); + })); + } public boolean add(int tutorialId, String playerUUID) { if (getByTutorialId(tutorialId, playerUUID).isPresent()) return false; - String query = "INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, tutorialId); - stmt.setString(2, playerUUID); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qInsert = "INSERT INTO tutorial (tutorial_id, uuid) VALUES (?, ?);"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { + ps.setInt(1, tutorialId); + ps.setString(2, playerUUID); + return ps.executeUpdate() > 0; + }))); } public boolean setStageId(int tutorialId, String playerUUID, int stageId) { - String query = "UPDATE tutorial SET stage_id = ?, last_stage_complete_date = ? WHERE tutorial_id = ? AND uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, stageId); - stmt.setObject(2, LocalDate.now()); - stmt.setInt(3, tutorialId); - stmt.setString(4, playerUUID); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetStage = "UPDATE tutorial SET stage_id = ?, last_stage_complete_date = ? WHERE tutorial_id = ? AND uuid = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetStage, ps -> { + ps.setInt(1, stageId); + ps.setObject(2, LocalDate.now()); + ps.setInt(3, tutorialId); + ps.setString(4, playerUUID); + return ps.executeUpdate() > 0; + }))); } public boolean setComplete(int tutorialId, String playerUUID) { - String query = "UPDATE tutorial SET is_complete = ?, last_stage_complete_date = ? WHERE tutorial_id = ? AND uuid = ?;"; - try (Connection conn = DatabaseConnection.getConnection(); - PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setBoolean(1, true); - stmt.setObject(2, Timestamp.valueOf(LocalDateTime.now())); - stmt.setInt(3, tutorialId); - stmt.setString(4, playerUUID); - return stmt.executeUpdate() > 0; - } catch (SQLException ex) { - Utils.logSqlException(ex); - } - return false; + String qSetComplete = "UPDATE tutorial SET is_complete = ?, last_stage_complete_date = ? WHERE tutorial_id = ? AND uuid = ?;"; + return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qSetComplete, ps -> { + ps.setBoolean(1, true); + ps.setObject(2, Timestamp.valueOf(LocalDateTime.now())); + ps.setInt(3, tutorialId); + ps.setString(4, playerUUID); + return ps.executeUpdate() > 0; + }))); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 6898dad0..387ebd5a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,16 +29,15 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.CityProject; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; -import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.CityPlotWorld; import com.alpsbte.plotsystem.core.system.plot.world.OnePlotWorld; +import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; import com.alpsbte.plotsystem.core.system.review.PlotReview; import com.alpsbte.plotsystem.utils.enums.PlotDifficulty; import com.alpsbte.plotsystem.utils.enums.Slot; import com.alpsbte.plotsystem.utils.enums.Status; import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.sk89q.worldedit.math.BlockVector2; -import com.sk89q.worldedit.math.BlockVector3; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -171,11 +170,6 @@ public byte[] getCompletedSchematic() { return DataProvider.PLOT.getCompletedSchematic(getID()); } - @Override - public BlockVector3 getCenter() { - return super.getCenter(); - } - public List getReviewHistory() { return DataProvider.REVIEW.getPlotReviewHistory(getID()); } @@ -197,12 +191,12 @@ public boolean setPasted(boolean pasted) { } public boolean addPlotMember(Builder member) { - List members = getPlotMembers(); - if (members.size() < 3 && members.stream().noneMatch(m -> m.getUUID().equals(member.getUUID()))) { + List plotMembers = getPlotMembers(); + if (plotMembers.size() < 3 && plotMembers.stream().noneMatch(m -> m.getUUID().equals(member.getUUID()))) { Slot slot = member.getFreeSlot(); if (slot != null) { - members.add(member); - if (DataProvider.PLOT.setPlotMembers(getID(), members)) { + plotMembers.add(member); + if (DataProvider.PLOT.addPlotMember(getID(), member)) { if (!member.setSlot(slot, getID())) return false; getPermissions().addBuilderPerms(member.getUUID()); return true; @@ -213,10 +207,10 @@ public boolean addPlotMember(Builder member) { } public boolean removePlotMember(Builder member) { - List members = getPlotMembers(); - if (!members.isEmpty() && members.contains(member)) { - members.remove(member); - if (DataProvider.PLOT.setPlotMembers(getID(), members)) { + List plotMembers = getPlotMembers(); + if (!plotMembers.isEmpty() && plotMembers.contains(member)) { + plotMembers.remove(member); + if (DataProvider.PLOT.removePlotMember(getID(), member)) { Slot slot = member.getSlotByPlotId(getID()); if (slot != null && !member.setSlot(slot, -1)) return false; if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 19735831..1bd10227 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -24,6 +24,7 @@ package com.alpsbte.plotsystem.utils; +import com.alpsbte.alpslib.io.database.SqlHelper; import com.alpsbte.alpslib.utils.AlpsUtils; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -55,6 +56,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.sql.SQLException; import java.time.LocalDateTime; import java.util.HashSet; import java.util.Objects; @@ -234,6 +236,23 @@ public static void logSqlException(Exception ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A SQL error occurred!"), ex); } + public static @Nullable T handleSqlException(@Nullable T defaultValue, @NotNull SqlHelper.SQLCheckedSupplier supplier) { + try { + return supplier.get(); + } catch (SQLException e) { + logSqlException(e); + return defaultValue; + } + } + + public static void handleSqlException(@NotNull SqlHelper.SQLRunnable supplier) { + try { + supplier.get(); + } catch (SQLException e) { + logSqlException(e); + } + } + public static Random getRandom() { if (random == null) { random = new Random(); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java index a37a5dfe..8cf70901 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -25,11 +25,11 @@ package com.alpsbte.plotsystem.utils.io; public abstract class ConfigPaths { + private ConfigPaths() {throw new IllegalStateException("Utility class");} // General Behaviour public static final String SPAWN_WORLD = "spawn-world"; - public static final String CHECK_FOR_UPDATES = "check-for-updates"; public static final String ENABLE_SCORE_REQUIREMENT = "enable-score-requirement"; public static final String DEV_MODE = "dev-mode"; public static final String INACTIVITY_INTERVAL = "inactivity-interval"; @@ -37,14 +37,6 @@ public abstract class ConfigPaths { public static final String ENABLE_GROUP_SUPPORT = "enable-group-support"; public static final String UNFINISHED_REMINDER_INTERVAL = "unfinished-reminder-interval"; public static final String DISABLE_CITY_INSPIRATION_MODE = "disable-city-inspiration-mode"; - - // Database - private static final String DATABASE = "database."; - public static final String DATABASE_URL = DATABASE + "url"; - public static final String DATABASE_NAME = DATABASE + "dbname"; - public static final String DATABASE_USERNAME = DATABASE + "username"; - public static final String DATABASE_PASSWORD = DATABASE + "password"; - // Leaderboards private static final String HOLOGRAMS = "holograms."; public static final String SCORE_LEADERBOARD = "score-leaderboard"; diff --git a/src/main/resources/DATABASE.sql b/src/main/resources/DATABASE.sql new file mode 100644 index 00000000..0509b942 --- /dev/null +++ b/src/main/resources/DATABASE.sql @@ -0,0 +1,276 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the Software), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +-- System Info +CREATE TABLE IF NOT EXISTS system_info +( + system_id INT NOT NULL AUTO_INCREMENT, + db_version DOUBLE NOT NULL, + current_plot_version DOUBLE NOT NULL, + last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + description TEXT NULL, + PRIMARY KEY (system_id) +); + +-- Build Team +CREATE TABLE IF NOT EXISTS build_team +( + build_team_id INT NOT NULL AUTO_INCREMENT, + name VARCHAR(255) NOT NULL, + api_key VARCHAR(255) NULL UNIQUE, + api_create_date DATETIME NULL, + PRIMARY KEY (build_team_id) +); + +-- Server +CREATE TABLE IF NOT EXISTS server +( + build_team_id INT NOT NULL, + server_name VARCHAR(255) NOT NULL UNIQUE, + PRIMARY KEY (build_team_id, server_name), + FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id) + ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- Countries +CREATE TABLE IF NOT EXISTS country +( + country_code VARCHAR(2) NOT NULL, + continent ENUM ('EU','AS','AF','OC','SA','NA') NOT NULL, + material VARCHAR(255) NOT NULL, + custom_model_data VARCHAR(255) NULL, + PRIMARY KEY (country_code) +); + +-- City Projects +CREATE TABLE IF NOT EXISTS city_project +( + city_project_id VARCHAR(255) NOT NULL, + build_team_id INT NOT NULL, + country_code VARCHAR(2) NOT NULL, + server_name VARCHAR(255) NOT NULL, + is_visible BOOLEAN NOT NULL DEFAULT 1, + PRIMARY KEY (city_project_id), + FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id) + ON DELETE RESTRICT ON UPDATE CASCADE, + FOREIGN KEY (country_code) REFERENCES country (country_code) + ON DELETE RESTRICT ON UPDATE CASCADE, + FOREIGN KEY (server_name) REFERENCES server (server_name) + ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- Builders +CREATE TABLE IF NOT EXISTS builder +( + uuid VARCHAR(36) NOT NULL, + name VARCHAR(255) NOT NULL UNIQUE, + score INT NOT NULL DEFAULT 0, + first_slot INT NULL, + second_slot INT NULL, + third_slot INT NULL, + plot_type INT NOT NULL, + PRIMARY KEY (uuid) +); + +-- Difficulty +CREATE TABLE IF NOT EXISTS plot_difficulty +( + difficulty_id VARCHAR(255) NOT NULL, + multiplier DECIMAL(4, 2) DEFAULT 1.00, + score_requirement INT NOT NULL DEFAULT 0, + PRIMARY KEY (difficulty_id), + CHECK ( multiplier > 0 ), + CHECK ( score_requirement >= 0 ) +); + +-- Plot +CREATE TABLE IF NOT EXISTS plot +( + plot_id INT NOT NULL AUTO_INCREMENT, + city_project_id VARCHAR(255) NOT NULL, + difficulty_id VARCHAR(255) NOT NULL, + owner_uuid VARCHAR(36) NULL, + status ENUM ('unclaimed','unfinished','unreviewed','completed') NOT NULL DEFAULT 'unclaimed', + outline_bounds TEXT NOT NULL, + initial_schematic MEDIUMBLOB NOT NULL, + complete_schematic MEDIUMBLOB NULL, + last_activity_date DATETIME NULL, + is_pasted BOOLEAN NOT NULL DEFAULT 0, + mc_version VARCHAR(8) NULL, + plot_version DOUBLE NOT NULL, + plot_type INT NULL, + created_by VARCHAR(36) NOT NULL, + create_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (plot_id), + FOREIGN KEY (city_project_id) REFERENCES city_project (city_project_id) + ON DELETE RESTRICT ON UPDATE CASCADE, + FOREIGN KEY (difficulty_id) REFERENCES plot_difficulty (difficulty_id) + ON DELETE RESTRICT ON UPDATE CASCADE, + FOREIGN KEY (owner_uuid) REFERENCES builder (uuid) + ON DELETE RESTRICT ON UPDATE CASCADE +); + +-- Tutorial +CREATE TABLE IF NOT EXISTS tutorial +( + tutorial_id INT NOT NULL, + uuid VARCHAR(36) NOT NULL, + stage_id INT NOT NULL DEFAULT 0, + is_complete BOOLEAN NOT NULL DEFAULT 0, + first_stage_start_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_stage_complete_date DATETIME NULL, + PRIMARY KEY (tutorial_id, uuid) +); + +-- Review +CREATE TABLE IF NOT EXISTS plot_review +( + review_id INT NOT NULL AUTO_INCREMENT, + plot_id INT NOT NULL, + rating VARCHAR(7) NOT NULL, + score INT NOT NULL DEFAULT 0, + feedback VARCHAR(256) NULL, + reviewed_by VARCHAR(36) NOT NULL, + review_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (review_id), + FOREIGN KEY (plot_id) REFERENCES plot (plot_id) + ON DELETE CASCADE ON UPDATE CASCADE +); + +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +-- Toggle Criteria +CREATE TABLE IF NOT EXISTS review_toggle_criteria +( + criteria_name VARCHAR(255) NOT NULL, + is_optional BOOLEAN NOT NULL, + PRIMARY KEY (criteria_name) +); + +-- Build team uses toggle criteria +CREATE TABLE IF NOT EXISTS build_team_uses_toggle_criteria +( + build_team_id INT NOT NULL, + criteria_name VARCHAR(255) NOT NULL, + PRIMARY KEY (build_team_id, criteria_name), + FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id) + ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (criteria_name) REFERENCES review_toggle_criteria (criteria_name) + ON DELETE CASCADE ON UPDATE CASCADE +); + +-- Review contains toggle criteria +CREATE TABLE IF NOT EXISTS review_contains_toggle_criteria +( + review_id INT NOT NULL, + criteria_name VARCHAR(255) NOT NULL, + is_checked BOOLEAN NOT NULL, + PRIMARY KEY (review_id, criteria_name), + FOREIGN KEY (review_id) REFERENCES plot_review (review_id) + ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (criteria_name) REFERENCES review_toggle_criteria (criteria_name) + ON DELETE CASCADE ON UPDATE CASCADE +); + +-- Build team has reviewer +CREATE TABLE IF NOT EXISTS build_team_has_reviewer +( + build_team_id INT NOT NULL, + uuid VARCHAR(36) NOT NULL, + PRIMARY KEY (build_team_id, uuid), + FOREIGN KEY (build_team_id) REFERENCES build_team (build_team_id) + ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (uuid) REFERENCES builder (uuid) + ON DELETE CASCADE ON UPDATE CASCADE +); + +-- Builder is plot member +CREATE TABLE IF NOT EXISTS builder_is_plot_member +( + plot_id INT NOT NULL, + uuid VARCHAR(36) NOT NULL, + PRIMARY KEY (plot_id, uuid), + FOREIGN KEY (plot_id) REFERENCES plot (plot_id) + ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (uuid) REFERENCES builder (uuid) + ON DELETE CASCADE ON UPDATE CASCADE +); + +-- Builder has review notification +CREATE TABLE IF NOT EXISTS builder_has_review_notification +( + review_id INT NOT NULL, + uuid VARCHAR(36) NOT NULL, + PRIMARY KEY (review_id, uuid), + FOREIGN KEY (review_id) REFERENCES plot_review (review_id) + ON DELETE CASCADE ON UPDATE CASCADE, + FOREIGN KEY (uuid) REFERENCES builder (uuid) + ON DELETE CASCADE ON UPDATE CASCADE +); + +-- Insert initial system info +INSERT INTO system_info (system_id, db_version, current_plot_version, description) +SELECT 1, 2.0, 4.0, 'Initial database schema for Plot-System v5.0' +FROM DUAL +WHERE NOT EXISTS (SELECT 1 FROM system_info); + +-- Insert initial review toggle criterias +INSERT INTO review_toggle_criteria (criteria_name, is_optional) +VALUES ('built_on_outlines', 0), + ('correct_amount_windows_doors', 0), + ('correct_facade_colour', 0), + ('correct_height', 0), + ('correct_roof_colour', 1), + ('correct_roof_shape', 0), + ('correct_window_type', 1), + ('windows_blacked_out', 0) +ON DUPLICATE KEY UPDATE criteria_name = VALUES(criteria_name); + +INSERT INTO plot_difficulty (difficulty_id, multiplier) +VALUES ('EASY', 1.0), + ('MEDIUM', 1.5), + ('HARD', 2) +ON DUPLICATE KEY UPDATE difficulty_id = VALUES(difficulty_id); \ No newline at end of file diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 5acfae8f..1ef96243 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -6,9 +6,6 @@ # | [Contacts - Discord] R3tuxn, Cinnazeyy & Zoriot # ----------------------------------------------------- -# Keep updated about newer versions -check-for-updates: true - # Enables special dev tools and features for development # NOTE: Do not change if you do not know what you are doing dev-mode: false @@ -48,6 +45,10 @@ database: dbname: plotsystem username: plotsystem password: minecraft + max-lifetime: 1800000 # 30 minutes + connection-timeout: 30000 # 30 seconds + keepalive-time: 120000 # 2 minutes + maximum-pool-size: 10 # Maximum number of connections in the pool # ----------------------------------------------------- From a4e8e85f406dd43709af94dfaa1451937ffc54ca Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sun, 6 Jul 2025 18:04:30 +0200 Subject: [PATCH 128/175] register review setup commands --- .../com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java | 1 + .../commands/admin/setup/CMD_Setup_ReviewCriteria.java | 3 --- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java index 262f7d2d..a13002b5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java @@ -37,6 +37,7 @@ public CMD_Setup() { registerSubCommand(new CMD_Setup_Country(this)); registerSubCommand(new CMD_Setup_City(this)); registerSubCommand(new CMD_Setup_Difficulty(this)); + registerSubCommand(new CMD_Setup_ReviewCriteria(this)); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java index f90ac7b2..3becfcc3 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -24,14 +24,12 @@ package com.alpsbte.plotsystem.commands.admin.setup; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; -import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.CommandSender; import java.util.List; @@ -39,7 +37,6 @@ import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; -import static net.kyori.adventure.text.format.NamedTextColor.RED; public class CMD_Setup_ReviewCriteria extends SubCommand { public CMD_Setup_ReviewCriteria(BaseCommand baseCommand) { From d369eb908035058972fd784afd3f9a75de0f3aea Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 14 Jul 2025 18:21:09 +0200 Subject: [PATCH 129/175] =?UTF-8?q?build:=20=F0=9F=91=B7=20exclude=20depen?= =?UTF-8?q?dency=20which=20is=20already=20present=20and=20add=20commons-io?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- pom.xml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 77e855ea..a06d7d4a 100644 --- a/pom.xml +++ b/pom.xml @@ -156,7 +156,13 @@ com.zaxxer HikariCP - 4.0.3 + 6.3.0 + + + org.slf4j + slf4j-api + + compile @@ -172,6 +178,12 @@ 1.5 provided + + commons-io + commons-io + 2.17.0 + provided + From 98077375c7c4791441d2028c443990c6b8a0f905 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 14 Jul 2025 21:49:16 +0200 Subject: [PATCH 130/175] =?UTF-8?q?fix(setup):=20=F0=9F=A9=B9=20reload=20l?= =?UTF-8?q?anguage=20system,=20allow=20full=20continent=20names,=20fix=20m?= =?UTF-8?q?essages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- .editorconfig | 4 ++-- .idea/copyright/profiles_settings.xml | 6 +++++- .../plotsystem/commands/admin/CMD_PReload.java | 2 ++ .../commands/admin/setup/CMD_Setup_City.java | 9 ++++----- .../commands/admin/setup/CMD_Setup_Country.java | 15 ++++++--------- .../java/com/alpsbte/plotsystem/utils/Utils.java | 12 ++++++++++-- 6 files changed, 29 insertions(+), 19 deletions(-) diff --git a/.editorconfig b/.editorconfig index 095d8c6e..3788965b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -76,7 +76,7 @@ ij_java_case_statement_on_separate_line = true ij_java_catch_on_new_line = false ij_java_class_annotation_wrap = split_into_lines ij_java_class_brace_style = end_of_line -ij_java_class_count_to_use_import_on_demand = 5 +ij_java_class_count_to_use_import_on_demand = 999 ij_java_class_names_in_javadoc = 1 ij_java_deconstruction_list_wrap = normal ij_java_do_not_indent_top_level_class_members = false @@ -153,7 +153,7 @@ ij_java_method_parameters_right_paren_on_new_line = false ij_java_method_parameters_wrap = off ij_java_modifier_list_wrap = false ij_java_multi_catch_types_wrap = normal -ij_java_names_count_to_use_import_on_demand = 3 +ij_java_names_count_to_use_import_on_demand = 999 ij_java_new_line_after_lparen_in_annotation = false ij_java_new_line_after_lparen_in_deconstruction_pattern = true ij_java_new_line_after_lparen_in_record_header = false diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml index 521907dd..d2650872 100644 --- a/.idea/copyright/profiles_settings.xml +++ b/.idea/copyright/profiles_settings.xml @@ -1,3 +1,7 @@ - + + + + + \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java index 1ef9ed0a..24c4d125 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java @@ -30,6 +30,7 @@ import com.alpsbte.plotsystem.core.holograms.HologramConfiguration; import com.alpsbte.plotsystem.core.holograms.HologramRegister; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; @@ -48,6 +49,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N try { plugin.reloadConfig(); + LangUtil.getInstance().reloadFiles(); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully reloaded config!")); DecentHologramDisplay.activeDisplays.forEach(leaderboard -> leaderboard.setLocation(HologramRegister diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 5db8db3f..28f47f57 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -25,7 +25,6 @@ package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -33,15 +32,15 @@ import com.alpsbte.plotsystem.core.system.Country; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; -import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.CommandSender; -import org.yaml.snakeyaml.DumperOptions; import java.util.List; import java.util.Optional; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; public class CMD_Setup_City extends SubCommand { @@ -178,8 +177,8 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); return; } - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be the ID of the City & no description will be present!")); sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.CITY_PROJECT + "." + cityProjectId + " language config setting, otherwise the name will be undefined!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index 118c1cab..d51f417c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -24,7 +24,6 @@ package com.alpsbte.plotsystem.commands.admin.setup; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -32,7 +31,6 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.io.LangPaths; -import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.command.CommandSender; import java.util.Arrays; @@ -40,7 +38,8 @@ import java.util.Optional; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; public class CMD_Setup_Country extends SubCommand { @@ -142,16 +141,14 @@ public void onCommand(CommandSender sender, String[] args) { Continent continent; try { continent = Continent.fromDatabase(args[2].toUpperCase()); + if (continent == null) { + continent = Continent.valueOf(args[2].toUpperCase()); + } } catch (IllegalArgumentException e) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Unknown continent! " + Arrays.toString(Continent.values()))); return; } - if (continent == null) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Unknown continent! " + Arrays.toString(Continent.values()))); - return; - } - String material = args[3]; String customModelData = args.length > 4 ? args[4] : null; @@ -161,7 +158,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added country!")); - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.COUNTRY + "." + code + " language config setting, otherwise the name will be the ID of the Country & no description will be present!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Edit the " + LangPaths.Database.COUNTRY + "." + code + " language config setting, otherwise name & id will be undefined!")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 1bd10227..5b7419d6 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -59,6 +59,7 @@ import java.sql.SQLException; import java.time.LocalDateTime; import java.util.HashSet; +import java.util.Locale; import java.util.Objects; import java.util.Random; import java.util.Set; @@ -66,7 +67,14 @@ import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.TEXT_HIGHLIGHT_END; import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.TEXT_HIGHLIGHT_START; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_RED; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class Utils { @@ -109,7 +117,7 @@ public static ItemStack getConfiguredItem(@NotNull String material, Object custo String headId = material.substring(material.indexOf("(") + 1, material.lastIndexOf(")")); base = AlpsHeadUtils.getCustomHead(headId); } else { - Material mat = Material.getMaterial(material); + Material mat = Material.getMaterial(material.toUpperCase(Locale.ROOT)); base = new ItemStack(mat == null ? Material.BARRIER : mat); } ItemBuilder builder = new ItemBuilder(base); From 2727601782406abb852a6ab4bd835f240b4de63a Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 14 Jul 2025 22:03:31 +0200 Subject: [PATCH 131/175] =?UTF-8?q?build:=20=F0=9F=91=B7=20setup=20github?= =?UTF-8?q?=20build=20workflow?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- .github/workflows/maven-build.yml | 38 +++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 .github/workflows/maven-build.yml diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml new file mode 100644 index 00000000..4bc349cc --- /dev/null +++ b/.github/workflows/maven-build.yml @@ -0,0 +1,38 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Java CI with Maven + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn clean package + - run: mkdir staging && cp target/*.jar staging + - uses: actions/upload-artifact@v4 + with: + name: Package + path: staging + + # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive + - name: Update dependency graph + uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 From 7628875a8af8c1d9012291b312ad461fbef25a60 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sat, 19 Jul 2025 15:29:58 +0200 Subject: [PATCH 132/175] =?UTF-8?q?fix(plot-utils):=20=F0=9F=A9=B9=20delay?= =?UTF-8?q?=20timed=20messages=20so=20no=20duplicated=20for=20unfinished?= =?UTF-8?q?=20plot=20notify?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also remove & cancel the Task when the Player disconnects. Signed-off-by: Zoriot --- .../plotsystem/core/EventListener.java | 15 +++++++++++-- .../core/system/plot/utils/PlotUtils.java | 21 ++++++++++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index 1f1d5b15..e5cbe9ff 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -74,7 +74,13 @@ import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -86,7 +92,9 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class EventListener implements Listener { @@ -156,6 +164,9 @@ public void onPlayerQuitEvent(@NotNull PlayerQuitEvent event) { if (plotWorld != null && !plotWorld.getWorldName().toLowerCase(Locale.ROOT).startsWith("t-")) plotWorld.unloadWorld(false); }, 60L); + + PlotUtils.plotReminder.get(event.getPlayer().getUniqueId()).cancel(); + PlotUtils.plotReminder.remove(event.getPlayer().getUniqueId()); } @EventHandler diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 6838ce05..7d13212f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -74,6 +74,7 @@ import org.bukkit.World; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -86,17 +87,28 @@ import java.nio.file.Paths; import java.text.DecimalFormat; import java.time.LocalDate; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; public final class PlotUtils { private PlotUtils() {} private static final String MSG_LINE = "--------------------------"; + public static final Map plotReminder = new HashMap<>(); /** * Returns the plot that the player is currently standing on or next to. @@ -336,7 +348,10 @@ public static void informPlayerAboutUnfinishedPlots(@NotNull Player player, Buil public static void startUnfinishedPlotReminderTimer(Player player) { int interval = PlotSystem.getPlugin().getConfig().getInt(ConfigPaths.UNFINISHED_REMINDER_INTERVAL); if (interval == -1) return; - Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), () -> informPlayerAboutUnfinishedPlots(player, Builder.byUUID(player.getUniqueId())), 0L, 20L * 60 * interval); + plotReminder.put(player.getUniqueId(), Bukkit.getScheduler().runTaskTimerAsynchronously(PlotSystem.getPlugin(), + () -> informPlayerAboutUnfinishedPlots(player, Builder.byUUID(player.getUniqueId())), + 20L * 60 * interval, + 20L * 60 * interval)); } public static final class Actions { From 793b93535a3c9d404a34ed6c69e673dd0673bbd3 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sat, 19 Jul 2025 19:23:03 +0200 Subject: [PATCH 133/175] =?UTF-8?q?build:=20=F0=9F=92=9A=20update=20alps?= =?UTF-8?q?=20repo=20deps=20to=20fix=20build?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Zoriot --- pom.xml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index a06d7d4a..236f6f7b 100644 --- a/pom.xml +++ b/pom.xml @@ -110,7 +110,7 @@ com.alpsbte canvas - 1.1 + 1.3 compile @@ -142,7 +142,7 @@ com.alpsbte.alpslib alpslib-utils - 1.3.4 + 1.3.5 compile @@ -175,13 +175,13 @@ li.cinnazeyy LangLibs-API - 1.5 + 1.5.1 provided commons-io commons-io - 2.17.0 + 2.17.0 provided From 45a26197eeb76f76d6f2e1be51cc7a98d080ddfd Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 28 Jul 2025 22:58:26 +0200 Subject: [PATCH 134/175] prevent legacy plot loading and set clearArea to false on completedSchematic loading --- .../com/alpsbte/plotsystem/commands/review/CMD_Review.java | 5 +++++ .../com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java | 5 +++++ .../core/system/plot/generator/DefaultPlotGenerator.java | 3 ++- 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 6751eaa1..2b02b250 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -82,6 +82,11 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_LOAD_LEGACY_PLOT))); + return; + } + Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 09a9ba32..10ffa1ac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -28,6 +28,7 @@ import com.alpsbte.alpslib.utils.item.LoreBuilder; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.system.Builder; +import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; @@ -144,6 +145,10 @@ protected void setItemClickEventsAsync() { // Set click event for teleport to plot item getMenu().getSlot(hasReview ? 12 : 13).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); + if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(clickPlayer, LangPaths.Message.Error.CANNOT_LOAD_LEGACY_PLOT))); + return; + } plot.getWorld().teleportPlayer(clickPlayer); }); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 6ada921c..434df2c5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -97,8 +97,9 @@ protected void generateOutlines() throws IOException, WorldEditException { if (plot instanceof Plot) { byte[] completedSchematic = ((Plot) plot).getCompletedSchematic(); if (completedSchematic != null) { + PlotSystem.getPlugin().getComponentLogger().info("Found completed schematic, pasting only that."); Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); - pasteSchematic(airMask, completedSchematic, world, true); + pasteSchematic(airMask, completedSchematic, world, false); } else super.generateOutlines(); } else super.generateOutlines(); From 7565b4e4a3602149cfaf536050e6dfe0e323eb4a Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Sat, 2 Aug 2025 16:22:40 +0200 Subject: [PATCH 135/175] fix createBuilder method always returning false and minor cosmetic fixes --- .../plotsystem/core/database/providers/BuilderProvider.java | 3 +-- .../java/com/alpsbte/plotsystem/core/system/CityProject.java | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 6f114997..5e111df6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -89,12 +89,11 @@ public boolean addBuilderIfNotExists(UUID uuid, String name) { ResultSet rs = ps.executeQuery(); if (rs.next()) return true; // builder already exists - SqlHelper.runQuery(qInsert, ps.getConnection(), insertStmt -> { + return SqlHelper.runQuery(qInsert, ps.getConnection(), insertStmt -> { insertStmt.setString(1, uuid.toString()); insertStmt.setString(2, name); return insertStmt.executeUpdate() > 0; // insert new builder }); - return false; }))); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index 24cb40ea..b407f3a4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -116,7 +116,7 @@ public boolean setBuildTeam(int buildTeamId) { public List getDescriptionComponents(Player player) { ArrayList descriptionLines = new ArrayList<>(); - for (String line : getDescription(player).split("%newline%")) descriptionLines.add(text(line)); + for (String line : getDescription(player).split("%newline%")) descriptionLines.add(text(line, GRAY)); return descriptionLines; } From e15df1bd90076d9891ee7547d566dd70a749def7 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 25 Aug 2025 01:20:30 +0200 Subject: [PATCH 136/175] =?UTF-8?q?build:=20=F0=9F=91=B7=20migrate=20proje?= =?UTF-8?q?ct=20from=20Maven=20to=20Gradle=20and=20update=20build=20config?= =?UTF-8?q?uration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/build.yml | 49 +++++ .github/workflows/maven-build.yml | 38 ---- .gitignore | 208 +++++++++++++++++--- .idea/copyright/profiles_settings.xml | 4 +- .idea/scopes/Java.xml | 3 + .idea/vcs.xml | 7 + build.gradle.kts | 112 +++++++++++ gradle.properties | 3 + gradle/libs.versions.toml | 38 ++++ gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 43764 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 233 +++++++++++++++++++++++ gradlew.bat | 94 +++++++++ pom.xml | 24 +-- settings.gradle.kts | 1 + src/main/resources/plugin.yml | 3 +- 16 files changed, 731 insertions(+), 93 deletions(-) create mode 100644 .github/workflows/build.yml delete mode 100644 .github/workflows/maven-build.yml create mode 100644 .idea/scopes/Java.xml create mode 100644 .idea/vcs.xml create mode 100644 build.gradle.kts create mode 100644 gradle.properties create mode 100644 gradle/libs.versions.toml create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat create mode 100644 settings.gradle.kts diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..c7b829e0 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,49 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle + +name: Java CI with Gradle + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 # full history + fetch-tags: true # grab your tags + # Make sure we check out by branch name, not just SHA: + ref: ${{ github.event_name == 'pull_request' && github.head_ref || github.ref_name }} + + - name: Set up JDK 21 + uses: actions/setup-java@v5 + with: + java-version: '21' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + + - name: Build with Gradle Wrapper + run: ./gradlew clean build + + - uses: actions/upload-artifact@v4 + with: + name: Staging-Build + path: build/libs + compression-level: '9' diff --git a/.github/workflows/maven-build.yml b/.github/workflows/maven-build.yml deleted file mode 100644 index 4bc349cc..00000000 --- a/.github/workflows/maven-build.yml +++ /dev/null @@ -1,38 +0,0 @@ -# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -name: Java CI with Maven - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 21 - uses: actions/setup-java@v4 - with: - java-version: '21' - distribution: 'temurin' - cache: maven - - name: Build with Maven - run: mvn clean package - - run: mkdir staging && cp target/*.jar staging - - uses: actions/upload-artifact@v4 - with: - name: Package - path: staging - - # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive - - name: Update dependency graph - uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 diff --git a/.gitignore b/.gitignore index 621f439f..11ea8148 100644 --- a/.gitignore +++ b/.gitignore @@ -1,34 +1,184 @@ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar -*.xml +# Created by https://www.toptal.com/developers/gitignore/api/intellij,gradle,maven +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij,gradle,maven + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +.idea/artifacts +.idea/compiler.xml +.idea/jarRepositories.xml +.idea/modules.xml +.idea/*.iml +.idea/modules *.iml +*.ipr -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* +# CMake +cmake-build-*/ -# Maven -.classpath -.project -.settings/ +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +.idea/misc.xml +# *.ipr + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Maven ### target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# Eclipse m2e generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +# JDT-specific (Eclipse Java Development Tools) + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/intellij,gradle,maven + +# Created by https://www.toptal.com/developers/gitignore/api/git +# Edit at https://www.toptal.com/developers/gitignore?templates=git + +### Git ### +# Created by git for backups. To disable backups in Git: +# $ git config --global mergetool.keepBackup false +*.orig + +# Created by git when using merge tools for conflicts +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +# End of https://www.toptal.com/developers/gitignore/api/git + +# Custom -# .idea -.idea/ \ No newline at end of file +/.idea/git_toolbox_prj.xml +/.idea/.name diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml index d2650872..dbbfe86e 100644 --- a/.idea/copyright/profiles_settings.xml +++ b/.idea/copyright/profiles_settings.xml @@ -1,7 +1,7 @@ - + - + \ No newline at end of file diff --git a/.idea/scopes/Java.xml b/.idea/scopes/Java.xml new file mode 100644 index 00000000..bc417ab6 --- /dev/null +++ b/.idea/scopes/Java.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..83067447 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 00000000..880b3312 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,112 @@ +plugins { + java + id("com.palantir.git-version") version "4.0.0" + id("com.gradleup.shadow") version "9.0.2" +} + +repositories { + // mavenLocal() // NEVER use in Production/Commits! + maven { + url = uri("https://jitpack.io") + } + + maven { + url = uri("https://repo.papermc.io/repository/maven-public/") + } + + maven { + url = uri("https://mvn.alps-bte.com/repository/alps-bte/") + } + + maven { + url = uri("https://repo.fancyplugins.de/releases") + } + + maven { + url = uri("https://maven.enginehub.org/repo/") + } + + maven { + url = uri("https://repo.onarandombox.com/content/groups/public/") + } + + maven { + url = uri("https://repo.codemc.io/repository/maven-public/") + } + + maven { + url = uri("https://repo.maven.apache.org/maven2/") + } +} + +dependencies { + implementation(libs.com.alpsbte.canvas) + implementation(libs.com.alpsbte.alpslib.alpslib.io) + implementation(libs.com.alpsbte.alpslib.alpslib.hologram) + implementation(libs.com.alpsbte.alpslib.alpslib.utils) + implementation(libs.org.mariadb.jdbc.mariadb.java.client) + implementation(libs.com.zaxxer.hikaricp) + compileOnly(libs.io.papermc.paper.paper.api) + compileOnly(libs.com.fastasyncworldedit.fastasyncworldedit.core) + compileOnly(libs.com.sk89q.worldguard.worldguard.bukkit) + compileOnly(libs.com.onarandombox.multiversecore.multiverse.core) + compileOnly(libs.com.github.fierioziy.particlenativeapi.particlenativeapi.plugin) + compileOnly(libs.com.arcaniax.headdatabase.api) + compileOnly(libs.com.github.decentsoftware.eu.decentholograms) + compileOnly(libs.de.oliver.fancynpcs) + compileOnly(libs.li.cinnazeyy.langlibs.api) + compileOnly(libs.commons.io.commons.io) +} + +val versionDetails: groovy.lang.Closure by extra +val details = versionDetails() + +group = "com.alpsbte" +version = "5.0.0" + "-" + details.branchName.replace( + "/", + "-" +) + "-" + details.commitDistance + "-" + details.gitHash + "-SNAPSHOT" +description = "An easy to use building system for the BuildTheEarth project." +java.sourceCompatibility = JavaVersion.VERSION_21 + +tasks.withType { + options.encoding = "UTF-8" +} + +tasks.withType { + options.encoding = "UTF-8" +} + +tasks.shadowJar { + // Exclude annotation classes (e.g. org.jetbrains.annotations) + exclude("org/jetbrains/annotations/**") + // Exclude slf4j classes + exclude("org/slf4j/**") + exclude("META-INF/**") + archiveClassifier = "" + enableAutoRelocation = true + relocationPrefix = "alpsplotsystem.libs." +} + +tasks.assemble { + dependsOn(tasks.shadowJar) // Ensure that the shadowJar task runs before the build task +} + +tasks.jar { + enabled = false // Disable the default jar task since we are using shadowJar +} + +tasks.processResources { + // work around IDEA-296490 + duplicatesStrategy = DuplicatesStrategy.INCLUDE + with(copySpec { + from("src/main/resources/plugin.yml") { + expand( + mapOf( + "version" to version, + "description" to description + ) + ) + } + }) +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..e19f37c1 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +org.gradle.configuration-cache=true + diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000..fed10bda --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,38 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +com-alpsbte-alpslib-alpslib-hologram = "1.1.1" +com-alpsbte-alpslib-alpslib-io = "1.2.0" +com-alpsbte-alpslib-alpslib-utils = "1.3.5" +com-alpsbte-canvas = "1.3" +com-arcaniax-headdatabase-api = "1.3.2" +com-fastasyncworldedit-fastasyncworldedit-core = "2.12.1" +com-github-decentsoftware-eu-decentholograms = "2.9.2" +com-github-fierioziy-particlenativeapi-particlenativeapi-plugin = "3.3.2" +com-onarandombox-multiversecore-multiverse-core = "4.3.1" +com-sk89q-worldguard-worldguard-bukkit = "7.1.0-SNAPSHOT" +com-zaxxer-hikaricp = "6.3.0" +commons-io-commons-io = "2.17.0" +de-oliver-fancynpcs = "2.4.0" +io-papermc-paper-paper-api = "1.21.4-R0.1-SNAPSHOT" +li-cinnazeyy-langlibs-api = "1.5.1" +org-mariadb-jdbc-mariadb-java-client = "2.7.4" + +[libraries] +com-alpsbte-alpslib-alpslib-hologram = { module = "com.alpsbte.alpslib:alpslib-hologram", version.ref = "com-alpsbte-alpslib-alpslib-hologram" } +com-alpsbte-alpslib-alpslib-io = { module = "com.alpsbte.alpslib:alpslib-io", version.ref = "com-alpsbte-alpslib-alpslib-io" } +com-alpsbte-alpslib-alpslib-utils = { module = "com.alpsbte.alpslib:alpslib-utils", version.ref = "com-alpsbte-alpslib-alpslib-utils" } +com-alpsbte-canvas = { module = "com.alpsbte:canvas", version.ref = "com-alpsbte-canvas" } +com-arcaniax-headdatabase-api = { module = "com.arcaniax:HeadDatabase-API", version.ref = "com-arcaniax-headdatabase-api" } +com-fastasyncworldedit-fastasyncworldedit-core = { module = "com.fastasyncworldedit:FastAsyncWorldEdit-Core", version.ref = "com-fastasyncworldedit-fastasyncworldedit-core" } +com-github-decentsoftware-eu-decentholograms = { module = "com.github.decentsoftware-eu:decentholograms", version.ref = "com-github-decentsoftware-eu-decentholograms" } +com-github-fierioziy-particlenativeapi-particlenativeapi-plugin = { module = "com.github.fierioziy.particlenativeapi:ParticleNativeAPI-plugin", version.ref = "com-github-fierioziy-particlenativeapi-particlenativeapi-plugin" } +com-onarandombox-multiversecore-multiverse-core = { module = "com.onarandombox.multiversecore:Multiverse-Core", version.ref = "com-onarandombox-multiversecore-multiverse-core" } +com-sk89q-worldguard-worldguard-bukkit = { module = "com.sk89q.worldguard:worldguard-bukkit", version.ref = "com-sk89q-worldguard-worldguard-bukkit" } +com-zaxxer-hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "com-zaxxer-hikaricp" } +commons-io-commons-io = { module = "commons-io:commons-io", version.ref = "commons-io-commons-io" } +de-oliver-fancynpcs = { module = "de.oliver:FancyNpcs", version.ref = "de-oliver-fancynpcs" } +io-papermc-paper-paper-api = { module = "io.papermc.paper:paper-api", version.ref = "io-papermc-paper-paper-api" } +li-cinnazeyy-langlibs-api = { module = "li.cinnazeyy:LangLibs-API", version.ref = "li-cinnazeyy-langlibs-api" } +org-mariadb-jdbc-mariadb-java-client = { module = "org.mariadb.jdbc:mariadb-java-client", version.ref = "org-mariadb-jdbc-mariadb-java-client" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..1b33c55baabb587c669f562ae36f953de2481846 GIT binary patch literal 43764 zcma&OWmKeVvL#I6?i3D%6z=Zs?ofE*?rw#G$eqJB ziT4y8-Y@s9rkH0Tz>ll(^xkcTl)CY?rS&9VNd66Yc)g^6)JcWaY(5$5gt z8gr3SBXUTN;~cBgz&})qX%#!Fxom2Yau_`&8)+6aSN7YY+pS410rRUU*>J}qL0TnJ zRxt*7QeUqTh8j)Q&iavh<}L+$Jqz))<`IfKussVk%%Ah-Ti?Eo0hQH!rK%K=#EAw0 zwq@@~XNUXRnv8$;zv<6rCRJ6fPD^hfrh;0K?n z=p!u^3xOgWZ%f3+?+>H)9+w^$Tn1e;?UpVMJb!!;f)`6f&4|8mr+g)^@x>_rvnL0< zvD0Hu_N>$(Li7|Jgu0mRh&MV+<}`~Wi*+avM01E)Jtg=)-vViQKax!GeDc!xv$^mL z{#OVBA$U{(Zr8~Xm|cP@odkHC*1R8z6hcLY#N@3E-A8XEvpt066+3t9L_6Zg6j@9Q zj$$%~yO-OS6PUVrM2s)(T4#6=JpI_@Uz+!6=GdyVU?`!F=d;8#ZB@(5g7$A0(`eqY z8_i@3w$0*es5mrSjhW*qzrl!_LQWs4?VfLmo1Sd@Ztt53+etwzAT^8ow_*7Jp`Y|l z*UgSEwvxq+FYO!O*aLf-PinZYne7Ib6ny3u>MjQz=((r3NTEeU4=-i0LBq3H-VJH< z^>1RE3_JwrclUn9vb7HcGUaFRA0QHcnE;6)hnkp%lY1UII#WPAv?-;c?YH}LWB8Nl z{sx-@Z;QxWh9fX8SxLZk8;kMFlGD3Jc^QZVL4nO)1I$zQwvwM&_!kW+LMf&lApv#< zur|EyC|U@5OQuph$TC_ZU`{!vJp`13e9alaR0Dbn5ikLFH7>eIz4QbV|C=%7)F=qo z_>M&5N)d)7G(A%c>}UCrW!Ql_6_A{?R7&CL`;!KOb3 z8Z=$YkV-IF;c7zs{3-WDEFJzuakFbd*4LWd<_kBE8~BFcv}js_2OowRNzWCtCQ6&k z{&~Me92$m*@e0ANcWKuz)?YjB*VoSTx??-3Cc0l2U!X^;Bv@m87eKHukAljrD54R+ zE;@_w4NPe1>3`i5Qy*3^E9x#VB6?}v=~qIprrrd5|DFkg;v5ixo0IsBmik8=Y;zv2 z%Bcf%NE$a44bk^`i4VwDLTbX=q@j9;JWT9JncQ!+Y%2&HHk@1~*L8-{ZpY?(-a9J-1~<1ltr9i~D9`P{XTIFWA6IG8c4;6bFw*lzU-{+?b&%OcIoCiw00n>A1ra zFPE$y@>ebbZlf(sN_iWBzQKDV zmmaLX#zK!@ZdvCANfwV}9@2O&w)!5gSgQzHdk2Q`jG6KD7S+1R5&F)j6QTD^=hq&7 zHUW+r^da^%V(h(wonR(j?BOiC!;y=%nJvz?*aW&5E87qq;2z`EI(f zBJNNSMFF9U{sR-af5{IY&AtoGcoG)Iq-S^v{7+t0>7N(KRoPj;+2N5;9o_nxIGjJ@ z7bYQK)bX)vEhy~VL%N6g^NE@D5VtV+Q8U2%{ji_=6+i^G%xeskEhH>Sqr194PJ$fB zu1y^){?9Vkg(FY2h)3ZHrw0Z<@;(gd_dtF#6y_;Iwi{yX$?asr?0N0_B*CifEi7<6 zq`?OdQjCYbhVcg+7MSgIM|pJRu~`g?g3x?Tl+V}#$It`iD1j+!x+!;wS0+2e>#g?Z z*EA^k7W{jO1r^K~cD#5pamp+o@8&yw6;%b|uiT?{Wa=4+9<}aXWUuL#ZwN1a;lQod zW{pxWCYGXdEq9qAmvAB904}?97=re$>!I%wxPV#|f#@A*Y=qa%zHlDv^yWbR03%V0 zprLP+b(#fBqxI%FiF*-n8HtH6$8f(P6!H3V^ysgd8de-N(@|K!A< z^qP}jp(RaM9kQ(^K(U8O84?D)aU(g?1S8iWwe)gqpHCaFlJxb*ilr{KTnu4_@5{K- z)n=CCeCrPHO0WHz)dDtkbZfUfVBd?53}K>C5*-wC4hpDN8cGk3lu-ypq+EYpb_2H; z%vP4@&+c2p;thaTs$dc^1CDGlPG@A;yGR5@$UEqk6p58qpw#7lc<+W(WR;(vr(D>W z#(K$vE#uBkT=*q&uaZwzz=P5mjiee6>!lV?c}QIX%ZdkO1dHg>Fa#xcGT6~}1*2m9 zkc7l3ItD6Ie~o_aFjI$Ri=C!8uF4!Ky7iG9QTrxVbsQroi|r)SAon#*B*{}TB-?=@ z8~jJs;_R2iDd!$+n$%X6FO&PYS{YhDAS+U2o4su9x~1+U3z7YN5o0qUK&|g^klZ6X zj_vrM5SUTnz5`*}Hyts9ADwLu#x_L=nv$Z0`HqN`Zo=V>OQI)fh01n~*a%01%cx%0 z4LTFVjmW+ipVQv5rYcn3;d2o4qunWUY!p+?s~X~(ost@WR@r@EuDOSs8*MT4fiP>! zkfo^!PWJJ1MHgKS2D_hc?Bs?isSDO61>ebl$U*9*QY(b=i&rp3@3GV@z>KzcZOxip z^dzA~44;R~cnhWz7s$$v?_8y-k!DZys}Q?4IkSyR!)C0j$(Gm|t#e3|QAOFaV2}36 z?dPNY;@I=FaCwylc_;~kXlZsk$_eLkNb~TIl8QQ`mmH&$*zwwR8zHU*sId)rxHu*K z;yZWa8UmCwju%aSNLwD5fBl^b0Ux1%q8YR*uG`53Mi<`5uA^Dc6Ync)J3N7;zQ*75)hf%a@{$H+%S?SGT)ks60)?6j$ zspl|4Ad6@%-r1t*$tT(en!gIXTUDcsj?28ZEzz)dH)SV3bZ+pjMaW0oc~rOPZP@g! zb9E+ndeVO_Ib9c_>{)`01^`ZS198 z)(t=+{Azi11$eu%aU7jbwuQrO`vLOixuh~%4z@mKr_Oc;F%Uq01fA)^W&y+g16e?rkLhTxV!EqC%2}sx_1u7IBq|}Be&7WI z4I<;1-9tJsI&pQIhj>FPkQV9{(m!wYYV@i5h?A0#BN2wqlEwNDIq06|^2oYVa7<~h zI_OLan0Do*4R5P=a3H9`s5*>xU}_PSztg`+2mv)|3nIy=5#Z$%+@tZnr> zLcTI!Mxa`PY7%{;KW~!=;*t)R_sl<^b>eNO@w#fEt(tPMg_jpJpW$q_DoUlkY|uo> z0-1{ouA#;t%spf*7VjkK&$QrvwUERKt^Sdo)5@?qAP)>}Y!h4(JQ!7{wIdkA+|)bv z&8hBwoX4v|+fie}iTslaBX^i*TjwO}f{V)8*!dMmRPi%XAWc8<_IqK1jUsApk)+~R zNFTCD-h>M5Y{qTQ&0#j@I@tmXGj%rzhTW5%Bkh&sSc=$Fv;M@1y!zvYG5P2(2|(&W zlcbR1{--rJ&s!rB{G-sX5^PaM@3EqWVz_y9cwLR9xMig&9gq(voeI)W&{d6j1jh&< zARXi&APWE1FQWh7eoZjuP z;vdgX>zep^{{2%hem;e*gDJhK1Hj12nBLIJoL<=0+8SVEBx7!4Ea+hBY;A1gBwvY<)tj~T=H`^?3>zeWWm|LAwo*S4Z%bDVUe z6r)CH1H!(>OH#MXFJ2V(U(qxD{4Px2`8qfFLG+=a;B^~Te_Z!r3RO%Oc#ZAHKQxV5 zRYXxZ9T2A%NVJIu5Pu7!Mj>t%YDO$T@M=RR(~mi%sv(YXVl`yMLD;+WZ{vG9(@P#e zMo}ZiK^7^h6TV%cG+;jhJ0s>h&VERs=tuZz^Tlu~%d{ZHtq6hX$V9h)Bw|jVCMudd zwZ5l7In8NT)qEPGF$VSKg&fb0%R2RnUnqa){)V(X(s0U zkCdVZe6wy{+_WhZh3qLp245Y2RR$@g-!9PjJ&4~0cFSHMUn=>dapv)hy}|y91ZWTV zCh=z*!S3_?`$&-eZ6xIXUq8RGl9oK0BJw*TdU6A`LJqX9eS3X@F)g$jLkBWFscPhR zpCv8#KeAc^y>>Y$k^=r|K(DTC}T$0#jQBOwB#@`P6~*IuW_8JxCG}J4va{ zsZzt}tt+cv7=l&CEuVtjD6G2~_Meh%p4RGuY?hSt?(sreO_F}8r7Kp$qQdvCdZnDQ zxzc*qchE*E2=WK)^oRNa>Ttj`fpvF-JZ5tu5>X1xw)J@1!IqWjq)ESBG?J|ez`-Tc zi5a}GZx|w-h%5lNDE_3ho0hEXMoaofo#Z;$8|2;EDF&*L+e$u}K=u?pb;dv$SXeQM zD-~7P0i_`Wk$#YP$=hw3UVU+=^@Kuy$>6?~gIXx636jh{PHly_a2xNYe1l60`|y!7 z(u%;ILuW0DDJ)2%y`Zc~hOALnj1~txJtcdD#o4BCT68+8gZe`=^te6H_egxY#nZH&P*)hgYaoJ^qtmpeea`35Fw)cy!w@c#v6E29co8&D9CTCl%^GV|X;SpneSXzV~LXyRn-@K0Df z{tK-nDWA!q38M1~`xUIt_(MO^R(yNY#9@es9RQbY@Ia*xHhD&=k^T+ zJi@j2I|WcgW=PuAc>hs`(&CvgjL2a9Rx zCbZyUpi8NWUOi@S%t+Su4|r&UoU|ze9SVe7p@f1GBkrjkkq)T}X%Qo1g!SQ{O{P?m z-OfGyyWta+UCXH+-+(D^%kw#A1-U;?9129at7MeCCzC{DNgO zeSqsV>W^NIfTO~4({c}KUiuoH8A*J!Cb0*sp*w-Bg@YfBIPZFH!M}C=S=S7PLLcIG zs7K77g~W)~^|+mx9onzMm0qh(f~OsDTzVmRtz=aZTllgR zGUn~_5hw_k&rll<4G=G+`^Xlnw;jNYDJz@bE?|r866F2hA9v0-8=JO3g}IHB#b`hy zA42a0>{0L7CcabSD+F7?pGbS1KMvT{@1_@k!_+Ki|5~EMGt7T%u=79F)8xEiL5!EJ zzuxQ`NBliCoJMJdwu|);zRCD<5Sf?Y>U$trQ-;xj6!s5&w=9E7)%pZ+1Nh&8nCCwM zv5>Ket%I?cxr3vVva`YeR?dGxbG@pi{H#8@kFEf0Jq6~K4>kt26*bxv=P&jyE#e$| zDJB_~imk^-z|o!2njF2hL*|7sHCnzluhJjwLQGDmC)Y9 zr9ZN`s)uCd^XDvn)VirMgW~qfn1~SaN^7vcX#K1G`==UGaDVVx$0BQnubhX|{e z^i0}>k-;BP#Szk{cFjO{2x~LjK{^Upqd&<+03_iMLp0$!6_$@TbX>8U-f*-w-ew1?`CtD_0y_Lo|PfKi52p?`5$Jzx0E8`M0 zNIb?#!K$mM4X%`Ry_yhG5k@*+n4||2!~*+&pYLh~{`~o(W|o64^NrjP?-1Lgu?iK^ zTX6u3?#$?R?N!{599vg>G8RGHw)Hx&=|g4599y}mXNpM{EPKKXB&+m?==R3GsIq?G zL5fH={=zawB(sMlDBJ+{dgb)Vx3pu>L=mDV0{r1Qs{0Pn%TpopH{m(By4;{FBvi{I z$}x!Iw~MJOL~&)p93SDIfP3x%ROjg}X{Sme#hiJ&Yk&a;iR}V|n%PriZBY8SX2*;6 z4hdb^&h;Xz%)BDACY5AUsV!($lib4>11UmcgXKWpzRL8r2Srl*9Y(1uBQsY&hO&uv znDNff0tpHlLISam?o(lOp#CmFdH<6HmA0{UwfU#Y{8M+7od8b8|B|7ZYR9f<#+V|ZSaCQvI$~es~g(Pv{2&m_rKSB2QQ zMvT}$?Ll>V+!9Xh5^iy3?UG;dF-zh~RL#++roOCsW^cZ&({6q|?Jt6`?S8=16Y{oH zp50I7r1AC1(#{b`Aq5cw>ypNggHKM9vBx!W$eYIzD!4KbLsZGr2o8>g<@inmS3*>J zx8oG((8f!ei|M@JZB`p7+n<Q}?>h249<`7xJ?u}_n;Gq(&km#1ULN87CeTO~FY zS_Ty}0TgQhV zOh3T7{{x&LSYGQfKR1PDIkP!WnfC1$l+fs@Di+d4O=eVKeF~2fq#1<8hEvpwuqcaH z4A8u~r^gnY3u6}zj*RHjk{AHhrrDqaj?|6GaVJbV%o-nATw}ASFr!f`Oz|u_QPkR# z0mDudY1dZRlk@TyQ?%Eti=$_WNFtLpSx9=S^be{wXINp%MU?a`F66LNU<c;0&ngifmP9i;bj6&hdGMW^Kf8e6ZDXbQD&$QAAMo;OQ)G zW(qlHh;}!ZP)JKEjm$VZjTs@hk&4{?@+NADuYrr!R^cJzU{kGc1yB?;7mIyAWwhbeA_l_lw-iDVi7wcFurf5 z#Uw)A@a9fOf{D}AWE%<`s1L_AwpZ?F!Vac$LYkp<#A!!`XKaDC{A%)~K#5z6>Hv@V zBEqF(D5?@6r3Pwj$^krpPDCjB+UOszqUS;b2n>&iAFcw<*im2(b3|5u6SK!n9Sg4I z0KLcwA6{Mq?p%t>aW0W!PQ>iUeYvNjdKYqII!CE7SsS&Rj)eIw-K4jtI?II+0IdGq z2WT|L3RL?;GtGgt1LWfI4Ka`9dbZXc$TMJ~8#Juv@K^1RJN@yzdLS8$AJ(>g!U9`# zx}qr7JWlU+&m)VG*Se;rGisutS%!6yybi%B`bv|9rjS(xOUIvbNz5qtvC$_JYY+c& za*3*2$RUH8p%pSq>48xR)4qsp!Q7BEiJ*`^>^6INRbC@>+2q9?x(h0bpc>GaNFi$K zPH$6!#(~{8@0QZk=)QnM#I=bDx5vTvjm$f4K}%*s+((H2>tUTf==$wqyoI`oxI7>C z&>5fe)Yg)SmT)eA(|j@JYR1M%KixxC-Eceknf-;N=jJTwKvk#@|J^&5H0c+%KxHUI z6dQbwwVx3p?X<_VRVb2fStH?HH zFR@Mp=qX%#L3XL)+$PXKV|o|#DpHAoqvj6uQKe@M-mnhCSou7Dj4YuO6^*V`m)1lf z;)@e%1!Qg$10w8uEmz{ENb$^%u}B;J7sDd zump}onoD#!l=agcBR)iG!3AF0-63%@`K9G(CzKrm$VJ{v7^O9Ps7Zej|3m= zVXlR&yW6=Y%mD30G@|tf=yC7-#L!16Q=dq&@beWgaIL40k0n% z)QHrp2Jck#evLMM1RGt3WvQ936ZC9vEje0nFMfvmOHVI+&okB_K|l-;|4vW;qk>n~ z+|kk8#`K?x`q>`(f6A${wfw9Cx(^)~tX7<#TpxR#zYG2P+FY~mG{tnEkv~d6oUQA+ z&hNTL=~Y@rF`v-RZlts$nb$3(OL1&@Y11hhL9+zUb6)SP!;CD)^GUtUpCHBE`j1te zAGud@miCVFLk$fjsrcpjsadP__yj9iEZUW{Ll7PPi<$R;m1o!&Xdl~R_v0;oDX2z^!&8}zNGA}iYG|k zmehMd1%?R)u6R#<)B)1oe9TgYH5-CqUT8N7K-A-dm3hbm_W21p%8)H{O)xUlBVb+iUR}-v5dFaCyfSd zC6Bd7=N4A@+Bna=!-l|*_(nWGDpoyU>nH=}IOrLfS+-d40&(Wo*dDB9nQiA2Tse$R z;uq{`X7LLzP)%Y9aHa4YQ%H?htkWd3Owv&UYbr5NUDAH^<l@Z0Cx%`N+B*i!!1u>D8%;Qt1$ zE5O0{-`9gdDxZ!`0m}ywH!;c{oBfL-(BH<&SQ~smbcobU!j49O^f4&IIYh~f+hK*M zZwTp%{ZSAhMFj1qFaOA+3)p^gnXH^=)`NTYgTu!CLpEV2NF=~-`(}7p^Eof=@VUbd z_9U|8qF7Rueg&$qpSSkN%%%DpbV?8E8ivu@ensI0toJ7Eas^jyFReQ1JeY9plb^{m z&eQO)qPLZQ6O;FTr*aJq=$cMN)QlQO@G&%z?BKUs1&I^`lq>=QLODwa`(mFGC`0H< zOlc*|N?B5&!U6BuJvkL?s1&nsi$*5cCv7^j_*l&$-sBmRS85UIrE--7eD8Gr3^+o? zqG-Yl4S&E;>H>k^a0GdUI(|n1`ws@)1%sq2XBdK`mqrNq_b4N{#VpouCXLzNvjoFv zo9wMQ6l0+FT+?%N(ka*;%m~(?338bu32v26!{r)|w8J`EL|t$}TA4q_FJRX5 zCPa{hc_I(7TGE#@rO-(!$1H3N-C0{R$J=yPCXCtGk{4>=*B56JdXU9cQVwB`6~cQZ zf^qK21x_d>X%dT!!)CJQ3mlHA@ z{Prkgfs6=Tz%63$6Zr8CO0Ak3A)Cv#@BVKr&aiKG7RYxY$Yx>Bj#3gJk*~Ps-jc1l z;4nltQwwT4@Z)}Pb!3xM?+EW0qEKA)sqzw~!C6wd^{03-9aGf3Jmt=}w-*!yXupLf z;)>-7uvWN4Unn8b4kfIza-X=x*e4n5pU`HtgpFFd))s$C@#d>aUl3helLom+RYb&g zI7A9GXLRZPl}iQS*d$Azxg-VgcUr*lpLnbPKUV{QI|bsG{8bLG<%CF( zMoS4pRDtLVYOWG^@ox^h8xL~afW_9DcE#^1eEC1SVSb1BfDi^@g?#f6e%v~Aw>@w- zIY0k+2lGWNV|aA*e#`U3=+oBDmGeInfcL)>*!w|*;mWiKNG6wP6AW4-4imN!W)!hE zA02~S1*@Q`fD*+qX@f3!2yJX&6FsEfPditB%TWo3=HA;T3o2IrjS@9SSxv%{{7&4_ zdS#r4OU41~GYMiib#z#O;zohNbhJknrPPZS6sN$%HB=jUnlCO_w5Gw5EeE@KV>soy z2EZ?Y|4RQDDjt5y!WBlZ(8M)|HP<0YyG|D%RqD+K#e7-##o3IZxS^wQ5{Kbzb6h(i z#(wZ|^ei>8`%ta*!2tJzwMv+IFHLF`zTU8E^Mu!R*45_=ccqI};Zbyxw@U%a#2}%f zF>q?SrUa_a4H9l+uW8JHh2Oob>NyUwG=QH~-^ZebU*R@67DcXdz2{HVB4#@edz?B< z5!rQH3O0>A&ylROO%G^fimV*LX7>!%re{_Sm6N>S{+GW1LCnGImHRoF@csnFzn@P0 zM=jld0z%oz;j=>c7mMwzq$B^2mae7NiG}%>(wtmsDXkWk{?BeMpTrIt3Mizq?vRsf zi_WjNp+61uV(%gEU-Vf0;>~vcDhe(dzWdaf#4mH3o^v{0EWhj?E?$5v02sV@xL0l4 zX0_IMFtQ44PfWBbPYN#}qxa%=J%dlR{O!KyZvk^g5s?sTNycWYPJ^FK(nl3k?z-5t z39#hKrdO7V(@!TU)LAPY&ngnZ1MzLEeEiZznn7e-jLCy8LO zu^7_#z*%I-BjS#Pg-;zKWWqX-+Ly$T!4`vTe5ZOV0j?TJVA*2?*=82^GVlZIuH%9s zXiV&(T(QGHHah=s&7e|6y?g+XxZGmK55`wGV>@1U)Th&=JTgJq>4mI&Av2C z)w+kRoj_dA!;SfTfkgMPO>7Dw6&1*Hi1q?54Yng`JO&q->^CX21^PrU^JU#CJ_qhV zSG>afB%>2fx<~g8p=P8Yzxqc}s@>>{g7}F!;lCXvF#RV)^fyYb_)iKVCz1xEq=fJ| z0a7DMCK*FuP=NM*5h;*D`R4y$6cpW-E&-i{v`x=Jbk_xSn@2T3q!3HoAOB`@5Vg6) z{PW|@9o!e;v1jZ2{=Uw6S6o{g82x6g=k!)cFSC*oemHaVjg?VpEmtUuD2_J^A~$4* z3O7HsbA6wxw{TP5Kk)(Vm?gKo+_}11vbo{Tp_5x79P~#F)ahQXT)tSH5;;14?s)On zel1J>1x>+7;g1Iz2FRpnYz;sD0wG9Q!vuzE9yKi3@4a9Nh1!GGN?hA)!mZEnnHh&i zf?#ZEN2sFbf~kV;>K3UNj1&vFhc^sxgj8FCL4v>EOYL?2uuT`0eDH}R zmtUJMxVrV5H{L53hu3#qaWLUa#5zY?f5ozIn|PkMWNP%n zWB5!B0LZB0kLw$k39=!akkE9Q>F4j+q434jB4VmslQ;$ zKiO#FZ`p|dKS716jpcvR{QJkSNfDVhr2%~eHrW;fU45>>snr*S8Vik-5eN5k*c2Mp zyxvX&_cFbB6lODXznHHT|rsURe2!swomtrqc~w5 zymTM8!w`1{04CBprR!_F{5LB+2_SOuZN{b*!J~1ZiPpP-M;);!ce!rOPDLtgR@Ie1 zPreuqm4!H)hYePcW1WZ0Fyaqe%l}F~Orr)~+;mkS&pOhP5Ebb`cnUt!X_QhP4_4p( z8YKQCDKGIy>?WIFm3-}Br2-N`T&FOi?t)$hjphB9wOhBXU#Hb+zm&We_-O)s(wc`2 z8?VsvU;J>Ju7n}uUb3s1yPx_F*|FlAi=Ge=-kN?1;`~6szP%$3B0|8Sqp%ebM)F8v zADFrbeT0cgE>M0DMV@_Ze*GHM>q}wWMzt|GYC%}r{OXRG3Ij&<+nx9;4jE${Fj_r* z`{z1AW_6Myd)i6e0E-h&m{{CvzH=Xg!&(bLYgRMO_YVd8JU7W+7MuGWNE=4@OvP9+ zxi^vqS@5%+#gf*Z@RVyU9N1sO-(rY$24LGsg1>w>s6ST^@)|D9>cT50maXLUD{Fzf zt~tp{OSTEKg3ZSQyQQ5r51){%=?xlZ54*t1;Ow)zLe3i?8tD8YyY^k%M)e`V*r+vL zPqUf&m)U+zxps+NprxMHF{QSxv}>lE{JZETNk1&F+R~bp{_T$dbXL2UGnB|hgh*p4h$clt#6;NO~>zuyY@C-MD@)JCc5XrYOt`wW7! z_ti2hhZBMJNbn0O-uTxl_b6Hm313^fG@e;RrhIUK9@# z+DHGv_Ow$%S8D%RB}`doJjJy*aOa5mGHVHz0e0>>O_%+^56?IkA5eN+L1BVCp4~m=1eeL zb;#G!#^5G%6Mw}r1KnaKsLvJB%HZL)!3OxT{k$Yo-XrJ?|7{s4!H+S2o?N|^Z z)+?IE9H7h~Vxn5hTis^3wHYuOU84+bWd)cUKuHapq=&}WV#OxHpLab`NpwHm8LmOo zjri+!k;7j_?FP##CpM+pOVx*0wExEex z@`#)K<-ZrGyArK;a%Km`^+We|eT+#MygHOT6lXBmz`8|lyZOwL1+b+?Z$0OhMEp3R z&J=iRERpv~TC=p2-BYLC*?4 zxvPs9V@g=JT0>zky5Poj=fW_M!c)Xxz1<=&_ZcL=LMZJqlnO1P^xwGGW*Z+yTBvbV z-IFe6;(k1@$1;tS>{%pXZ_7w+i?N4A2=TXnGf=YhePg8bH8M|Lk-->+w8Y+FjZ;L=wSGwxfA`gqSn)f(XNuSm>6Y z@|#e-)I(PQ^G@N`%|_DZSb4_pkaEF0!-nqY+t#pyA>{9^*I-zw4SYA1_z2Bs$XGUZbGA;VeMo%CezHK0lO={L%G)dI-+8w?r9iexdoB{?l zbJ}C?huIhWXBVs7oo{!$lOTlvCLZ_KN1N+XJGuG$rh<^eUQIqcI7^pmqhBSaOKNRq zrx~w^?9C?*&rNwP_SPYmo;J-#!G|{`$JZK7DxsM3N^8iR4vvn>E4MU&Oe1DKJvLc~ zCT>KLZ1;t@My zRj_2hI^61T&LIz)S!+AQIV23n1>ng+LUvzv;xu!4;wpqb#EZz;F)BLUzT;8UA1x*6vJ zicB!3Mj03s*kGV{g`fpC?V^s(=JG-k1EMHbkdP4P*1^8p_TqO|;!Zr%GuP$8KLxuf z=pv*H;kzd;P|2`JmBt~h6|GxdU~@weK5O=X&5~w$HpfO}@l-T7@vTCxVOwCkoPQv8 z@aV_)I5HQtfs7^X=C03zYmH4m0S!V@JINm6#(JmZRHBD?T!m^DdiZJrhKpBcur2u1 zf9e4%k$$vcFopK5!CC`;ww(CKL~}mlxK_Pv!cOsFgVkNIghA2Au@)t6;Y3*2gK=5d z?|@1a)-(sQ%uFOmJ7v2iG&l&m^u&^6DJM#XzCrF%r>{2XKyxLD2rgWBD;i(!e4InDQBDg==^z;AzT2z~OmV0!?Z z0S9pX$+E;w3WN;v&NYT=+G8hf=6w0E1$0AOr61}eOvE8W1jX%>&Mjo7&!ulawgzLH zbcb+IF(s^3aj12WSi#pzIpijJJzkP?JzRawnxmNDSUR#7!29vHULCE<3Aa#be}ie~d|!V+ z%l~s9Odo$G&fH!t!+`rUT0T9DulF!Yq&BfQWFZV1L9D($r4H(}Gnf6k3^wa7g5|Ws zj7%d`!3(0bb55yhC6@Q{?H|2os{_F%o=;-h{@Yyyn*V7?{s%Grvpe!H^kl6tF4Zf5 z{Jv1~yZ*iIWL_9C*8pBMQArfJJ0d9Df6Kl#wa}7Xa#Ef_5B7=X}DzbQXVPfCwTO@9+@;A^Ti6il_C>g?A-GFwA0#U;t4;wOm-4oS})h z5&on>NAu67O?YCQr%7XIzY%LS4bha9*e*4bU4{lGCUmO2UQ2U)QOqClLo61Kx~3dI zmV3*(P6F_Tr-oP%x!0kTnnT?Ep5j;_IQ^pTRp=e8dmJtI4YgWd0}+b2=ATkOhgpXe z;jmw+FBLE}UIs4!&HflFr4)vMFOJ19W4f2^W(=2)F%TAL)+=F>IE$=e=@j-*bFLSg z)wf|uFQu+!=N-UzSef62u0-C8Zc7 zo6@F)c+nZA{H|+~7i$DCU0pL{0Ye|fKLuV^w!0Y^tT$isu%i1Iw&N|tX3kwFKJN(M zXS`k9js66o$r)x?TWL}Kxl`wUDUpwFx(w4Yk%49;$sgVvT~n8AgfG~HUcDt1TRo^s zdla@6heJB@JV z!vK;BUMznhzGK6PVtj0)GB=zTv6)Q9Yt@l#fv7>wKovLobMV-+(8)NJmyF8R zcB|_K7=FJGGn^X@JdFaat0uhKjp3>k#^&xE_}6NYNG?kgTp>2Iu?ElUjt4~E-?`Du z?mDCS9wbuS%fU?5BU@Ijx>1HG*N?gIP+<~xE4u=>H`8o((cS5M6@_OK%jSjFHirQK zN9@~NXFx*jS{<|bgSpC|SAnA@I)+GB=2W|JJChLI_mx+-J(mSJ!b)uUom6nH0#2^(L@JBlV#t zLl?j54s`Y3vE^c_3^Hl0TGu*tw_n?@HyO@ZrENxA+^!)OvUX28gDSF*xFtQzM$A+O zCG=n#6~r|3zt=8%GuG} z<#VCZ%2?3Q(Ad#Y7GMJ~{U3>E{5e@z6+rgZLX{Cxk^p-7dip^d29;2N1_mm4QkASo z-L`GWWPCq$uCo;X_BmGIpJFBlhl<8~EG{vOD1o|X$aB9KPhWO_cKiU*$HWEgtf=fn zsO%9bp~D2c@?*K9jVN@_vhR03>M_8h!_~%aN!Cnr?s-!;U3SVfmhRwk11A^8Ns`@KeE}+ zN$H}a1U6E;*j5&~Og!xHdfK5M<~xka)x-0N)K_&e7AjMz`toDzasH+^1bZlC!n()crk9kg@$(Y{wdKvbuUd04N^8}t1iOgsKF zGa%%XWx@WoVaNC1!|&{5ZbkopFre-Lu(LCE5HWZBoE#W@er9W<>R=^oYxBvypN#x3 zq#LC8&q)GFP=5^-bpHj?LW=)-g+3_)Ylps!3^YQ{9~O9&K)xgy zMkCWaApU-MI~e^cV{Je75Qr7eF%&_H)BvfyKL=gIA>;OSq(y z052BFz3E(Prg~09>|_Z@!qj}@;8yxnw+#Ej0?Rk<y}4ghbD569B{9hSFr*^ygZ zr6j7P#gtZh6tMk6?4V$*Jgz+#&ug;yOr>=qdI#9U&^am2qoh4Jy}H2%a|#Fs{E(5r z%!ijh;VuGA6)W)cJZx+;9Bp1LMUzN~x_8lQ#D3+sL{be-Jyeo@@dv7XguJ&S5vrH` z>QxOMWn7N-T!D@1(@4>ZlL^y5>m#0!HKovs12GRav4z!>p(1~xok8+_{| z#Ae4{9#NLh#Vj2&JuIn5$d6t@__`o}umFo(n0QxUtd2GKCyE+erwXY?`cm*h&^9*8 zJ+8x6fRZI-e$CRygofIQN^dWysCxgkyr{(_oBwwSRxZora1(%(aC!5BTtj^+YuevI zx?)H#(xlALUp6QJ!=l9N__$cxBZ5p&7;qD3PsXRFVd<({Kh+mShFWJNpy`N@ab7?9 zv5=klvCJ4bx|-pvOO2-+G)6O?$&)ncA#Urze2rlBfp#htudhx-NeRnJ@u%^_bfw4o z4|{b8SkPV3b>Wera1W(+N@p9H>dc6{cnkh-sgr?e%(YkWvK+0YXVwk0=d`)}*47*B z5JGkEdVix!w7-<%r0JF~`ZMMPe;f0EQHuYHxya`puazyph*ZSb1mJAt^k4549BfS; zK7~T&lRb=W{s&t`DJ$B}s-eH1&&-wEOH1KWsKn0a(ZI+G!v&W4A*cl>qAvUv6pbUR z#(f#EKV8~hk&8oayBz4vaswc(?qw1vn`yC zZQDl2PCB-&Uu@g9ZQHhO+v(W0bNig{-k0;;`+wM@#@J)8r?qOYs#&vUna8ILxN7S{ zp1s41KnR8miQJtJtOr|+qk}wrLt+N*z#5o`TmD1)E&QD(Vh&pjZJ_J*0!8dy_ z>^=@v=J)C`x&gjqAYu`}t^S=DFCtc0MkBU2zf|69?xW`Ck~(6zLD)gSE{7n~6w8j_ zoH&~$ED2k5-yRa0!r8fMRy z;QjBYUaUnpd}mf%iVFPR%Dg9!d>g`01m~>2s))`W|5!kc+_&Y>wD@@C9%>-lE`WB0 zOIf%FVD^cj#2hCkFgi-fgzIfOi+ya)MZK@IZhHT5FVEaSbv-oDDs0W)pA0&^nM0TW zmgJmd7b1R7b0a`UwWJYZXp4AJPteYLH>@M|xZFKwm!t3D3&q~av?i)WvAKHE{RqpD{{%OhYkK?47}+}` zrR2(Iv9bhVa;cDzJ%6ntcSbx7v7J@Y4x&+eWSKZ*eR7_=CVIUSB$^lfYe@g+p|LD{ zPSpQmxx@b$%d!05|H}WzBT4_cq?@~dvy<7s&QWtieJ9)hd4)$SZz}#H2UTi$CkFWW|I)v_-NjuH!VypONC=1`A=rm_jfzQ8Fu~1r8i{q-+S_j$ z#u^t&Xnfi5tZtl@^!fUJhx@~Cg0*vXMK}D{>|$#T*+mj(J_@c{jXBF|rm4-8%Z2o! z2z0o(4%8KljCm^>6HDK!{jI7p+RAPcty_~GZ~R_+=+UzZ0qzOwD=;YeZt*?3%UGdr z`c|BPE;yUbnyARUl&XWSNJ<+uRt%!xPF&K;(l$^JcA_CMH6)FZt{>6ah$|(9$2fc~ z=CD00uHM{qv;{Zk9FR0~u|3|Eiqv9?z2#^GqylT5>6JNZwKqKBzzQpKU2_pmtD;CT zi%Ktau!Y2Tldfu&b0UgmF(SSBID)15*r08eoUe#bT_K-G4VecJL2Pa=6D1K6({zj6 za(2Z{r!FY5W^y{qZ}08+h9f>EKd&PN90f}Sc0ejf%kB4+f#T8Q1=Pj=~#pi$U zp#5rMR%W25>k?<$;$x72pkLibu1N|jX4cWjD3q^Pk3js!uK6h7!dlvw24crL|MZs_ zb%Y%?Fyp0bY0HkG^XyS76Ts*|Giw{31LR~+WU5NejqfPr73Rp!xQ1mLgq@mdWncLy z%8}|nzS4P&`^;zAR-&nm5f;D-%yNQPwq4N7&yULM8bkttkD)hVU>h>t47`{8?n2&4 zjEfL}UEagLUYwdx0sB2QXGeRmL?sZ%J!XM`$@ODc2!y|2#7hys=b$LrGbvvjx`Iqi z&RDDm3YBrlKhl`O@%%&rhLWZ*ABFz2nHu7k~3@e4)kO3%$=?GEFUcCF=6-1n!x^vmu+Ai*amgXH+Rknl6U>#9w;A} zn2xanZSDu`4%%x}+~FG{Wbi1jo@wqBc5(5Xl~d0KW(^Iu(U3>WB@-(&vn_PJt9{1`e9Iic@+{VPc`vP776L*viP{wYB2Iff8hB%E3|o zGMOu)tJX!`qJ}ZPzq7>=`*9TmETN7xwU;^AmFZ-ckZjV5B2T09pYliaqGFY|X#E-8 z20b>y?(r-Fn5*WZ-GsK}4WM>@TTqsxvSYWL6>18q8Q`~JO1{vLND2wg@58OaU!EvT z1|o+f1mVXz2EKAbL!Q=QWQKDZpV|jznuJ}@-)1&cdo z^&~b4Mx{*1gurlH;Vhk5g_cM&6LOHS2 zRkLfO#HabR1JD4Vc2t828dCUG#DL}f5QDSBg?o)IYYi@_xVwR2w_ntlpAW0NWk$F1 z$If?*lP&Ka1oWfl!)1c3fl`g*lMW3JOn#)R1+tfwrs`aiFUgz3;XIJ>{QFxLCkK30 zNS-)#DON3yb!7LBHQJ$)4y%TN82DC2-9tOIqzhZ27@WY^<6}vXCWcR5iN{LN8{0u9 zNXayqD=G|e?O^*ms*4P?G%o@J1tN9_76e}E#66mr89%W_&w4n66~R;X_vWD(oArwj z4CpY`)_mH2FvDuxgT+akffhX0b_slJJ*?Jn3O3~moqu2Fs1oL*>7m=oVek2bnprnW zixkaIFU%+3XhNA@@9hyhFwqsH2bM|`P?G>i<-gy>NflhrN{$9?LZ1ynSE_Mj0rADF zhOz4FnK}wpLmQuV zgO4_Oz9GBu_NN>cPLA=`SP^$gxAnj;WjJnBi%Q1zg`*^cG;Q)#3Gv@c^j6L{arv>- zAW%8WrSAVY1sj$=umcAf#ZgC8UGZGoamK}hR7j6}i8#np8ruUlvgQ$j+AQglFsQQq zOjyHf22pxh9+h#n$21&$h?2uq0>C9P?P=Juw0|;oE~c$H{#RGfa>| zj)Iv&uOnaf@foiBJ}_;zyPHcZt1U~nOcNB{)og8Btv+;f@PIT*xz$x!G?u0Di$lo7 zOugtQ$Wx|C($fyJTZE1JvR~i7LP{ zbdIwqYghQAJi9p}V&$=*2Azev$6K@pyblphgpv8^9bN!?V}{BkC!o#bl&AP!3DAjM zmWFsvn2fKWCfjcAQmE+=c3Y7j@#7|{;;0f~PIodmq*;W9Fiak|gil6$w3%b_Pr6K_ zJEG@&!J%DgBZJDCMn^7mk`JV0&l07Bt`1ymM|;a)MOWz*bh2#d{i?SDe9IcHs7 zjCrnyQ*Y5GzIt}>`bD91o#~5H?4_nckAgotN{2%!?wsSl|LVmJht$uhGa+HiH>;av z8c?mcMYM7;mvWr6noUR{)gE!=i7cZUY7e;HXa221KkRoc2UB>s$Y(k%NzTSEr>W(u z<(4mcc)4rB_&bPzX*1?*ra%VF}P1nwiP5cykJ&W{!OTlz&Td0pOkVp+wc z@k=-Hg=()hNg=Q!Ub%`BONH{ z_=ZFgetj@)NvppAK2>8r!KAgi>#%*7;O-o9MOOfQjV-n@BX6;Xw;I`%HBkk20v`qoVd0)}L6_49y1IhR z_OS}+eto}OPVRn*?UHC{eGyFU7JkPz!+gX4P>?h3QOwGS63fv4D1*no^6PveUeE5% zlehjv_3_^j^C({a2&RSoVlOn71D8WwMu9@Nb@=E_>1R*ve3`#TF(NA0?d9IR_tm=P zOP-x;gS*vtyE1Cm zG0L?2nRUFj#aLr-R1fX*$sXhad)~xdA*=hF3zPZhha<2O$Ps+F07w*3#MTe?)T8|A!P!v+a|ot{|^$q(TX`35O{WI0RbU zCj?hgOv=Z)xV?F`@HKI11IKtT^ocP78cqHU!YS@cHI@{fPD?YXL)?sD~9thOAv4JM|K8OlQhPXgnevF=F7GKD2#sZW*d za}ma31wLm81IZxX(W#A9mBvLZr|PoLnP>S4BhpK8{YV_}C|p<)4#yO{#ISbco92^3 zv&kCE(q9Wi;9%7>>PQ!zSkM%qqqLZW7O`VXvcj;WcJ`2~v?ZTYB@$Q&^CTfvy?1r^ z;Cdi+PTtmQwHX_7Kz?r#1>D zS5lWU(Mw_$B&`ZPmqxpIvK<~fbXq?x20k1~9az-Q!uR78mCgRj*eQ>zh3c$W}>^+w^dIr-u{@s30J=)1zF8?Wn|H`GS<=>Om|DjzC{}Jt?{!fSJe*@$H zg>wFnlT)k#T?LslW zu$^7Uy~$SQ21cE?3Ijl+bLfuH^U5P^$@~*UY#|_`uvAIe(+wD2eF}z_y!pvomuVO; zS^9fbdv)pcm-B@CW|Upm<7s|0+$@@<&*>$a{aW+oJ%f+VMO<#wa)7n|JL5egEgoBv zl$BY(NQjE0#*nv=!kMnp&{2Le#30b)Ql2e!VkPLK*+{jv77H7)xG7&=aPHL7LK9ER z5lfHxBI5O{-3S?GU4X6$yVk>lFn;ApnwZybdC-GAvaznGW-lScIls-P?Km2mF>%B2 zkcrXTk+__hj-3f48U%|jX9*|Ps41U_cd>2QW81Lz9}%`mTDIhE)jYI$q$ma7Y-`>% z8=u+Oftgcj%~TU}3nP8&h7k+}$D-CCgS~wtWvM|UU77r^pUw3YCV80Ou*+bH0!mf0 zxzUq4ed6y>oYFz7+l18PGGzhB^pqSt)si=9M>~0(Bx9*5r~W7sa#w+_1TSj3Jn9mW zMuG9BxN=}4645Cpa#SVKjFst;9UUY@O<|wpnZk$kE+to^4!?0@?Cwr3(>!NjYbu?x z1!U-?0_O?k!NdM^-rIQ8p)%?M+2xkhltt*|l=%z2WFJhme7*2xD~@zk#`dQR$6Lmd zb3LOD4fdt$Cq>?1<%&Y^wTWX=eHQ49Xl_lFUA(YQYHGHhd}@!VpYHHm=(1-O=yfK#kKe|2Xc*9}?BDFN zD7FJM-AjVi)T~OG)hpSWqH>vlb41V#^G2B_EvYlWhDB{Z;Q9-0)ja(O+By`31=biA zG&Fs#5!%_mHi|E4Nm$;vVQ!*>=_F;ZC=1DTPB#CICS5fL2T3XmzyHu?bI;m7D4@#; ztr~;dGYwb?m^VebuULtS4lkC_7>KCS)F@)0OdxZIFZp@FM_pHnJes8YOvwB|++#G( z&dm*OP^cz95Wi15vh`Q+yB>R{8zqEhz5of>Po$9LNE{xS<)lg2*roP*sQ}3r3t<}; zPbDl{lk{pox~2(XY5=qg0z!W-x^PJ`VVtz$git7?)!h>`91&&hESZy1KCJ2nS^yMH z!=Q$eTyRi68rKxdDsdt+%J_&lapa{ds^HV9Ngp^YDvtq&-Xp}60B_w@Ma>_1TTC;^ zpbe!#gH}#fFLkNo#|`jcn?5LeUYto%==XBk6Ik0kc4$6Z+L3x^4=M6OI1=z5u#M%0 z0E`kevJEpJjvvN>+g`?gtnbo$@p4VumliZV3Z%CfXXB&wPS^5C+7of2tyVkMwNWBiTE2 z8CdPu3i{*vR-I(NY5syRR}I1TJOV@DJy-Xmvxn^IInF>Tx2e)eE9jVSz69$6T`M9-&om!T+I znia!ZWJRB28o_srWlAxtz4VVft8)cYloIoVF=pL zugnk@vFLXQ_^7;%hn9x;Vq?lzg7%CQR^c#S)Oc-8d=q_!2ZVH764V z!wDKSgP}BrVV6SfCLZnYe-7f;igDs9t+K*rbMAKsp9L$Kh<6Z;e7;xxced zn=FGY<}CUz31a2G}$Q(`_r~75PzM4l_({Hg&b@d8&jC}B?2<+ed`f#qMEWi z`gm!STV9E4sLaQX+sp5Nu9*;9g12naf5?=P9p@H@f}dxYprH+3ju)uDFt^V{G0APn zS;16Dk{*fm6&BCg#2vo?7cbkkI4R`S9SSEJ=#KBk3rl69SxnCnS#{*$!^T9UUmO#&XXKjHKBqLdt^3yVvu8yn|{ zZ#%1CP)8t-PAz(+_g?xyq;C2<9<5Yy<~C74Iw(y>uUL$+$mp(DRcCWbCKiGCZw@?_ zdomfp+C5xt;j5L@VfhF*xvZdXwA5pcdsG>G<8II-|1dhAgzS&KArcb0BD4ZZ#WfiEY{hkCq5%z9@f|!EwTm;UEjKJsUo696V>h zy##eXYX}GUu%t{Gql8vVZKkNhQeQ4C%n|RmxL4ee5$cgwlU+?V7a?(jI#&3wid+Kz5+x^G!bb#$q>QpR#BZ}Xo5UW^ zD&I`;?(a}Oys7-`I^|AkN?{XLZNa{@27Dv^s4pGowuyhHuXc zuctKG2x0{WCvg_sGN^n9myJ}&FXyGmUQnW7fR$=bj$AHR88-q$D!*8MNB{YvTTEyS zn22f@WMdvg5~o_2wkjItJN@?mDZ9UUlat2zCh(zVE=dGi$rjXF7&}*sxac^%HFD`Y zTM5D3u5x**{bW!68DL1A!s&$2XG@ytB~dX-?BF9U@XZABO`a|LM1X3HWCllgl0+uL z04S*PX$%|^WAq%jkzp~%9HyYIF{Ym?k)j3nMwPZ=hlCg9!G+t>tf0o|J2%t1 ztC+`((dUplgm3`+0JN~}&FRRJ3?l*>Y&TfjS>!ShS`*MwO{WIbAZR#<%M|4c4^dY8 z{Rh;-!qhY=dz5JthbWoovLY~jNaw>%tS4gHVlt5epV8ekXm#==Po$)}mh^u*cE>q7*kvX&gq)(AHoItMYH6^s6f(deNw%}1=7O~bTHSj1rm2|Cq+3M z93djjdomWCTCYu!3Slx2bZVy#CWDozNedIHbqa|otsUl+ut?>a;}OqPfQA05Yim_2 zs@^BjPoFHOYNc6VbNaR5QZfSMh2S*`BGwcHMM(1@w{-4jVqE8Eu0Bi%d!E*^Rj?cR z7qgxkINXZR)K^=fh{pc0DCKtrydVbVILI>@Y0!Jm>x-xM!gu%dehm?cC6ok_msDVA*J#{75%4IZt}X|tIVPReZS#aCvuHkZxc zHVMtUhT(wp09+w9j9eRqz~LtuSNi2rQx_QgQ(}jBt7NqyT&ma61ldD(s9x%@q~PQl zp6N*?=N$BtvjQ_xIT{+vhb1>{pM0Arde0!X-y))A4znDrVx8yrP3B1(7bKPE5jR@5 zwpzwT4cu~_qUG#zYMZ_!2Tkl9zP>M%cy>9Y(@&VoB84#%>amTAH{(hL4cDYt!^{8L z645F>BWO6QaFJ-{C-i|-d%j7#&7)$X7pv#%9J6da#9FB5KyDhkA+~)G0^87!^}AP>XaCSScr;kL;Z%RSPD2CgoJ;gpYT5&6NUK$86$T?jRH=w8nI9Z534O?5fk{kd z`(-t$8W|#$3>xoMfXvV^-A(Q~$8SKDE^!T;J+rQXP71XZ(kCCbP%bAQ1|%$%Ov9_a zyC`QP3uPvFoBqr_+$HenHklqyIr>PU_Fk5$2C+0eYy^~7U&(!B&&P2%7#mBUhM!z> z_B$Ko?{Pf6?)gpYs~N*y%-3!1>o-4;@1Zz9VQHh)j5U1aL-Hyu@1d?X;jtDBNk*vMXPn@ z+u@wxHN*{uHR!*g*4Xo&w;5A+=Pf9w#PeZ^x@UD?iQ&${K2c}UQgLRik-rKM#Y5rdDphdcNTF~cCX&9ViRP}`>L)QA4zNXeG)KXFzSDa6 zd^St;inY6J_i=5mcGTx4_^Ys`M3l%Q==f>{8S1LEHn{y(kbxn5g1ezt4CELqy)~TV6{;VW>O9?5^ ztcoxHRa0jQY7>wwHWcxA-BCwzsP>63Kt&3fy*n#Cha687CQurXaRQnf5wc9o8v7Rw zNwGr2fac;Wr-Ldehn7tF^(-gPJwPt@VR1f;AmKgxN&YPL;j=0^xKM{!wuU|^mh3NE zy35quf}MeL!PU;|{OW_x$TBothLylT-J>_x6p}B_jW1L>k)ps6n%7Rh z96mPkJIM0QFNYUM2H}YF5bs%@Chs6#pEnloQhEl?J-)es!(SoJpEPoMTdgA14-#mC zghayD-DJWtUu`TD8?4mR)w5E`^EHbsz2EjH5aQLYRcF{l7_Q5?CEEvzDo(zjh|BKg z3aJl_n#j&eFHsUw4~lxqnr!6NL*se)6H=A+T1e3xUJGQrd}oSPwSy5+$tt{2t5J5@(lFxl43amsARG74iyNC}uuS zd2$=(r6RdamdGx^eatX@F2D8?U23tDpR+Os?0Gq2&^dF+$9wiWf?=mDWfjo4LfRwL zI#SRV9iSz>XCSgEj!cW&9H-njJopYiYuq|2w<5R2!nZ27DyvU4UDrHpoNQZiGPkp@ z1$h4H46Zn~eqdj$pWrv;*t!rTYTfZ1_bdkZmVVIRC21YeU$iS-*XMNK`#p8Z_DJx| zk3Jssf^XP7v0X?MWFO{rACltn$^~q(M9rMYoVxG$15N;nP)A98k^m3CJx8>6}NrUd@wp-E#$Q0uUDQT5GoiK_R{ z<{`g;8s>UFLpbga#DAf%qbfi`WN1J@6IA~R!YBT}qp%V-j!ybkR{uY0X|x)gmzE0J z&)=eHPjBxJvrZSOmt|)hC+kIMI;qgOnuL3mbNR0g^<%|>9x7>{}>a2qYSZAGPt4it?8 zNcLc!Gy0>$jaU?}ZWxK78hbhzE+etM`67*-*x4DN>1_&{@5t7_c*n(qz>&K{Y?10s zXsw2&nQev#SUSd|D8w7ZD2>E<%g^; zV{yE_O}gq?Q|zL|jdqB^zcx7vo(^})QW?QKacx$yR zhG|XH|8$vDZNIfuxr-sYFR{^csEI*IM#_gd;9*C+SysUFejP0{{z7@P?1+&_o6=7V|EJLQun^XEMS)w(=@eMi5&bbH*a0f;iC~2J74V2DZIlLUHD&>mlug5+v z6xBN~8-ovZylyH&gG#ptYsNlT?-tzOh%V#Y33zlsJ{AIju`CjIgf$@gr8}JugRq^c zAVQ3;&uGaVlVw}SUSWnTkH_6DISN&k2QLMBe9YU=sA+WiX@z)FoSYX`^k@B!j;ZeC zf&**P?HQG6Rk98hZ*ozn6iS-dG}V>jQhb3?4NJB*2F?6N7Nd;EOOo;xR7acylLaLy z9)^lykX39d@8@I~iEVar4jmjjLWhR0d=EB@%I;FZM$rykBNN~jf>#WbH4U{MqhhF6 zU??@fSO~4EbU4MaeQ_UXQcFyO*Rae|VAPLYMJEU`Q_Q_%s2*>$#S^)&7er+&`9L=1 z4q4ao07Z2Vsa%(nP!kJ590YmvrWg+YrgXYs_lv&B5EcoD`%uL79WyYA$0>>qi6ov7 z%`ia~J^_l{p39EY zv>>b}Qs8vxsu&WcXEt8B#FD%L%ZpcVtY!rqVTHe;$p9rbb5O{^rFMB>auLn-^;s+-&P1#h~mf~YLg$8M9 zZ4#87;e-Y6x6QO<{McUzhy(%*6| z)`D~A(TJ$>+0H+mct(jfgL4x%^oC^T#u(bL)`E2tBI#V1kSikAWmOOYrO~#-cc_8! zCe|@1&mN2{*ceeiBldHCdrURk4>V}79_*TVP3aCyV*5n@jiNbOm+~EQ_}1#->_tI@ zqXv+jj2#8xJtW508rzFrYcJxoek@iW6SR@1%a%Bux&;>25%`j3UI`0DaUr7l79`B1 zqqUARhW1^h6=)6?;@v>xrZNM;t}{yY3P@|L}ey@gG( z9r{}WoYN(9TW&dE2dEJIXkyHA4&pU6ki=rx&l2{DLGbVmg4%3Dlfvn!GB>EVaY_%3+Df{fBiqJV>~Xf8A0aqUjgpa} zoF8YXO&^_x*Ej}nw-$-F@(ddB>%RWoPUj?p8U{t0=n>gAI83y<9Ce@Q#3&(soJ{64 z37@Vij1}5fmzAuIUnXX`EYe;!H-yTVTmhAy;y8VZeB#vD{vw9~P#DiFiKQ|kWwGFZ z=jK;JX*A;Jr{#x?n8XUOLS;C%f|zj-7vXtlf_DtP7bpurBeX%Hjwr z4lI-2TdFpzkjgiv!8Vfv`=SP+s=^i3+N~1ELNWUbH|ytVu>EyPN_3(4TM^QE1swRo zoV7Y_g)a>28+hZG0e7g%@2^s>pzR4^fzR-El}ARTmtu!zjZLuX%>#OoU3}|rFjJg} zQ2TmaygxJ#sbHVyiA5KE+yH0LREWr%^C*yR|@gM$nK2P zo}M}PV0v))uJh&33N>#aU376@ZH79u(Yw`EQ2hM3SJs9f99+cO6_pNW$j$L-CtAfe zYfM)ccwD!P%LiBk!eCD?fHCGvgMQ%Q2oT_gmf?OY=A>&PaZQOq4eT=lwbaf}33LCH zFD|)lu{K7$8n9gX#w4~URjZxWm@wlH%oL#G|I~Fb-v^0L0TWu+`B+ZG!yII)w05DU z>GO?n(TN+B=>HdxVDSlIH76pta$_LhbBg;eZ`M7OGcqt||qi zogS72W1IN%=)5JCyOHWoFP7pOFK0L*OAh=i%&VW&4^LF@R;+K)t^S!96?}^+5QBIs zjJNTCh)?)4k^H^g1&jc>gysM`y^8Rm3qsvkr$9AeWwYpa$b22=yAd1t<*{ zaowSEFP+{y?Ob}8&cwfqoy4Pb9IA~VnM3u!trIK$&&0Op#Ql4j>(EW?UNUv#*iH1$ z^j>+W{afcd`{e&`-A{g}{JnIzYib)!T56IT@YEs{4|`sMpW3c8@UCoIJv`XsAw!XC z34|Il$LpW}CIHFC5e*)}00I5{%OL*WZRGzC0?_}-9{#ue?-ug^ zLE|uv-~6xnSs_2_&CN9{9vyc!Xgtn36_g^wI0C4s0s^;8+p?|mm;Odt3`2ZjwtK;l zfd6j)*Fr#53>C6Y8(N5?$H0ma;BCF3HCjUs7rpb2Kf*x3Xcj#O8mvs#&33i+McX zQpBxD8!O{5Y8D&0*QjD=Yhl9%M0)&_vk}bmN_Ud^BPN;H=U^bn&(csl-pkA+GyY0Z zKV7sU_4n;}uR78ouo8O%g*V;79KY?3d>k6%gpcmQsKk&@Vkw9yna_3asGt`0Hmj59 z%0yiF*`jXhByBI9QsD=+>big5{)BGe&+U2gAARGe3ID)xrid~QN_{I>k}@tzL!Md_ z&=7>TWciblF@EMC3t4-WX{?!m!G6$M$1S?NzF*2KHMP3Go4=#ZHkeIv{eEd;s-yD# z_jU^Ba06TZqvV|Yd;Z_sN%$X=!T+&?#p+OQIHS%!LO`Hx0q_Y0MyGYFNoM{W;&@0@ zLM^!X4KhdtsET5G<0+|q0oqVXMW~-7LW9Bg}=E$YtNh1#1D^6Mz(V9?2g~I1( zoz9Cz=8Hw98zVLwC2AQvp@pBeKyidn6Xu0-1SY1((^Hu*-!HxFUPs)yJ+i`^BC>PC zjwd0mygOVK#d2pRC9LxqGc6;Ui>f{YW9Bvb>33bp^NcnZoH~w9(lM5@JiIlfa-6|k ziy31UoMN%fvQfhi8^T+=yrP{QEyb-jK~>$A4SZT-N56NYEbpvO&yUme&pWKs3^94D zH{oXnUTb3T@H+RgzML*lejx`WAyw*?K7B-I(VJx($2!NXYm%3`=F~TbLv3H<{>D?A zJo-FDYdSA-(Y%;4KUP2SpHKAIcv9-ld(UEJE7=TKp|Gryn;72?0LHqAN^fk6%8PCW z{g_-t)G5uCIf0I`*F0ZNl)Z>))MaLMpXgqWgj-y;R+@A+AzDjsTqw2Mo9ULKA3c70 z!7SOkMtZb+MStH>9MnvNV0G;pwSW9HgP+`tg}e{ij0H6Zt5zJ7iw`hEnvye!XbA@!~#%vIkzowCOvq5I5@$3wtc*w2R$7!$*?}vg4;eDyJ_1=ixJuEp3pUS27W?qq(P^8$_lU!mRChT}ctvZz4p!X^ zOSp|JOAi~f?UkwH#9k{0smZ7-#=lK6X3OFEMl7%)WIcHb=#ZN$L=aD`#DZKOG4p4r zwlQ~XDZ`R-RbF&hZZhu3(67kggsM-F4Y_tI^PH8PMJRcs7NS9ogF+?bZB*fcpJ z=LTM4W=N9yepVvTj&Hu~0?*vR1HgtEvf8w%Q;U0^`2@e8{SwgX5d(cQ|1(!|i$km! zvY03MK}j`sff;*-%mN~ST>xU$6Bu?*Hm%l@0dk;j@%>}jsgDcQ)Hn*UfuThz9(ww_ zasV`rSrp_^bp-0sx>i35FzJwA!d6cZ5#5#nr@GcPEjNnFHIrtUYm1^Z$;{d&{hQV9 z6EfFHaIS}46p^5I-D_EcwwzUUuO}mqRh&T7r9sfw`)G^Q%oHxEs~+XoM?8e*{-&!7 z7$m$lg9t9KP9282eke608^Q2E%H-xm|oJ8=*SyEo} z@&;TQ3K)jgspgKHyGiKVMCz>xmC=H5Fy3!=TP)-R3|&1S-B)!6q50wfLHKM@7Bq6E z44CY%G;GY>tC`~yh!qv~YdXw! zSkquvYNs6k1r7>Eza?Vkkxo6XRS$W7EzL&A`o>=$HXgBp{L(i^$}t`NcnAxzbH8Ht z2!;`bhKIh`f1hIFcI5bHI=ueKdzmB9)!z$s-BT4ItyY|NaA_+o=jO%MU5as9 zc2)aLP>N%u>wlaXTK!p)r?+~)L+0eCGb5{8WIk7K52$nufnQ+m8YF+GQc&{^(zh-$ z#wyWV*Zh@d!b(WwXqvfhQX)^aoHTBkc;4ossV3&Ut*k>AI|m+{#kh4B!`3*<)EJVj zwrxK>99v^k4&Y&`Awm>|exo}NvewV%E+@vOc>5>%H#BK9uaE2$vje zWYM5fKuOTtn96B_2~~!xJPIcXF>E_;yO8AwpJ4)V`Hht#wbO3Ung~@c%%=FX4)q+9 z99#>VC2!4l`~0WHs9FI$Nz+abUq# zz`Of97})Su=^rGp2S$)7N3rQCj#0%2YO<R&p>$<#lgXcUj=4H_{oAYiT3 z44*xDn-$wEzRw7#@6aD)EGO$0{!C5Z^7#yl1o;k0PhN=aVUQu~eTQ^Xy{z8Ow6tk83 z4{5xe%(hx)%nD&|e*6sTWH`4W&U!Jae#U4TnICheJmsw{l|CH?UA{a6?2GNgpZLyzU2UlFu1ZVwlALmh_DOs03J^Cjh1im`E3?9&zvNmg(MuMw&0^Lu$(#CJ*q6DjlKsY-RMJ^8yIY|{SQZ*9~CH|u9L z`R78^r=EbbR*_>5?-)I+$6i}G)%mN(`!X72KaV(MNUP7Nv3MS9S|Pe!%N2AeOt5zG zVJ;jI4HZ$W->Ai_4X+`9c(~m=@ek*m`ZQbv3ryI-AD#AH=`x$~WeW~M{Js57(K7(v ze5`};LG|%C_tmd>bkufMWmAo&B+DT9ZV~h(4jg0>^aeAqL`PEUzJJtI8W1M!bQWpv zvN(d}E1@nlYa!L!!A*RN!(Q3F%J?5PvQ0udu?q-T)j3JKV~NL>KRb~w-lWc685uS6 z=S#aR&B8Sc8>cGJ!!--?kwsJTUUm`Jk?7`H z7PrO~xgBrSW2_tTlCq1LH8*!o?pj?qxy8}(=r_;G18POrFh#;buWR0qU24+XUaVZ0 z?(sXcr@-YqvkCmHr{U2oPogHL{r#3r49TeR<{SJX1pcUqyWPrkYz^X8#QW~?F)R5i z>p^!i<;qM8Nf{-fd6!_&V*e_9qP6q(s<--&1Ttj01j0w>bXY7y1W*%Auu&p|XSOH=)V7Bd4fUKh&T1)@cvqhuD-d=?w}O zjI%i(f|thk0Go*!d7D%0^ztBfE*V=(ZIN84f5HU}T9?ulmEYzT5usi=DeuI*d|;M~ zp_=Cx^!4k#=m_qSPBr5EK~E?3J{dWWPH&oCcNepYVqL?nh4D5ynfWip$m*YlZ8r^Z zuFEUL-nW!3qjRCLIWPT0x)FDL7>Yt7@8dA?R2kF@WE>ysMY+)lTsgNM#3VbXVGL}F z1O(>q>2a+_`6r5Xv$NZAnp=Kgnr3)cL(^=8ypEeOf3q8(HGe@7Tt59;yFl||w|mnO zHDxg2G3z8=(6wjj9kbcEY@Z0iOd7Gq5GiPS5% z*sF1J<#daxDV2Z8H>wxOF<;yKzMeTaSOp_|XkS9Sfn6Mpe9UBi1cSTieGG5$O;ZLIIJ60Y>SN4vC?=yE_CWlo(EEE$e4j?z&^FM%kNmRtlbEL^dPPgvs9sbK5fGw*r@ z+!EU@u$T8!nZh?Fdf_qk$VuHk^yVw`h`_#KoS*N%epIIOfQUy_&V}VWDGp3tplMbf z5Se1sJUC$7N0F1-9jdV2mmGK{-}fu|Nv;12jDy0<-kf^AmkDnu6j~TPWOgy1MT68|D z=4=50jVbUKdKaQgD`eWGr3I&^<6uhkjz$YwItY8%Yp9{z4-{6g{73<_b*@XJ4Nm3-3z z?BW3{aY_ccRjb@W1)i5nLg|7BnWS!B`_Uo9CWaE`Ij327QH?i)9A}4Ug4wmxVVa^b z-4+m%-wwOl7cKH7+=x&nrCrbEC)Q$fpg&V83#uEH;C=GNMz`ps@^RxK%T*8%OPnC` z{WO~J%nxYJ`x|N%?&i7?;{_8t^jM&=50HlaOQj8fS}_`moH$c;vI<|cruPFnpT8yU zS%rPOCUSd5Zdb(zwk`hqwTQn)*&n)uYsP*F_(~xEWq}C= zv30kFmZFwJZ@ELVX3?$dXQh|icO7UrL*_5G=I^xXjImz`ZPp>?g#tf(ej~KaIU0algsG!IS09;>?MvqGg#c{i+}qY|{P8W~O%#>|gFd z<1dr$-oxyRGN17yZo1OwLnzwYs0|;IS_nymNB0IlSzPQ%-r`?T=;_XQ^~&#}b|AB} zkNbN5uB?-sUB-T5QLlg%Uk3)uHB;>VIzGe9_J9 zaeISkQm!v(9d(0ML^b9fR^sfHFlH?7Mvddt37OuR{|O0{uv)(&-6<87W4 zyO>s!=cPgP3O&7xxU5DlIPw_o3O>6o6Qb?JWs3qw#p3sBc3g$?Dx zi(6D+DYgV;GrUis-CL%Qe{nvZnwaVXmbhH(|GFh|Q)k=1uvA$I@1DXI7bKlQ@8D6P zS?(*?><>)G49q0wr;NajpxP4W2G)kHl6^=Z>hrNEI4Mwd_$O6$1dXF;Q#hE(-eeW6 zz03GJF%Wl?HO=_ztv5*zRlcU~{+{k%#N59mgm~eK>P!QZ6E?#Cu^2)+K8m@ySvZ*5 z|HDT}BkF@3!l(0%75G=1u2hETXEj!^1Z$!)!lyGXlWD!_vqGE$Z)#cUVBqlORW>0^ zDjyVTxwKHKG|0}j-`;!R-p>}qQfBl(?($7pP<+Y8QE#M8SCDq~k<+>Q^Zf@cT_WdX3~BSe z+|KK|7OL5Hm5(NFP~j>Ct3*$wi0n0!xl=(C61`q&cec@mFlH(sy%+RH<=s)8aAPN`SfJdkAQjdv82G5iRdv8 zh{9wHUZaniSEpslXl^_ODh}mypC?b*9FzLjb~H@3DFSe;D(A-K3t3eOTB(m~I6C;(-lKAvit(70k`%@+O*Ztdz;}|_TS~B?Tpmi=QKC^m_ z2YpEaT3iiz*;T~ap1yiA)a`dKMwu`^UhIUeltNQ1Yjo=q@bI@&3zH?rVUg=IxLy-ni zyxDu%-Fr{H6owTjZU2O5>nDb=q&Jz_TjeSq%!2m40x&U6w~GQ({quPL73IsJS;f`$ zsuhioqCBj(gJ>2hoo)Gou7(WP*pX)f=Y=!=k!&1K?EYY%jJ~X&DnK{^saPQK<1BJ z_A`_{%ZozcB(3w$z^To^6d|XuT@=X~wtW!+{4ID@N{AB~J6AL5vuY>JwvWCNFKsKh zd}@>q@_WV#QZ&UJ0#?X(pXR!oyXOEG3rqzHbCzGLONDb042i$})fM@XF)uSP(DHUc z^&{|$*xe{cs?Gp8=B%RY3L7#$ve$?TWh>MZdxF1zH1v}1z+$Ov#G7?%D)bBCyDe*% zSeKSpETC2V1){II>@UwJi>4uBN+iAx+82E~gb|Cr&8E^i&)A!uv-g?jzH99wU}8+# z$nh>yvb;TwZmS@7LrvuCu_d0-WxFNI&C7%sWuTL%YU!l|I1{|->=dlOeHOCtUO#zkS3ESO8LHV4hTdQL5EdV zuWD33fFPH}HPrW^s$Qn1Xgp&AT6<-He{{4%eIu3rN=iK|9mURdKXfB&Q?qGok%!cs ze53UP{Z!TO-Y@q2;;k2avA3`lm4OoN4@S*k=UA)7H;qZ`d8`XaYFCv?Ba+uGW@r5v z&&{nf(24WSBOhc7!qF^@0cz;XcUynNaj6w2349;s!K{KVqs5yS{ z7VubS`2OzT^5#1~6Tt^RTvt9-J|D2F>y~>2;jeF>g`hx5l%B3H=aLExQihuYngzlnBTYOTHJQMzl>kwqN5JYs)Ej zblA@ntkUS~xi+}y6|(81helS}Q~&VB37qyV|S3Y=><^1wh%msQM?fz z<58MX(=|PSUKCF#)dbhR%D&xgCD?$aR0qen+wpp6 zst}vX18!Be96TD??j1HsHTUx(a&@F?=gT`Q$oJFFyrh^;zgz!(NlAHGn0cJy@us=w zNhC#l5G;H}+>49Nsh12=ZPO2r*2OBQe5kpb&1?*PIBFitK8}FUfb~S-#hKfF0o#&d z#3aPkB$9scYku&kA6{0xHnBV#&Wei5J>5T-XX-gUXEPo+9b7WL=*XESc(3BshL`aj zXp}QIp*40}oWJt*l043e8_5;H5PI5c)U&IEw5dF(4zjX0y_lk9 zAp@!mK>WUqHo)-jop=DoK>&no>kAD=^qIE7qis&_*4~ z6q^EF$D@R~3_xseCG>Ikb6Gfofb$g|75PPyyZN&tiRxqovo_k zO|HA|sgy#B<32gyU9x^&)H$1jvw@qp+1b(eGAb)O%O!&pyX@^nQd^9BQ4{(F8<}|A zhF&)xusQhtoXOOhic=8#Xtt5&slLia3c*a?dIeczyTbC#>FTfiLST57nc3@Y#v_Eg#VUv zT8cKH#f3=1PNj!Oroz_MAR*pow%Y0*6YCYmUy^7`^r|j23Q~^*TW#cU7CHf0eAD_0 zEWEVddxFgQ7=!nEBQ|ibaScslvhuUk^*%b#QUNrEB{3PG@uTxNwW}Bs4$nS9wc(~O zG7Iq>aMsYkcr!9#A;HNsJrwTDYkK8ikdj{M;N$sN6BqJ<8~z>T20{J8Z2rRUuH7~3 z=tgS`AgxbBOMg87UT4Lwge`*Y=01Dvk>)^{Iu+n6fuVX4%}>?3czOGR$0 zpp*wp>bsFFSV`V;r_m+TZns$ZprIi`OUMhe^cLE$2O+pP3nP!YB$ry}2THx2QJs3< za1;>d-AggCarrQ>&Z!d@;mW+!q6eXhb&`GbzUDSxpl8AJ#Cm#tuc)_xh(2NV=5XMs zrf_ozRYO$NkC=pKFX5OH8v1>0i9Z$ec`~Mf+_jQ68spn(CJwclDhEEkH2Qw;${J$clv__nUjn5jA0wCLEnu1j;v!0vB>Ri6m9`;R{JMS%^)4FC zU0Z44+u$I$w=Bj|iu4DT5h~sS`C*zbmX?@-crY}E+hy>}2~C0Nn(EKk@5^qO4@l@! z6O0lr%tzGC`D^)8xU3FnMZVm0kX1sBWhaQyzVoXFWwr%Ny?=2M{5s#5i7fTu3gEkG zc{(Pr$v=;`Y#&`y*J}#M9ux>0?xu!`$9cUKm#Bdd_&S#LPTS?ZPV6zN6>W6JTS~-LfjL{mB=b(KMk3 z2HjBSlJeyUVqDd=Mt!=hpYsvby2GL&3~zm;0{^nZJq+4vb?5HH4wufvr}IX42sHeK zm@x?HN$8TsTavXs)tLDFJtY9b)y~Tl@7z4^I8oUQq4JckH@~CVQ;FoK(+e0XAM>1O z(ei}h?)JQp>)d=6ng-BZF1Z5hsAKW@mXq+hU?r8I(*%`tnIIOXw7V6ZK(T9RFJJe@ zZS!aC+p)Gf2Ujc=a6hx4!A1Th%YH!Lb^xpI!Eu` zmJO{9rw){B1Ql18d%F%da+Tbu1()?o(zT7StYqK6_w`e+fjXq5L^y(0 z09QA6H4oFj59c2wR~{~>jUoDzDdKz}5#onYPJRwa`SUO)Pd4)?(ENBaFVLJr6Kvz= zhTtXqbx09C1z~~iZt;g^9_2nCZ{};-b4dQJbv8HsWHXPVg^@(*!@xycp#R?a|L!+` zY5w))JWV`Gls(=}shH0#r*;~>_+-P5Qc978+QUd>J%`fyn{*TsiG-dWMiJXNgwBaT zJ=wgYFt+1ACW)XwtNx)Q9tA2LPoB&DkL16P)ERWQlY4%Y`-5aM9mZ{eKPUgI!~J3Z zkMd5A_p&v?V-o-6TUa8BndiX?ooviev(DKw=*bBVOW|=zps9=Yl|-R5@yJe*BPzN}a0mUsLn{4LfjB_oxpv(mwq# zSY*%E{iB)sNvWfzg-B!R!|+x(Q|b@>{-~cFvdDHA{F2sFGA5QGiIWy#3?P2JIpPKg6ncI^)dvqe`_|N=8 '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..db3a6ac2 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pom.xml b/pom.xml index 236f6f7b..240e9637 100644 --- a/pom.xml +++ b/pom.xml @@ -1,27 +1,4 @@ - com.alpsbte PlotSystem 5.0.0 + An easy to use building system for the BuildTheEarth project. diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000..22487c71 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "PlotSystem" diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index e7703628..c0b96ea3 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,5 +1,6 @@ main: com.alpsbte.plotsystem.PlotSystem -version: "${project.version}${build.number}" +version: "${version}" +description: "${description}" api-version: "1.21" name: Plot-System author: R3tuxn, Cinnazeyy & Zoriot From efe65475a490f80e18856ac491a6339fee999b99 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 25 Aug 2025 03:32:54 +0200 Subject: [PATCH 137/175] =?UTF-8?q?refactor:=20=E2=9C=A8=20convert=20class?= =?UTF-8?q?es=20to=20records=20for=20improved=20data=20abstraction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Suggested by idea, sonarqube & codacy. --- .github/workflows/build.yml | 2 +- .../admin/setup/CMD_Setup_BuildTeam.java | 16 ++++--- .../admin/setup/CMD_Setup_ReviewCriteria.java | 4 +- .../database/providers/ReviewProvider.java | 43 +++++++++++-------- .../providers/TutorialPlotProvider.java | 8 +++- .../menus/review/ReviewPlotTogglesMenu.java | 8 ++-- .../core/system/plot/utils/PlotUtils.java | 6 +-- .../review/BuildTeamToggleCriteria.java | 41 +++++++++++------- .../system/review/ReviewNotification.java | 42 ++++++++++-------- .../core/system/review/ToggleCriteria.java | 41 +++++++++++------- 10 files changed, 126 insertions(+), 85 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c7b829e0..fe4b4c3d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,4 +1,4 @@ -# This workflow uses actions that are not certified by GitHub. +# This workflow uses actions that GitHub does not certify. # They are provided by a third-party and are governed by # separate terms of service, privacy policy, and support # documentation. diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 87786a62..c0439d3c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -39,7 +39,9 @@ import java.util.StringJoiner; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; public class CMD_Setup_BuildTeam extends SubCommand { public CMD_Setup_BuildTeam(BaseCommand baseCommand) { @@ -385,7 +387,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(text("--------------------------", DARK_GRAY)); for (ToggleCriteria c : criteria) { sender.sendMessage(text(" » ", DARK_GRAY) - .append(text(c.getCriteriaName() + " (" + (c.isOptional() ? "optional" : "required") + ")"))); + .append(text(c.criteriaName() + " (" + (c.isOptional() ? "optional" : "required") + ")"))); } sender.sendMessage(text("--------------------------", DARK_GRAY)); } @@ -435,7 +437,7 @@ public void onCommand(CommandSender sender, String[] args) { } boolean successful = DataProvider.REVIEW.assignBuildTeamToggleCriteria(buildTeam.get().getId(), criteria.get()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully assigned criteria '" + criteria.get().getCriteriaName() + "' to build team with ID '" + args[1] + "'!")); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully assigned criteria '" + criteria.get().criteriaName() + "' to build team with ID '" + args[1] + "'!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } @@ -478,14 +480,14 @@ public void onCommand(CommandSender sender, String[] args) { // Check if toggle criteria exists Optional criteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(buildTeam.get().getId()) - .stream().filter(t -> t.getCriteriaName().equalsIgnoreCase(args[2])).findFirst(); + .stream().filter(t -> t.criteriaName().equalsIgnoreCase(args[2])).findFirst(); if (criteria.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Toggle criteria could not be found or is not assigned!")); return; } boolean successful = DataProvider.REVIEW.removeBuildTeamToggleCriteria(buildTeam.get().getId(), criteria.get()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed criteria '" + criteria.get().getCriteriaName() + "' from build team with ID '" + args[1] + "'!")); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed criteria '" + criteria.get().criteriaName() + "' from build team with ID '" + args[1] + "'!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java index 3becfcc3..a639b1ed 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -90,7 +90,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(text("--------------------------", DARK_GRAY)); for (ToggleCriteria c : criteria) { sender.sendMessage(text(" » ", DARK_GRAY) - .append(text(c.getCriteriaName() + " (" + (c.isOptional() ? "optional" : "required") + ")"))); + .append(text(c.criteriaName() + " (" + (c.isOptional() ? "optional" : "required") + ")"))); } sender.sendMessage(text("--------------------------", DARK_GRAY)); } @@ -182,7 +182,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - boolean successful = DataProvider.REVIEW.removeToggleCriteria(criteria.get().getCriteriaName()); + boolean successful = DataProvider.REVIEW.removeToggleCriteria(criteria.get().criteriaName()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 0f2e44f8..5e229750 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -29,14 +29,23 @@ import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; -import com.alpsbte.plotsystem.core.system.review.*; +import com.alpsbte.plotsystem.core.system.review.BuildTeamToggleCriteria; +import com.alpsbte.plotsystem.core.system.review.PlotReview; +import com.alpsbte.plotsystem.core.system.review.ReviewNotification; +import com.alpsbte.plotsystem.core.system.review.ReviewRating; +import com.alpsbte.plotsystem.core.system.review.ToggleCriteria; import com.alpsbte.plotsystem.utils.Utils; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.sql.ResultSet; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; public class ReviewProvider { protected static final List NOTIFICATIONS = new ArrayList<>(); @@ -68,7 +77,7 @@ public ReviewProvider() { ResultSet rs = ps.executeQuery(); while (rs.next()) { String criteriaName = rs.getString(1); - ToggleCriteria toggle = TOGGLE_CRITERIA.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst().orElseThrow(); + ToggleCriteria toggle = TOGGLE_CRITERIA.stream().filter(c -> c.criteriaName().equals(criteriaName)).findFirst().orElseThrow(); BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(rs.getInt(2), toggle)); } })); @@ -179,7 +188,7 @@ public boolean removeReview(int reviewId) { // remove all review notifications List notifications = getReviewNotifications(reviewId); for (ReviewNotification notification : notifications) { - removeReviewNotification(notification.getReviewId(), notification.getUuid()); + removeReviewNotification(notification.reviewId(), notification.uuid()); } // remove checked toggle criteria @@ -213,11 +222,11 @@ public boolean removeAllReviewsOfPlot(int plotId) { // --- Toggle Criteria --- public Optional getToggleCriteria(String criteriaName) { - return TOGGLE_CRITERIA.stream().filter(c -> c.getCriteriaName().equals(criteriaName)).findFirst(); + return TOGGLE_CRITERIA.stream().filter(c -> c.criteriaName().equals(criteriaName)).findFirst(); } public boolean addToggleCriteria(String criteriaName, boolean isOptional) { - Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); + Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.criteriaName().equals(criteriaName)).findFirst(); if (criteria.isPresent()) return false; String qInsertToggleCriteria = "INSERT INTO review_toggle_criteria (criteria_name, is_optional) VALUES (?, ?);"; @@ -231,7 +240,7 @@ public boolean addToggleCriteria(String criteriaName, boolean isOptional) { } public boolean removeToggleCriteria(String criteriaName) { - Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); + Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.criteriaName().equals(criteriaName)).findFirst(); if (criteria.isEmpty()) return false; String qDeleteToggleCriteria = "DELETE FROM review_toggle_criteria WHERE criteria_name = ?;"; @@ -244,7 +253,7 @@ public boolean removeToggleCriteria(String criteriaName) { } public boolean setToggleCriteriaOptional(String criteriaName, boolean isOptional) { - Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.getCriteriaName().equals(criteriaName)).findFirst(); + Optional criteria = TOGGLE_CRITERIA.stream().filter(t -> t.criteriaName().equals(criteriaName)).findFirst(); if (criteria.isEmpty()) return false; String qSetToggleCriteriaOptional = "UPDATE review_toggle_criteria SET is_optional = ? WHERE criteria_name = ?;"; @@ -258,17 +267,17 @@ public boolean setToggleCriteriaOptional(String criteriaName, boolean isOptional public List getAllToggleCriteria() {return TOGGLE_CRITERIA.stream().toList();} public List getBuildTeamToggleCriteria(int buildTeamId) { - return BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(c -> c.getBuildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::getCriteria).toList(); + return BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(c -> c.buildTeamId() == buildTeamId).map(BuildTeamToggleCriteria::criteria).toList(); } public boolean assignBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { Optional existingCriteria = getBuildTeamToggleCriteria(buildTeamId).stream().filter(t -> - t.getCriteriaName().equals(criteria.getCriteriaName())).findFirst(); + t.criteriaName().equals(criteria.criteriaName())).findFirst(); if (existingCriteria.isPresent()) return false; String qInsertCriteriaToBuildteam = "INSERT INTO build_team_uses_toggle_criteria (build_team_id, criteria_name) VALUES (?, ?);"; if (!Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsertCriteriaToBuildteam, ps -> { ps.setInt(1, buildTeamId); - ps.setString(2, criteria.getCriteriaName()); + ps.setString(2, criteria.criteriaName()); return ps.executeUpdate() > 0; })))) return false; BUILD_TEAM_TOGGLE_CRITERIA.add(new BuildTeamToggleCriteria(buildTeamId, criteria)); @@ -277,12 +286,12 @@ public boolean assignBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria cri public boolean removeBuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { Optional existingCriteria = BUILD_TEAM_TOGGLE_CRITERIA.stream().filter(btc -> - btc.getBuildTeamId() == buildTeamId && btc.getCriteria().getCriteriaName().equals(criteria.getCriteriaName())).findFirst(); + btc.buildTeamId() == buildTeamId && btc.criteria().criteriaName().equals(criteria.criteriaName())).findFirst(); if (existingCriteria.isEmpty()) return false; String qDeleteCriteriaToBuildteam = "DELETE FROM build_team_uses_toggle_criteria WHERE build_team_id = ? AND criteria_name = ?;"; return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qDeleteCriteriaToBuildteam, ps -> { ps.setInt(1, buildTeamId); - ps.setString(2, criteria.getCriteriaName()); + ps.setString(2, criteria.criteriaName()); boolean successful = ps.executeUpdate() > 0; if (successful) BUILD_TEAM_TOGGLE_CRITERIA.remove(existingCriteria.get()); return successful; @@ -307,7 +316,7 @@ public boolean addReviewToggleCriteria(int reviewId, @NotNull ToggleCriteria tog String qInsertToggleCriteriaToReview = "INSERT INTO review_contains_toggle_criteria (review_id, criteria_name, is_checked) VALUES (?, ?, ?);"; return Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsertToggleCriteriaToReview, ps -> { ps.setInt(1, reviewId); - ps.setString(2, toggle.getCriteriaName()); + ps.setString(2, toggle.criteriaName()); ps.setBoolean(3, isChecked); return ps.executeUpdate() > 0; }))); @@ -320,15 +329,15 @@ public void removeCheckedToggleCriteria(int reviewId) { // --- Review Notification --- public Optional getReviewNotification(int reviewId, UUID uuid) { - return NOTIFICATIONS.stream().filter(n -> n.getReviewId() == reviewId && n.getUuid() == uuid).findFirst(); + return NOTIFICATIONS.stream().filter(n -> n.reviewId() == reviewId && n.uuid() == uuid).findFirst(); } public List getReviewNotifications(int reviewId) { - return NOTIFICATIONS.stream().filter(n -> n.getReviewId() == reviewId).toList(); + return NOTIFICATIONS.stream().filter(n -> n.reviewId() == reviewId).toList(); } public List getReviewNotifications(UUID uuid) { - return NOTIFICATIONS.stream().filter(n -> n.getUuid() == uuid).toList(); + return NOTIFICATIONS.stream().filter(n -> n.uuid() == uuid).toList(); } public void removeReviewNotification(int reviewId, UUID uuid) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index d79acae4..33f0b428 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -33,7 +33,11 @@ import java.sql.Timestamp; import java.time.LocalDate; import java.time.LocalDateTime; -import java.util.*; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.Optional; public class TutorialPlotProvider { public static final Map tutorialPlots = new HashMap<>(); @@ -47,7 +51,7 @@ public Optional getByTutorialId(int tutorialId, String playerUUID) Optional tutorialPlot = tutorialPlots.keySet().stream() .filter(t -> t.getTutorialID() == tutorialId && t.getUUID().toString().equals(playerUUID)).findFirst(); - if (!tutorialPlot.isEmpty()) return tutorialPlot; + if (tutorialPlot.isPresent()) return tutorialPlot; String qGet = "SELECT stage_id, is_complete, last_stage_complete_date FROM tutorial WHERE tutorial_id = ? AND uuid = ?;"; return Utils.handleSqlException(tutorialPlot, () -> SqlHelper.runQuery(qGet, ps -> { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 38a8ea22..953db0fa 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -86,7 +86,7 @@ protected void setMenuItemsAsync() { for (int i = 0; i < Math.min(buildTeamCriteria.size(), 36); i++) { ToggleCriteria criteria = buildTeamCriteria.get(i); boolean isChecked = rating.getCheckedToggles().stream() - .anyMatch(t -> t.getCriteriaName().equals(criteria.getCriteriaName())); + .anyMatch(t -> t.criteriaName().equals(criteria.criteriaName())); getMenu().getSlot(9 + i).setItem(getToggleItem(criteria, isChecked)); } @@ -113,7 +113,7 @@ protected void setItemClickEventsAsync() { int finalI = i; getMenu().getSlot(9 + i).setClickHandler(((player, clickInformation) -> { ToggleCriteria clickedCriteria = buildTeamCriteria.get(finalI); - boolean isChecked = rating.getCheckedToggles().stream().anyMatch(t -> t.getCriteriaName().equals(clickedCriteria.getCriteriaName())); + boolean isChecked = rating.getCheckedToggles().stream().anyMatch(t -> t.criteriaName().equals(clickedCriteria.criteriaName())); rating.setToggleCriteria(clickedCriteria, !isChecked); getMenu().getSlot(9 + finalI).setItem(getToggleItem(clickedCriteria, !isChecked)); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 7d13212f..582d183d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -108,7 +108,7 @@ public final class PlotUtils { private PlotUtils() {} private static final String MSG_LINE = "--------------------------"; - public static final Map plotReminder = new HashMap<>(); + public static final Map plotReminder = new HashMap<>(); /** * Returns the plot that the player is currently standing on or next to. @@ -643,7 +643,7 @@ public static void sendGroupTipMessage(@NotNull Plot plot, Player player) { public static void sendFeedbackMessage(@NotNull List notifications, @NotNull Player player) { player.sendMessage(text(MSG_LINE, DARK_GRAY)); for (ReviewNotification notification : notifications) { - PlotReview review = DataProvider.REVIEW.getReview(notification.getReviewId()).orElseThrow(); + PlotReview review = DataProvider.REVIEW.getReview(notification.reviewId()).orElseThrow(); player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(review.getPlot().getID())), GREEN))); Component tc = text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_SHOW_FEEDBACK), GOLD) @@ -651,7 +651,7 @@ public static void sendFeedbackMessage(@NotNull List notific .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.PLOT_NAME) + " " + LangUtil.getInstance().get(player, LangPaths.Review.FEEDBACK))); player.sendMessage(tc); - DataProvider.REVIEW.removeReviewNotification(notification.getReviewId(), notification.getUuid()); + DataProvider.REVIEW.removeReviewNotification(notification.reviewId(), notification.uuid()); if (notifications.size() != notifications.indexOf(notification) + 1) { player.sendMessage(empty()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java index 7006ddfc..8dd9bd38 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java @@ -1,19 +1,28 @@ -package com.alpsbte.plotsystem.core.system.review; - -public class BuildTeamToggleCriteria { - private final int buildTeamId; - private final ToggleCriteria criteria; +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ - public BuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { - this.buildTeamId = buildTeamId; - this.criteria = criteria; - } - - public int getBuildTeamId() { - return buildTeamId; - } +package com.alpsbte.plotsystem.core.system.review; - public ToggleCriteria getCriteria() { - return criteria; - } +public record BuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java index 1a206bdc..5680b54d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java @@ -1,21 +1,29 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.system.review; import java.util.UUID; -public class ReviewNotification { - private final int reviewId; - private final UUID uuid; - - public ReviewNotification(int reviewId, UUID uuid) { - this.reviewId = reviewId; - this.uuid = uuid; - } - - public int getReviewId() { - return reviewId; - } - - public UUID getUuid() { - return uuid; - } -} +public record ReviewNotification(int reviewId, UUID uuid) {} diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java index f48f5d3c..8a457af4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java @@ -1,27 +1,36 @@ +/* + * The MIT License (MIT) + * + * Copyright © 2021-2025, Alps BTE + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + package com.alpsbte.plotsystem.core.system.review; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import org.bukkit.entity.Player; -public class ToggleCriteria { - private final String criteriaName; - private final boolean isOptional; - - public ToggleCriteria(String criteriaName, boolean isOptional) { - this.criteriaName = criteriaName; - this.isOptional = isOptional; - } - - public String getCriteriaName() { - return criteriaName; - } +public record ToggleCriteria(String criteriaName, boolean isOptional) { public String getDisplayName(Player player) { return LangUtil.getInstance().get(player, LangPaths.Database.TOGGLE_CRITERIA + "." + criteriaName); } - - public boolean isOptional() { - return isOptional; - } } From dc846240f3650aaf8db76610db4f0697fe662486 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Wed, 27 Aug 2025 18:38:38 +0200 Subject: [PATCH 138/175] =?UTF-8?q?fix(tutorial):=20=F0=9F=A9=B9=20refacto?= =?UTF-8?q?r=20base=20block=20handling=20to=20support=20multiple=20block?= =?UTF-8?q?=20names=20and=20improve=20readability?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../system/tutorial/BeginnerTutorial.java | 49 +++++++++++++------ .../events/commands/LineCmdEventTask.java | 18 +++---- .../plotsystem/utils/io/TutorialPaths.java | 7 ++- .../resources/tutorial/tutorial_beginner.yml | 5 +- 4 files changed, 48 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java index d20500ce..a2f9e853 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2025, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -40,24 +40,44 @@ import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.ChatMessageTask; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.io.*; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; +import com.alpsbte.plotsystem.utils.io.ConfigUtil; +import com.alpsbte.plotsystem.utils.io.LangPaths; +import com.alpsbte.plotsystem.utils.io.LangUtil; +import com.alpsbte.plotsystem.utils.io.TutorialPaths; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.event.HoverEvent; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; import org.bukkit.block.data.BlockData; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; -import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.*; +import static com.alpsbte.alpslib.utils.AlpsUtils.deserialize; +import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.Delay; import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.Sound; +import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.TEXT_CLICK_HIGHLIGHT; +import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.TEXT_HIGHLIGHT_END; +import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.TEXT_HIGHLIGHT_START; +import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.getDocumentationLinks; +import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.setBlockAt; import static net.kyori.adventure.text.Component.text; -import static com.alpsbte.alpslib.utils.AlpsUtils.deserialize; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class BeginnerTutorial extends AbstractPlotTutorial { @@ -106,7 +126,7 @@ public void onTutorialComplete(UUID playerUUID) { Bukkit.getScheduler().runTaskLaterAsynchronously(PlotSystem.getPlugin(), () -> { sendTutorialCompletedTipMessage(getPlayer()); getPlayer().playSound(getPlayer().getLocation(), Utils.SoundUtils.NOTIFICATION_SOUND, 1f, 1f); - }, 20 * 7); + }, 20 * 7L); } private static class Stage1 extends AbstractPlotStage { @@ -312,8 +332,7 @@ public StageTimeline getTimeline() { } private static class Stage5 extends AbstractPlotStage { - private final static String BASE_BLOCK = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getString(TutorialPaths.Beginner.BASE_BLOCK); - private final static int BASE_BLOCK_ID = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getInt(TutorialPaths.Beginner.BASE_BLOCK_ID); + private static final List BASE_BLOCKS = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getStringList(TutorialPaths.Beginner.BASE_BLOCKS); protected Stage5(Player player, TutorialPlot plot) { super(player, 1, plot, 1); @@ -335,7 +354,7 @@ public List setMessages() { @Override protected List setTasks() { return LangUtil.getInstance().getList(getPlayer(), LangPaths.Tutorials.Beginner.STAGE5_TASKS, - TEXT_HIGHLIGHT_START + "//line " + BASE_BLOCK.toLowerCase() + TEXT_HIGHLIGHT_END); + TEXT_HIGHLIGHT_START + "//line " + BASE_BLOCKS.getFirst() + TEXT_HIGHLIGHT_END); } @Override @@ -364,7 +383,7 @@ public StageTimeline getTimeline() { }, Sound.NPC_TALK, false) .delay(Delay.TASK_START) .addTask(new PlotPermissionChangeTask(getPlayer(), false, true)) - .addTask(new LineCmdEventTask(getPlayer(), deserialize(getTasks().getFirst()), BASE_BLOCK, BASE_BLOCK_ID, buildingLinePoints, ((minPoint, maxPoint) -> { + .addTask(new LineCmdEventTask(getPlayer(), deserialize(getTasks().getFirst()), BASE_BLOCKS, buildingLinePoints, ((minPoint, maxPoint) -> { if (minPoint != null && maxPoint != null) { buildingLinePoints.remove(minPoint); @@ -381,8 +400,8 @@ public StageTimeline getTimeline() { } private static class Stage6 extends AbstractPlotStage { - private final static int HEIGHT = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getInt(TutorialPaths.Beginner.HEIGHT); - private final static int HEIGHT_OFFSET = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getInt(TutorialPaths.Beginner.HEIGHT_OFFSET); + private static final int HEIGHT = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getInt(TutorialPaths.Beginner.HEIGHT); + private static final int HEIGHT_OFFSET = ConfigUtil.getTutorialInstance().getBeginnerTutorial().getInt(TutorialPaths.Beginner.HEIGHT_OFFSET); protected Stage6(Player player, TutorialPlot plot) { super(player, 1, plot, 2); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java index 048e9a73..55a1653b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -40,7 +40,9 @@ import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; +import java.util.List; import java.util.Map; import java.util.Objects; @@ -53,8 +55,8 @@ public class LineCmdEventTask extends AbstractCmdEventTask { private Vector minPoint; private Vector maxPoint; - public LineCmdEventTask(Player player, Component assignmentMessage, String blockName, int blockId, Map linePoints, BiTaskAction lineCmdAction) { - super(player, "//line", new String[]{blockName, String.valueOf(blockId)}, assignmentMessage, linePoints.size(), true); + public LineCmdEventTask(Player player, Component assignmentMessage, @NotNull List blocks, @NotNull Map linePoints, BiTaskAction lineCmdAction) { + super(player, "//line", blocks.toArray(new String[0]), assignmentMessage, linePoints.size(), true); this.linePoints = linePoints; this.lineCmdAction = lineCmdAction; } @@ -83,8 +85,8 @@ protected void onCommand(boolean isValid, String[] args) { @Override public void performEvent(Event event) { - if (event instanceof PlayerInteractEvent) { - onPlayerInteractEvent((PlayerInteractEvent) event); + if (event instanceof PlayerInteractEvent playerInteractEvent) { + onPlayerInteractEvent(playerInteractEvent); } else super.performEvent(event); } @@ -108,11 +110,9 @@ private boolean isPointInLine(Vector point) { } private boolean drawLine() { - try { - EditSession editSession = WorldEdit.getInstance().newEditSession((new BukkitWorld(player.getWorld()))); + try (EditSession editSession = WorldEdit.getInstance().newEditSession((new BukkitWorld(player.getWorld())))) { editSession.drawLine(Objects.requireNonNull(BlockTypes.WHITE_WOOL).getDefaultState(), BlockVector3.at(minPoint.getX(), minPoint.getY(), minPoint.getZ()), BlockVector3.at(maxPoint.getX(), maxPoint.getY(), maxPoint.getZ()), 0, false); - editSession.close(); } catch (MaxChangedBlocksException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while drawing line!"), ex); return false; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java index 2ef2191b..3e5e7356 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java @@ -1,7 +1,7 @@ /* - * The MIT License (MIT) + * The MIT License (MIT) * - * Copyright © 2023, Alps BTE + * Copyright © 2021-2025, Alps BTE * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -33,8 +33,7 @@ public static final class Beginner { public static final String POINT_2 = TELEPORT_COORDINATES + "point-2"; public static final String POINT_3 = TELEPORT_COORDINATES + "point-3"; public static final String POINT_4 = TELEPORT_COORDINATES + "point-4"; - public static final String BASE_BLOCK = BEGINNER + "base-block"; - public static final String BASE_BLOCK_ID = BEGINNER + "base-block-id"; + public static final String BASE_BLOCKS = BEGINNER + "base-blocks"; public static final String HEIGHT = BEGINNER + "height"; public static final String HEIGHT_OFFSET = BEGINNER + "height-offset"; public static final String WINDOW_POINTS = BEGINNER + "window-points"; diff --git a/src/main/resources/tutorial/tutorial_beginner.yml b/src/main/resources/tutorial/tutorial_beginner.yml index e2f063f4..0a79569d 100644 --- a/src/main/resources/tutorial/tutorial_beginner.yml +++ b/src/main/resources/tutorial/tutorial_beginner.yml @@ -66,9 +66,8 @@ beginner: point-2: '3693367.0,-4531328.0' point-3: '3693370.0,-4531337.0' point-4: '3693357.0,-4531342.0' - # BaseBlock for the building outline - base-block: 'WHITE_WOOL' - base-block-id: 35 + # BaseBlocks for the building outline (multiple blocks or legacy id's are supported) + base-blocks: [ 'WHITE_WOOL', 'WHITE', '35', '35:0' ] # Height of the plot building, which must be calculated height: 7 height-offset: 1 From b3382cf40398a5d767e20e8f1530bda170b6568d Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 29 Sep 2025 10:53:28 +0200 Subject: [PATCH 139/175] Update dependencies for mc 1.21.8 Signed-off-by: Zoriot --- pom.xml | 32 ++++++++------ .../com/alpsbte/plotsystem/PlotSystem.java | 6 +-- .../plot/generator/PlotWorldGenerator.java | 42 ++++++++++++------- .../core/system/plot/utils/PlotUtils.java | 4 +- .../core/system/plot/world/PlotWorld.java | 15 ++++--- .../system/tutorial/utils/TutorialNPC.java | 10 ++--- .../com/alpsbte/plotsystem/utils/Utils.java | 9 ++-- src/main/resources/plugin.yml | 2 +- 8 files changed, 71 insertions(+), 49 deletions(-) diff --git a/pom.xml b/pom.xml index 680e26dd..4478937a 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ com.alpsbte PlotSystem - 4.1.4 + 4.2.0 @@ -99,9 +99,9 @@ - com.onarandombox.multiversecore - Multiverse-Core - 4.3.1 + org.mvplugins.multiverse.core + multiverse-core + 5.3.0 provided @@ -115,7 +115,7 @@ com.alpsbte canvas - 1.1 + 1.3 compile @@ -136,7 +136,7 @@ com.alpsbte.alpslib alpslib-io - 1.0.38 + 1.2.0 com.alpsbte.alpslib @@ -147,7 +147,7 @@ com.alpsbte.alpslib alpslib-utils - 1.3.4 + 1.3.5 compile @@ -187,24 +187,30 @@ - com.comphenix.protocol + net.dmulloy2 ProtocolLib - 5.1.0 + 5.4.0 provided de.oliver FancyNpcs - 2.4.0 + 2.7.0 provided li.cinnazeyy - LangLibs - 1.5 + LangLibs-API + 1.5.1 provided + + + commons-io + commons-io + 2.20.0 + @@ -246,7 +252,7 @@ src/main/java/ - ${project.artifactId}-${project.version}-${build.number} + ${project.artifactId}-${project.version}${build.number} org.apache.maven.plugins diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index 011bf148..0a907d5f 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -49,7 +49,6 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.ProtocolManager; -import com.onarandombox.MultiverseCore.MultiverseCore; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import de.oliver.fancynpcs.api.FancyNpcsPlugin; @@ -61,6 +60,7 @@ import org.bukkit.plugin.java.JavaPlugin; import org.ipvp.canvas.MenuFunctionListener; import org.jetbrains.annotations.NotNull; +import org.mvplugins.multiverse.core.MultiverseCoreApi; import java.io.IOException; import java.io.InputStream; @@ -346,8 +346,8 @@ public static String getMultiverseInventoriesConfigPath(String worldName) { /** * @return Multiverse-Core instance */ - public static MultiverseCore getMultiverseCore() { - return (MultiverseCore) plugin.getServer().getPluginManager().getPlugin("Multiverse-Core"); + public static MultiverseCoreApi getMultiverseCore() { + return MultiverseCoreApi.get(); } /** diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java index 15e10d5f..7b44be70 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java @@ -25,8 +25,6 @@ package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; -import com.onarandombox.MultiverseCore.api.MVWorldManager; -import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.flags.Flags; @@ -37,7 +35,12 @@ import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionContainer; import org.bukkit.*; +import org.bukkit.entity.SpawnCategory; import org.bukkit.generator.ChunkGenerator; +import org.mvplugins.multiverse.core.world.LoadedMultiverseWorld; +import org.mvplugins.multiverse.core.world.WorldManager; +import org.mvplugins.multiverse.core.world.options.ImportWorldOptions; +import org.mvplugins.multiverse.external.vavr.control.Option; import javax.annotation.Nonnull; import java.util.Objects; @@ -46,7 +49,7 @@ import static net.kyori.adventure.text.Component.text; public class PlotWorldGenerator { - private final MVWorldManager worldManager = PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager(); + private final WorldManager worldManager = PlotSystem.DependencyManager.getMultiverseCore().getWorldManager(); private WorldCreator worldCreator; private final String worldName; @@ -74,9 +77,13 @@ protected void generateWorld() { protected void createMultiverseWorld() throws Exception { // Check if world creator is configured and add new world to multiverse world manager if (worldCreator != null) { - if (!worldManager.isMVWorld(worldName)) - worldManager.addWorld(worldName, environment, null, worldType, false, - "VoidGen:{\"caves\":false,\"decoration\":false,\"mobs\":false,\"structures\":false}", false); + if (!worldManager.isLoadedWorld(worldName)) { + worldManager.importWorld(ImportWorldOptions.worldName(worldName) + .environment(environment) + .generator("VoidGen:{\"caves\":false,\"decoration\":false,\"mobs\":false,\"structures\":false}") + .useSpawnAdjust(false) + ); + } } else { throw new Exception("World Creator is not configured"); } @@ -84,7 +91,12 @@ protected void createMultiverseWorld() throws Exception { protected void configureWorld() { World bukkitWorld = Bukkit.getWorld(worldName); - MultiverseWorld mvWorld = worldManager.getMVWorld(bukkitWorld); + Option mvWorld = worldManager.getLoadedWorld(worldName); + + if (mvWorld.isEmpty()) { + PlotSystem.getPlugin().getComponentLogger().warn(text("Multiverse world" + worldName + " is not loaded! Skipping world configuration...")); + return; + } // Set world time to midday assert bukkitWorld != null; @@ -100,14 +112,14 @@ protected void configureWorld() { bukkitWorld.setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false); // Configure multiverse world - mvWorld.setAllowFlight(true); - mvWorld.setGameMode(GameMode.CREATIVE); - mvWorld.setEnableWeather(false); - mvWorld.setDifficulty(Difficulty.PEACEFUL); - mvWorld.setAllowAnimalSpawn(false); - mvWorld.setAllowMonsterSpawn(false); - mvWorld.setAutoLoad(false); - mvWorld.setKeepSpawnInMemory(false); + mvWorld.get().setAllowFlight(true); + mvWorld.get().setGameMode(GameMode.CREATIVE); + mvWorld.get().setAllowWeather(false); + mvWorld.get().setDifficulty(Difficulty.PEACEFUL); + mvWorld.get().getEntitySpawnConfig().getSpawnCategoryConfig(SpawnCategory.ANIMAL).setSpawn(false); + mvWorld.get().getEntitySpawnConfig().getSpawnCategoryConfig(SpawnCategory.MONSTER).setSpawn(false); + mvWorld.get().setAutoLoad(false); + mvWorld.get().setKeepSpawnInMemory(false); worldManager.saveWorldsConfig(); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index c33d6210..a1679c3a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -190,8 +190,8 @@ public static boolean isPlayerOnPlot(@NotNull AbstractPlot plot, Player player) return null; } - public static boolean isPlotWorld(World world) { - return PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().isMVWorld(world) && (PlotWorld.isOnePlotWorld(world.getName()) || PlotWorld.isCityPlotWorld(world.getName())); + public static boolean isPlotWorld(@NotNull World world) { + return PlotSystem.DependencyManager.getMultiverseCore().getWorldManager().isLoadedWorld(world) && (PlotWorld.isOnePlotWorld(world.getName()) || PlotWorld.isCityPlotWorld(world.getName())); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index b62db7ac..cbabe15c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -31,7 +31,6 @@ import com.alpsbte.plotsystem.core.system.plot.generator.AbstractPlotGenerator; import com.alpsbte.plotsystem.utils.Utils; import com.fastasyncworldedit.core.FaweAPI; -import com.onarandombox.MultiverseCore.MultiverseCore; import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.math.BlockVector3; @@ -46,6 +45,8 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.mvplugins.multiverse.core.MultiverseCoreApi; +import org.mvplugins.multiverse.core.world.options.DeleteWorldOptions; import java.io.File; import java.io.IOException; @@ -59,7 +60,7 @@ public class PlotWorld implements IWorld { public static final int MAX_WORLD_HEIGHT = 256; public static final int MIN_WORLD_HEIGHT = 5; - private final MultiverseCore mvCore = PlotSystem.DependencyManager.getMultiverseCore(); + private final MultiverseCoreApi mvCore = PlotSystem.DependencyManager.getMultiverseCore(); private final String worldName; private final AbstractPlot plot; @@ -81,7 +82,9 @@ public boolean regenWorld(@NotNull Class ge @Override public boolean deleteWorld() { if (isWorldGenerated() && loadWorld()) { - if (mvCore.getMVWorldManager().deleteWorld(getWorldName(), true, true) && mvCore.saveWorldConfig()) { + if (Boolean.TRUE.equals(mvCore.getWorldManager().getWorld(getWorldName()) + .map(world -> mvCore.getWorldManager().deleteWorld(DeleteWorldOptions.world(world)).isSuccess()) + .getOrElse(false)) && mvCore.getWorldManager().saveWorldsConfig().isSuccess()) { try { File multiverseInventoriesConfig = new File(PlotSystem.DependencyManager.getMultiverseInventoriesConfigPath(getWorldName())); File worldGuardConfig = new File(PlotSystem.DependencyManager.getWorldGuardConfigPath(getWorldName())); @@ -102,7 +105,7 @@ public boolean loadWorld() { if (isWorldGenerated()) { if (isWorldLoaded()) { return true; - } else return mvCore.getMVWorldManager().loadWorld(getWorldName()) || isWorldLoaded(); + } else return mvCore.getWorldManager().loadWorld(getWorldName()).isSuccess() || isWorldLoaded(); } else PlotSystem.getPlugin().getComponentLogger().warn(text("Could not load world " + worldName + " because it is not generated!")); return false; } @@ -145,7 +148,7 @@ public Location getSpawnPoint(BlockVector3 plotVector) { } // Set spawn point 1 block above the highest block at the spawn location - spawnLocation.setY(getBukkitWorld().getHighestBlockYAt((int) spawnLocation.getX(), (int) spawnLocation.getZ()) + 1); + spawnLocation.setY(getBukkitWorld().getHighestBlockYAt((int) spawnLocation.getX(), (int) spawnLocation.getZ()) + 1d); return spawnLocation; } return null; @@ -199,7 +202,7 @@ public boolean isWorldLoaded() { @Override public boolean isWorldGenerated() { - return mvCore.getMVWorldManager().getMVWorld(worldName) != null || mvCore.getMVWorldManager().getUnloadedWorlds().contains(worldName); + return mvCore.getWorldManager().getWorld(worldName).isDefined(); } private ProtectedRegion getRegion(String regionName) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java index 87c97b00..bed2b72f 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java @@ -27,7 +27,7 @@ import de.oliver.fancynpcs.api.FancyNpcsPlugin; import de.oliver.fancynpcs.api.Npc; import de.oliver.fancynpcs.api.NpcData; -import de.oliver.fancynpcs.api.utils.SkinFetcher; +import de.oliver.fancynpcs.api.skins.SkinData; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; @@ -44,7 +44,7 @@ public class TutorialNPC { private final String id; private final String displayName; private final String interactionPrompt; - private final SkinFetcher.SkinData skin; + private final SkinData skin; private Npc npc; private TutorialNPCHologram hologram; @@ -61,7 +61,7 @@ public TutorialNPC(String npcId, String npcDisplayName, String npcInteractionPro this.id = npcId; this.displayName = npcDisplayName; this.interactionPrompt = npcInteractionPrompt; - this.skin = new SkinFetcher.SkinData(npcId, npcSknTexture, npcSkinSignature); + this.skin = new SkinData(npcId, SkinData.SkinVariant.AUTO, npcSknTexture, npcSkinSignature); } /** @@ -74,7 +74,7 @@ public void create(Location spawnPos) { NpcData npcData = new NpcData(id, UUID.randomUUID(), spawnPos); npc = FancyNpcsPlugin.get().getNpcAdapter().apply(npcData); - npc.getData().setSkin(skin); + npc.getData().setSkinData(skin); npc.getData().setDisplayName(EMPTY_TAG); npc.getData().setTurnToPlayer(true); npc.setSaveToFile(false); @@ -158,7 +158,7 @@ public String getInteractionPrompt() { return interactionPrompt; } - public SkinFetcher.SkinData getSkin() { + public SkinData getSkin() { return skin; } } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index ee74b6e0..fb2206a7 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -36,7 +36,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.CustomHeads; -import com.onarandombox.MultiverseCore.api.MultiverseWorld; import com.sk89q.worldedit.math.BlockVector2; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; @@ -53,6 +52,8 @@ import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.mvplugins.multiverse.core.world.LoadedMultiverseWorld; +import org.mvplugins.multiverse.external.vavr.control.Option; import java.sql.SQLException; import java.time.LocalDateTime; @@ -79,14 +80,14 @@ public static Location getSpawnLocation() { if (!Objects.requireNonNull(config.getString(ConfigPaths.SPAWN_WORLD)).equalsIgnoreCase("default")) { try { - MultiverseWorld spawnWorld = PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().getMVWorld(config.getString(ConfigPaths.SPAWN_WORLD)); - return spawnWorld.getSpawnLocation(); + Option spawnWorld = PlotSystem.DependencyManager.getMultiverseCore().getWorldManager().getLoadedWorld(config.getString(ConfigPaths.SPAWN_WORLD)); + return spawnWorld.get().getSpawnLocation(); } catch (Exception ignore) { PlotSystem.getPlugin().getComponentLogger().warn(text("Could not find %s in multiverse config!"), ConfigPaths.SPAWN_WORLD); } } - return PlotSystem.DependencyManager.getMultiverseCore().getMVWorldManager().getSpawnWorld().getSpawnLocation(); + return PlotSystem.DependencyManager.getMultiverseCore().getWorldManager().getDefaultWorld().get().getSpawnLocation(); } public static void updatePlayerInventorySlots(Player player) { diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 0e8923cf..190643ce 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ main: com.alpsbte.plotsystem.PlotSystem -version: 4.1.3 +version: 4.2.0 api-version: "1.21" name: Plot-System author: R3tuxn & Cinnazeyy From d362fd5b046a4a5cda953b8588ac98bd571d8236 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Tue, 30 Sep 2025 11:15:21 +0200 Subject: [PATCH 140/175] Update MIT license text to allow GitHub detection --- LICENSE.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/LICENSE.txt b/LICENSE.txt index dae462c7..2ff6e64f 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,7 @@ MIT License -Copyright (c) 2021 Alps BTE +Copyright (c) Alps BTE +Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 8bf1374458f357d683e27b8972806eb65686580c Mon Sep 17 00:00:00 2001 From: Zoriot Date: Tue, 30 Sep 2025 11:19:21 +0200 Subject: [PATCH 141/175] style: remove copyright from individual files --- .../com/alpsbte/plotsystem/PlotSystem.java | 32 +++---------- .../plotsystem/commands/BaseCommand.java | 24 ---------- .../plotsystem/commands/CMD_Companion.java | 24 ---------- .../plotsystem/commands/CMD_Plots.java | 24 ---------- .../alpsbte/plotsystem/commands/CMD_Tpll.java | 24 ---------- .../plotsystem/commands/CMD_Tutorial.java | 24 ---------- .../plotsystem/commands/CommandManager.java | 26 +--------- .../alpsbte/plotsystem/commands/ICommand.java | 24 ---------- .../plotsystem/commands/SubCommand.java | 24 ---------- .../commands/admin/CMD_DeletePlot.java | 24 ---------- .../commands/admin/CMD_PReload.java | 24 ---------- .../commands/admin/CMD_SetLeaderboard.java | 24 ---------- .../commands/admin/setup/CMD_Setup.java | 24 ---------- .../admin/setup/CMD_Setup_BuildTeam.java | 24 ---------- .../commands/admin/setup/CMD_Setup_City.java | 24 ---------- .../admin/setup/CMD_Setup_Country.java | 24 ---------- .../admin/setup/CMD_Setup_Difficulty.java | 28 ++--------- .../admin/setup/CMD_Setup_ReviewCriteria.java | 24 ---------- .../admin/setup/CMD_Setup_Server.java | 24 ---------- .../plotsystem/commands/plot/CMD_Plot.java | 24 ---------- .../commands/plot/CMD_Plot_Abandon.java | 24 ---------- .../commands/plot/CMD_Plot_Feedback.java | 24 ---------- .../commands/plot/CMD_Plot_Invite.java | 26 +--------- .../commands/plot/CMD_Plot_Links.java | 24 ---------- .../commands/plot/CMD_Plot_Members.java | 24 ---------- .../commands/plot/CMD_Plot_Submit.java | 24 ---------- .../commands/plot/CMD_Plot_Teleport.java | 24 ---------- .../commands/plot/CMD_Plot_UndoSubmit.java | 24 ---------- .../commands/review/CMD_EditFeedback.java | 24 ---------- .../commands/review/CMD_EditPlot.java | 24 ---------- .../commands/review/CMD_Review.java | 24 ---------- .../commands/review/CMD_UndoReview.java | 24 ---------- .../plotsystem/core/EventListener.java | 24 ---------- .../core/database/DataProvider.java | 34 ++++--------- .../database/providers/BuildTeamProvider.java | 24 ---------- .../database/providers/BuilderProvider.java | 31 +++--------- .../providers/CityProjectProvider.java | 24 ---------- .../database/providers/CountryProvider.java | 24 ---------- .../providers/DifficultyProvider.java | 24 ---------- .../core/database/providers/PlotProvider.java | 24 ---------- .../database/providers/ReviewProvider.java | 24 ---------- .../database/providers/ServerProvider.java | 24 ---------- .../providers/TutorialPlotProvider.java | 24 ---------- .../core/holograms/HologramConfiguration.java | 24 ---------- .../core/holograms/PlotTutorialHologram.java | 33 +++---------- .../leaderboards/LeaderboardTimeframe.java | 24 ---------- .../leaderboards/ScoreLeaderboard.java | 30 ++---------- .../plotsystem/core/menus/AbstractMenu.java | 24 ---------- .../core/menus/AbstractPaginatedMenu.java | 24 ---------- .../core/menus/BuilderUtilitiesMenu.java | 24 ---------- .../plotsystem/core/menus/FeedbackMenu.java | 32 +++---------- .../core/menus/PlayerPlotsMenu.java | 32 +++---------- .../core/menus/PlotActionsMenu.java | 30 ++---------- .../plotsystem/core/menus/PlotMemberMenu.java | 28 ++--------- .../plotsystem/core/menus/PlotTypeMenu.java | 28 ++--------- .../plotsystem/core/menus/SettingsMenu.java | 24 ---------- .../core/menus/SpecialToolsMenu.java | 24 ---------- .../core/menus/companion/CityProjectMenu.java | 24 ---------- .../core/menus/companion/CompanionMenu.java | 35 ++++---------- .../core/menus/companion/ContinentMenu.java | 24 ---------- .../core/menus/companion/CountryMenu.java | 31 +++--------- .../core/menus/review/ReviewMenu.java | 24 ---------- .../core/menus/review/ReviewPlotMenu.java | 31 +++--------- .../menus/review/ReviewPlotTogglesMenu.java | 24 ---------- .../menus/tutorial/TutorialStagesMenu.java | 31 +++--------- .../core/menus/tutorial/TutorialsMenu.java | 32 +++---------- .../plotsystem/core/system/BuildTeam.java | 24 ---------- .../plotsystem/core/system/Builder.java | 26 +--------- .../plotsystem/core/system/CityProject.java | 32 +++---------- .../plotsystem/core/system/Country.java | 24 ---------- .../plotsystem/core/system/Difficulty.java | 24 ---------- .../core/system/plot/AbstractPlot.java | 24 ---------- .../plotsystem/core/system/plot/Plot.java | 24 ---------- .../core/system/plot/TutorialPlot.java | 24 ---------- .../plot/generator/AbstractPlotGenerator.java | 24 ---------- .../plot/generator/DefaultPlotGenerator.java | 24 ---------- .../plot/generator/PlotWorldGenerator.java | 32 +++---------- .../plot/generator/TutorialPlotGenerator.java | 24 ---------- .../system/plot/utils/PlotPermissions.java | 24 ---------- .../core/system/plot/utils/PlotType.java | 24 ---------- .../core/system/plot/utils/PlotUtils.java | 24 ---------- .../core/system/plot/world/CityPlotWorld.java | 24 ---------- .../core/system/plot/world/IWorld.java | 24 ---------- .../core/system/plot/world/OnePlotWorld.java | 26 +--------- .../core/system/plot/world/PlotWorld.java | 24 ---------- .../review/BuildTeamToggleCriteria.java | 24 ---------- .../core/system/review/PlotReview.java | 24 ---------- .../system/review/ReviewNotification.java | 24 ---------- .../core/system/review/ToggleCriteria.java | 24 ---------- .../system/tutorial/AbstractPlotTutorial.java | 31 +++--------- .../system/tutorial/AbstractTutorial.java | 35 ++++---------- .../tutorial/AbstractTutorialHologram.java | 29 ++--------- .../system/tutorial/BeginnerTutorial.java | 24 ---------- .../core/system/tutorial/PlotTutorial.java | 24 ---------- .../core/system/tutorial/Tutorial.java | 26 +--------- .../system/tutorial/TutorialCategory.java | 24 ---------- .../tutorial/TutorialEventListener.java | 29 ++--------- .../tutorial/stage/AbstractPlotStage.java | 25 ---------- .../system/tutorial/stage/AbstractStage.java | 24 ---------- .../system/tutorial/stage/StageTimeline.java | 39 +++++---------- .../tutorial/stage/TutorialTimeline.java | 24 ---------- .../system/tutorial/stage/TutorialWorld.java | 24 ---------- .../tutorial/stage/tasks/AbstractTask.java | 26 +--------- .../tutorial/stage/tasks/DelayTask.java | 24 ---------- .../stage/tasks/PlotPermissionChangeTask.java | 24 ---------- .../stage/tasks/PlotSchematicPasteTask.java | 24 ---------- .../tutorial/stage/tasks/TeleportTask.java | 24 ---------- .../stage/tasks/events/BuildEventTask.java | 24 ---------- .../stage/tasks/events/ChatEventTask.java | 24 ---------- .../stage/tasks/events/EventTask.java | 24 ---------- .../tasks/events/NpcInteractEventTask.java | 24 ---------- .../tasks/events/TeleportPointEventTask.java | 24 ---------- .../events/commands/AbstractCmdEventTask.java | 24 ---------- .../events/commands/ContinueCmdEventTask.java | 24 ---------- .../events/commands/LineCmdEventTask.java | 24 ---------- .../events/commands/WandCmdEventTask.java | 24 ---------- .../stage/tasks/message/ChatMessageTask.java | 32 ++----------- .../tasks/message/CreateHologramTask.java | 26 +--------- .../tasks/message/DeleteHologramTask.java | 24 ---------- .../system/tutorial/utils/TutorialNPC.java | 24 ---------- .../tutorial/utils/TutorialNPCHologram.java | 30 ++---------- .../utils/TutorialNPCTurnTracker.java | 24 ---------- .../system/tutorial/utils/TutorialUtils.java | 28 ++--------- .../plotsystem/utils/DependencyManager.java | 24 ---------- .../utils/PlotMemberInvitation.java | 29 ++--------- .../alpsbte/plotsystem/utils/ShortLink.java | 24 ---------- .../com/alpsbte/plotsystem/utils/Utils.java | 24 ---------- .../plotsystem/utils/chat/ChatInput.java | 28 ++--------- .../utils/chat/PlayerFeedbackChatInput.java | 26 +--------- .../utils/chat/PlayerInviteeChatInput.java | 26 +--------- .../conversion/CoordinateConversion.java | 26 +--------- .../plotsystem/utils/enums/Category.java | 24 ---------- .../plotsystem/utils/enums/Continent.java | 26 +--------- .../utils/enums/PlotDifficulty.java | 24 ---------- .../alpsbte/plotsystem/utils/enums/Slot.java | 24 ---------- .../plotsystem/utils/enums/Status.java | 24 ---------- .../plotsystem/utils/io/ConfigPaths.java | 24 ---------- .../plotsystem/utils/io/ConfigUtil.java | 24 ---------- .../plotsystem/utils/io/LangPaths.java | 24 ---------- .../alpsbte/plotsystem/utils/io/LangUtil.java | 26 +--------- .../plotsystem/utils/io/TutorialPaths.java | 24 ---------- .../plotsystem/utils/items/BaseItems.java | 24 ---------- .../plotsystem/utils/items/MenuItems.java | 29 ++--------- src/main/resources/DATABASE.sql | 48 ------------------- 144 files changed, 178 insertions(+), 3532 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java index cacd4c3b..56611342 100644 --- a/src/main/java/com/alpsbte/plotsystem/PlotSystem.java +++ b/src/main/java/com/alpsbte/plotsystem/PlotSystem.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; @@ -63,7 +39,13 @@ import java.util.UUID; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; +import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; public class PlotSystem extends JavaPlugin { private static PlotSystem plugin; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java b/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java index b308ac4c..37098a61 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import com.alpsbte.plotsystem.utils.Utils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java index c892c437..006d06a7 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import com.alpsbte.plotsystem.core.menus.companion.CompanionMenu; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java index f1f830c2..4d895582 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index 9183f83c..de3fa0a5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java index ba87ce34..595ce97b 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java index 86b8c5c1..4eef4a05 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import com.alpsbte.plotsystem.PlotSystem; @@ -30,9 +6,9 @@ import com.alpsbte.plotsystem.commands.admin.CMD_SetLeaderboard; import com.alpsbte.plotsystem.commands.admin.setup.CMD_Setup; import com.alpsbte.plotsystem.commands.plot.CMD_Plot; +import com.alpsbte.plotsystem.commands.review.CMD_EditFeedback; import com.alpsbte.plotsystem.commands.review.CMD_EditPlot; import com.alpsbte.plotsystem.commands.review.CMD_Review; -import com.alpsbte.plotsystem.commands.review.CMD_EditFeedback; import com.alpsbte.plotsystem.commands.review.CMD_UndoReview; import java.util.ArrayList; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/ICommand.java b/src/main/java/com/alpsbte/plotsystem/commands/ICommand.java index 39148409..80312607 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/ICommand.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/ICommand.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import org.bukkit.command.CommandSender; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/SubCommand.java b/src/main/java/com/alpsbte/plotsystem/commands/SubCommand.java index 4250fc4e..ae6fbd9a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/SubCommand.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/SubCommand.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands; import com.alpsbte.plotsystem.utils.io.LangUtil; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java index 530b72f5..72d6539b 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java index 24c4d125..409a60e4 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_PReload.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java index a35a2cfc..f2d18813 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java index a13002b5..05b64e36 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.plotsystem.commands.BaseCommand; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index c0439d3c..0487399c 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index 28f47f57..ef647437 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index d51f417c..f9bcfe22 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.plotsystem.commands.BaseCommand; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java index b74f466e..599e40c5 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; @@ -36,7 +12,9 @@ import java.util.Optional; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; public class CMD_Setup_Difficulty extends SubCommand { diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java index a639b1ed..e8054840 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.plotsystem.commands.BaseCommand; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index 410cdb87..cded4398 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.admin.setup; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java index 825ba9eb..765c61cf 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.plotsystem.commands.BaseCommand; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java index 1cb48d46..0a9f0fbb 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java index 7d1b51ca..23f77fe4 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java index b21a3181..67450e91 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java @@ -1,35 +1,11 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.PlotMemberInvitation; import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java index 3fd369b2..b3dfddae 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Links.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java index 0c752761..6d013f95 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java index e93a3284..0dfc8834 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index 5f7b2f38..b4c9033b 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java index b4a6bebc..d73e2006 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index 1db181db..dbce4751 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.review; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 8a51b596..26423934 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.review; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 2b02b250..4330d5d0 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.review; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index d5a9a90c..c1c76cf9 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.commands.review; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index e5cbe9ff..c117c199 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java index a1dba9df..2e557d18 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/DataProvider.java @@ -1,30 +1,14 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database; -import com.alpsbte.plotsystem.core.database.providers.*; +import com.alpsbte.plotsystem.core.database.providers.BuildTeamProvider; +import com.alpsbte.plotsystem.core.database.providers.BuilderProvider; +import com.alpsbte.plotsystem.core.database.providers.CityProjectProvider; +import com.alpsbte.plotsystem.core.database.providers.CountryProvider; +import com.alpsbte.plotsystem.core.database.providers.DifficultyProvider; +import com.alpsbte.plotsystem.core.database.providers.PlotProvider; +import com.alpsbte.plotsystem.core.database.providers.ReviewProvider; +import com.alpsbte.plotsystem.core.database.providers.ServerProvider; +import com.alpsbte.plotsystem.core.database.providers.TutorialPlotProvider; public final class DataProvider { public static final BuilderProvider BUILDER = new BuilderProvider(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java index 5935a4b6..f9ebdec2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuildTeamProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index 5e111df6..c8070258 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; @@ -35,7 +11,12 @@ import org.jetbrains.annotations.NotNull; import java.sql.ResultSet; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; public class BuilderProvider { protected static final Map BUILDERS = new HashMap<>(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 6fea3bcf..10e87570 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java index 7c9e32ff..df759ce1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CountryProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java index 1acd026e..95d6d291 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/DifficultyProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index c0320f72..00384c0c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index 5e229750..f2d5aaac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java index fcb884dc..6da3f21a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ServerProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java index 33f0b428..ae9e4660 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/TutorialPlotProvider.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.database.providers; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramConfiguration.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramConfiguration.java index 8d2d313a..b42cbcca 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramConfiguration.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/HologramConfiguration.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.holograms; public interface HologramConfiguration { diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotTutorialHologram.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotTutorialHologram.java index 5e729f94..9ed7dd9c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotTutorialHologram.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/PlotTutorialHologram.java @@ -1,32 +1,8 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.holograms; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorialHologram; -import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.ChatMessageTask; +import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.Component; @@ -35,7 +11,12 @@ import org.bukkit.Sound; import org.bukkit.entity.Player; -import static org.bukkit.ChatColor.*; +import static org.bukkit.ChatColor.BOLD; +import static org.bukkit.ChatColor.DARK_GRAY; +import static org.bukkit.ChatColor.GOLD; +import static org.bukkit.ChatColor.GRAY; +import static org.bukkit.ChatColor.GREEN; +import static org.bukkit.ChatColor.YELLOW; public class PlotTutorialHologram extends AbstractTutorialHologram { public PlotTutorialHologram(Player player, int plotTutorialId, int holoId, String content) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java index dde38049..dc722dd0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/LeaderboardTimeframe.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.holograms.leaderboards; import com.alpsbte.plotsystem.utils.io.ConfigPaths; diff --git a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java index c1ca5ef4..e4ec49e2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/core/holograms/leaderboards/ScoreLeaderboard.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.holograms.leaderboards; import com.alpsbte.alpslib.hologram.DecentHologramPagedDisplay; @@ -36,7 +12,11 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.logging.Level; public class ScoreLeaderboard extends DecentHologramPagedDisplay implements HologramConfiguration { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java index 0dfc4ce4..fd0df002 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java index 8c52640e..4fc32722 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2022, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java index 144dba7b..7a0b5fb9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 1113caaa..bc620ab7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; @@ -44,7 +20,13 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class FeedbackMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 334b7c01..2a585e52 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; @@ -50,7 +26,13 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class PlayerPlotsMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 10ffa1ac..bc0ad058 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -44,7 +20,11 @@ import org.ipvp.canvas.mask.Mask; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class PlotActionsMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index b2ed00f7..d272c4b8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; @@ -50,7 +26,9 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class PlotMemberMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index d7e57697..a28aa952 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -42,7 +18,9 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.RED; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class PlotTypeMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java index 67c1ec93..74dfc848 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java index 2d904e19..b41a26d1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index 0bccffc8..a705108a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.companion; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index fae7e8d4..af88582e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.companion; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -51,12 +27,19 @@ import org.ipvp.canvas.Menu; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import java.util.function.Consumer; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class CompanionMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java index 068d4c95..893afd20 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.companion; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index e6aa5cad..80191bf7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.companion; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -53,7 +29,12 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class CountryMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index 63eebd08..bdfb7c00 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.review; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index 7120d4e7..29c80eab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.review; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -53,7 +29,12 @@ import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class ReviewPlotMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 953db0fa..68e96739 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.review; import com.alpsbte.alpslib.utils.item.ItemBuilder; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java index 19f59cd4..eb964d53 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.tutorial; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -47,7 +23,12 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; -import static net.md_5.bungee.api.ChatColor.*; +import static net.md_5.bungee.api.ChatColor.AQUA; +import static net.md_5.bungee.api.ChatColor.BOLD; +import static net.md_5.bungee.api.ChatColor.GREEN; +import static net.md_5.bungee.api.ChatColor.RED; +import static net.md_5.bungee.api.ChatColor.WHITE; +import static net.md_5.bungee.api.ChatColor.YELLOW; public class TutorialStagesMenu extends AbstractMenu { private static final int TOTAL_STAGES_ROWS = 2; diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index fa22481e..630a9723 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.menus.tutorial; import com.alpsbte.alpslib.utils.head.AlpsHeadUtils; @@ -51,7 +27,13 @@ import org.ipvp.canvas.mask.Mask; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; +import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class TutorialsMenu extends AbstractMenu { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java index e9a5bd3e..743cdbde 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/BuildTeam.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2022, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DataProvider; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index ed2cc509..9171c7f0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.PlotSystem; @@ -33,7 +9,7 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; -import java.util.*; +import java.util.UUID; public class Builder { private final UUID uuid; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index b407f3a4..cd1adaf2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -43,7 +19,13 @@ import java.util.concurrent.ExecutionException; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class CityProject { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index f9edbc70..509c8ba0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DataProvider; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java b/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java index b347d1a2..65e9a293 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Difficulty.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system; import com.alpsbte.plotsystem.core.database.DataProvider; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index a8ea7b8f..6b652386 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index 387ebd5a..cd5f2265 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index 2e457932..17e3b3da 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index f85c53ac..6b168e97 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 434df2c5..3071a704 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java index 2482bb4a..4f466c27 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/PlotWorldGenerator.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; @@ -37,7 +13,13 @@ import com.sk89q.worldguard.protection.managers.storage.StorageException; import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; import com.sk89q.worldguard.protection.regions.RegionContainer; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.Difficulty; +import org.bukkit.GameMode; +import org.bukkit.GameRule; +import org.bukkit.World; +import org.bukkit.WorldCreator; +import org.bukkit.WorldType; import org.bukkit.generator.ChunkGenerator; import javax.annotation.Nonnull; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java index 1b3028e2..b5662f25 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/TutorialPlotGenerator.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.generator; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java index be605930..e0cf41e8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotPermissions.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.utils; import com.alpsbte.plotsystem.core.system.plot.world.PlotWorld; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotType.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotType.java index 15b7b5a7..645a3cb2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotType.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotType.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.utils; public enum PlotType { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 582d183d..6b2d6aa2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.utils; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index b3152dc0..446d2710 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.world; import com.alpsbte.plotsystem.core.system.plot.AbstractPlot; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java index bca5b9bf..bf5cf74a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/IWorld.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2022, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.world; import com.alpsbte.plotsystem.core.system.plot.generator.AbstractPlotGenerator; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index 94a1a1cb..8ea21905 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.world; import com.alpsbte.plotsystem.PlotSystem; @@ -30,9 +6,9 @@ import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; import com.alpsbte.plotsystem.core.system.plot.generator.AbstractPlotGenerator; +import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; import com.alpsbte.plotsystem.core.system.plot.generator.TutorialPlotGenerator; import com.alpsbte.plotsystem.core.system.plot.utils.PlotType; -import com.alpsbte.plotsystem.core.system.plot.generator.DefaultPlotGenerator; import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java index ce0ccadb..d21e63be 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/PlotWorld.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.plot.world; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java index 8dd9bd38..9bcba6ad 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/BuildTeamToggleCriteria.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.review; public record BuildTeamToggleCriteria(int buildTeamId, ToggleCriteria criteria) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 79b47b7a..6771b769 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.review; import com.alpsbte.plotsystem.core.database.DataProvider; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java index 5680b54d..4944c900 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ReviewNotification.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.review; import java.util.UUID; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java index 8a457af4..4659374c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/ToggleCriteria.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.review; import com.alpsbte.plotsystem.utils.io.LangPaths; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index 4e1dad5d..4a275a7d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import com.alpsbte.alpslib.utils.AlpsUtils; @@ -54,7 +30,12 @@ import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.Sound; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public abstract class AbstractPlotTutorial extends AbstractTutorial implements PlotTutorial { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java index 2c006b96..85d1fe45 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java @@ -1,40 +1,21 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.system.tutorial.stage.AbstractStage; import com.alpsbte.plotsystem.core.system.tutorial.stage.StageTimeline; -import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPC; import com.alpsbte.plotsystem.core.system.tutorial.stage.TutorialWorld; -import org.bukkit.*; +import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPC; +import org.bukkit.Bukkit; +import org.bukkit.World; import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import java.util.stream.Collectors; import static net.kyori.adventure.text.Component.text; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java index 529ba342..80ef5b10 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; @@ -35,7 +11,10 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; -import java.util.*; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; public abstract class AbstractTutorialHologram extends DecentHologramDisplay { protected static final String READ_EMOJI = "✅"; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java index a2f9e853..5695ffe4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import com.alpsbte.alpslib.utils.AlpsUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java index 0dfce561..261e52fc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/PlotTutorial.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import java.io.IOException; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java index caec5485..f8bee326 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/Tutorial.java @@ -1,32 +1,8 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import com.alpsbte.plotsystem.core.system.tutorial.stage.StageTimeline; -import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPC; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.AbstractTask; +import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialNPC; import org.bukkit.World; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java index f101e127..cf441093 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialCategory.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; public enum TutorialCategory { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java index 4e3e9f0e..6a366c72 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/TutorialEventListener.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.EventTask; @@ -31,7 +7,10 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPlaceEvent; -import org.bukkit.event.player.*; +import org.bukkit.event.player.PlayerChangedWorldEvent; +import org.bukkit.event.player.PlayerCommandPreprocessEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java index 3c3113ca..33cd80c3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java @@ -1,28 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - - package com.alpsbte.plotsystem.core.system.tutorial.stage; import com.alpsbte.plotsystem.core.system.plot.TutorialPlot; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java index 384de008..4b742d46 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractStage.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorialHologram; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java index 4725b18d..607e98f0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java @@ -1,40 +1,18 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorialHologram; -import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.*; +import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.AbstractTask; +import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.DelayTask; +import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.TeleportTask; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.ChatEventTask; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.NpcInteractEventTask; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.TeleportPointEventTask; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.commands.ContinueCmdEventTask; +import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.ChatMessageTask; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.CreateHologramTask; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.DeleteHologramTask; -import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message.ChatMessageTask; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Sound; @@ -43,7 +21,14 @@ import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; public class StageTimeline implements TutorialTimeline { private static final Map activeTimelines = new HashMap<>(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialTimeline.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialTimeline.java index 302c75a3..4e2ee561 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialTimeline.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialTimeline.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.AbstractTask; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialWorld.java index e98255bd..1cebad50 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/TutorialWorld.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java index 7b24f31f..f8bf5a10 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java @@ -1,32 +1,8 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks; import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; -import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.core.system.tutorial.stage.StageTimeline; +import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.entity.Player; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/DelayTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/DelayTask.java index 42de838c..a449dd98 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/DelayTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/DelayTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotPermissionChangeTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotPermissionChangeTask.java index 7a251233..0cefab38 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotPermissionChangeTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotPermissionChangeTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java index 118f5983..bc7e7e10 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/PlotSchematicPasteTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/TeleportTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/TeleportTask.java index c9e02be7..650066b7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/TeleportTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/TeleportTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java index cd58c450..d920cd6d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java index d02176a7..38be3773 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/ChatEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events; import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/EventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/EventTask.java index b59e05dd..df82d5c7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/EventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/EventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events; import org.bukkit.event.Event; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/NpcInteractEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/NpcInteractEventTask.java index 483bda5e..4c2b8dc2 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/NpcInteractEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/NpcInteractEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java index 10f05cba..fb2a5736 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/TeleportPointEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java index 97b7f3df..573d598d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.commands; import com.alpsbte.plotsystem.core.system.tutorial.TutorialEventListener; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/ContinueCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/ContinueCmdEventTask.java index 74a7a3e3..ad897cd3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/ContinueCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/ContinueCmdEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.commands; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java index 55a1653b..199c9284 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/LineCmdEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.commands; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/WandCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/WandCmdEventTask.java index a896b01c..2126800a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/WandCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/WandCmdEventTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.events.commands; import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java index 8c449f11..4ec67f7d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java @@ -1,32 +1,8 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; -import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.AbstractTask; +import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.Component; @@ -35,8 +11,10 @@ import org.bukkit.Sound; import org.bukkit.entity.Player; -import static net.kyori.adventure.text.Component.*; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.Component.text; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; public class ChatMessageTask extends AbstractTask { private final Object[] messages; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/CreateHologramTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/CreateHologramTask.java index f4b0325c..faf9ad03 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/CreateHologramTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/CreateHologramTask.java @@ -1,32 +1,8 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorialHologram; -import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.AbstractTask; +import com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils; import eu.decentsoftware.holograms.event.HologramClickEvent; import net.kyori.adventure.text.Component; import org.bukkit.entity.Player; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/DeleteHologramTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/DeleteHologramTask.java index 55193d17..cec5b966 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/DeleteHologramTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/DeleteHologramTask.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.stage.tasks.message; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java index 87c97b00..ea9a27ad 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2024, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.utils; import de.oliver.fancynpcs.api.FancyNpcsPlugin; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCHologram.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCHologram.java index b0c6595d..9b7058f5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCHologram.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCHologram.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2024, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.utils; import com.alpsbte.alpslib.hologram.DecentHologramDisplay; @@ -32,10 +8,10 @@ import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; -import java.util.UUID; -import java.util.List; -import java.util.Collections; import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; public class TutorialNPCHologram extends DecentHologramDisplay { private static final double NPC_HOLOGRAM_Y = 2.3; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java index dbfb21f9..fb451c33 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPCTurnTracker.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2024, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.utils; import com.alpsbte.plotsystem.core.system.tutorial.AbstractTutorial; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java index cdcdeecf..f8ebd445 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.core.system.tutorial.utils; import net.kyori.adventure.text.Component; @@ -35,7 +11,9 @@ import java.util.List; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; public class TutorialUtils { public static final String TEXT_HIGHLIGHT_START = "", TEXT_HIGHLIGHT_END = ""; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java b/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java index 65edb5c7..64439727 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/DependencyManager.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java index 5c825e14..cc36d77a 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils; import com.alpsbte.alpslib.utils.AlpsUtils; @@ -43,7 +19,10 @@ import static com.alpsbte.plotsystem.core.system.tutorial.utils.TutorialUtils.TEXT_HIGHLIGHT_START; import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class PlotMemberInvitation { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/ShortLink.java b/src/main/java/com/alpsbte/plotsystem/utils/ShortLink.java index 3881bcda..cb429c3e 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/ShortLink.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/ShortLink.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils; import com.alpsbte.plotsystem.PlotSystem; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 5b7419d6..c34de5c3 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils; import com.alpsbte.alpslib.io.database.SqlHelper; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/chat/ChatInput.java b/src/main/java/com/alpsbte/plotsystem/utils/chat/ChatInput.java index cc035348..9fe30bf0 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/chat/ChatInput.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/chat/ChatInput.java @@ -1,31 +1,9 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.chat; import java.time.LocalDateTime; -import java.util.*; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; public interface ChatInput { Map awaitChatInput = new HashMap<>(); diff --git a/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java b/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java index 6ee82f9e..46a8385f 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerFeedbackChatInput.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.chat; import com.alpsbte.plotsystem.core.system.review.PlotReview; @@ -35,7 +11,7 @@ import java.util.UUID; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; public class PlayerFeedbackChatInput implements ChatInput { private final LocalDateTime dateTime; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerInviteeChatInput.java b/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerInviteeChatInput.java index 29183ca9..54de173d 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerInviteeChatInput.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/chat/PlayerInviteeChatInput.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.chat; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -35,7 +11,7 @@ import java.util.UUID; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; public class PlayerInviteeChatInput implements ChatInput { private final LocalDateTime dateTime; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/conversion/CoordinateConversion.java b/src/main/java/com/alpsbte/plotsystem/utils/conversion/CoordinateConversion.java index 374a737b..28d77c8d 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/conversion/CoordinateConversion.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/conversion/CoordinateConversion.java @@ -1,33 +1,9 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.conversion; import com.alpsbte.plotsystem.utils.conversion.projection.GeographicProjection; -import com.alpsbte.plotsystem.utils.conversion.projection.ScaleProjectionTransform; import com.alpsbte.plotsystem.utils.conversion.projection.OffsetProjectionTransform; import com.alpsbte.plotsystem.utils.conversion.projection.OutOfProjectionBoundsException; +import com.alpsbte.plotsystem.utils.conversion.projection.ScaleProjectionTransform; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java index 033a6bb8..bb3d9cf1 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.enums; public enum Category { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java index fc8ce00e..152f62eb 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Continent.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2023, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.enums; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -39,7 +15,7 @@ import java.util.Arrays; import java.util.List; -import static net.kyori.adventure.text.Component.*; +import static net.kyori.adventure.text.Component.text; public enum Continent { EUROPE("EU", LangPaths.Continent.EUROPE), diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/PlotDifficulty.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/PlotDifficulty.java index e03b7fe1..1c8ef51f 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/PlotDifficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/PlotDifficulty.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.enums; public enum PlotDifficulty { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java index 5ba57dac..df651662 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Slot.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.enums; public enum Slot { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Status.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Status.java index 30badd9c..8d7ecf50 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Status.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/enums/Status.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.enums; public enum Status { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java index 8cf70901..0f263ca1 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigPaths.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.io; public abstract class ConfigPaths { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java index 69999648..bd606f35 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.io; import com.alpsbte.alpslib.io.config.ConfigNotImplementedException; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 86eb5a66..c4c165df 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.io; public abstract class LangPaths { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java index 749be872..a83f7f43 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangUtil.java @@ -1,34 +1,10 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.io; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.utils.Utils.ChatUtils; import li.cinnazeyy.langlibs.core.LangLibAPI; -import li.cinnazeyy.langlibs.core.language.Language; import li.cinnazeyy.langlibs.core.file.LanguageFile; +import li.cinnazeyy.langlibs.core.language.Language; import li.cinnazeyy.langlibs.core.language.LanguageUtil; import org.bukkit.Bukkit; import org.bukkit.entity.Player; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java index 3e5e7356..f021f9f8 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/TutorialPaths.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.io; public abstract class TutorialPaths { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index 10f9ace0..c72e523c 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.items; import com.alpsbte.plotsystem.utils.Utils; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java index 63deab45..f52b8ee4 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/MenuItems.java @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - package com.alpsbte.plotsystem.utils.items; import com.alpsbte.alpslib.utils.item.ItemBuilder; @@ -33,7 +9,10 @@ import org.bukkit.inventory.ItemStack; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.GOLD; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.RED; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class MenuItems { diff --git a/src/main/resources/DATABASE.sql b/src/main/resources/DATABASE.sql index 0509b942..c79c3fcf 100644 --- a/src/main/resources/DATABASE.sql +++ b/src/main/resources/DATABASE.sql @@ -1,27 +1,3 @@ -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the Software), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -- System Info CREATE TABLE IF NOT EXISTS system_info ( @@ -158,30 +134,6 @@ CREATE TABLE IF NOT EXISTS plot_review ON DELETE CASCADE ON UPDATE CASCADE ); -/* - * The MIT License (MIT) - * - * Copyright © 2021-2025, Alps BTE - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -- Toggle Criteria CREATE TABLE IF NOT EXISTS review_toggle_criteria ( From 0c3b19a8917c7b2f76cb61790451ebce7d2440d4 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Tue, 30 Sep 2025 11:21:06 +0200 Subject: [PATCH 142/175] style: remove copyright config files --- .idea/copyright/AlpsMIT.xml | 6 ------ .idea/copyright/profiles_settings.xml | 7 ------- .idea/scopes/Java.xml | 3 --- 3 files changed, 16 deletions(-) delete mode 100644 .idea/copyright/AlpsMIT.xml delete mode 100644 .idea/copyright/profiles_settings.xml delete mode 100644 .idea/scopes/Java.xml diff --git a/.idea/copyright/AlpsMIT.xml b/.idea/copyright/AlpsMIT.xml deleted file mode 100644 index 0ccafc12..00000000 --- a/.idea/copyright/AlpsMIT.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml deleted file mode 100644 index dbbfe86e..00000000 --- a/.idea/copyright/profiles_settings.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/.idea/scopes/Java.xml b/.idea/scopes/Java.xml deleted file mode 100644 index bc417ab6..00000000 --- a/.idea/scopes/Java.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file From 23b81d93a8ee374b5e99991b1f661107ab590997 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 20 Oct 2025 10:55:57 +0200 Subject: [PATCH 143/175] delete unused Category.java and reuse tryParse return value in CMD_Setup_BuildTeam.java --- .../admin/setup/CMD_Setup_BuildTeam.java | 53 +++++++++++++------ .../plotsystem/utils/enums/Category.java | 5 -- 2 files changed, 36 insertions(+), 22 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 0487399c..943fcd4f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -160,7 +160,10 @@ public CMD_Setup_BuildTeam_Remove(BaseCommand baseCommand, SubCommand subCommand @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 1) {sendInfo(sender); return;} + + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); @@ -173,7 +176,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = DataProvider.BUILD_TEAM.removeBuildTeam(buildTeam.get().getId()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -204,9 +207,12 @@ public CMD_Setup_BuildTeam_SetName(BaseCommand baseCommand, SubCommand subComman @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 2) {sendInfo(sender); return;} - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} + + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(input); // Check if build team exists if (buildTeam.isEmpty()) { @@ -253,13 +259,13 @@ public CMD_Setup_BuildTeam_AddReviewer(BaseCommand baseCommand, SubCommand subCo @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) { - sendInfo(sender); - return; - } + if (args.length <= 2) {sendInfo(sender); return;} + + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} // Check if build team exists - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(input); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; @@ -303,10 +309,13 @@ public CMD_Setup_BuildTeam_RemoveReviewer(BaseCommand baseCommand, SubCommand su @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 2) {sendInfo(sender); return;} + + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} // Check if build team exists - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(input); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); @@ -352,8 +361,12 @@ public CMD_Setup_BuildTeam_Criteria(BaseCommand baseCommand, SubCommand subComma @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 1 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} - List criteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(Integer.parseInt(args[1])); + if (args.length <= 1) {sendInfo(sender); return;} + + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} + + List criteria = DataProvider.REVIEW.getBuildTeamToggleCriteria(input); if (criteria.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently no toggle criteria assigned to the build team " + args[1] + " in the database!")); return; @@ -396,10 +409,13 @@ public CMD_Setup_BuildTeam_AssignCriteria(BaseCommand baseCommand, SubCommand su @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 2) {sendInfo(sender); return;} + + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} // Check if build team exists - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(input); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; @@ -445,10 +461,13 @@ public CMD_Setup_BuildTeam_RemoveCriteria(BaseCommand baseCommand, SubCommand su @Override public void onCommand(CommandSender sender, String[] args) { - if (args.length <= 2 || AlpsUtils.tryParseInt(args[1]) == null) {sendInfo(sender); return;} + if (args.length <= 2) {sendInfo(sender); return;} + + Integer input = AlpsUtils.tryParseInt(args[1]); + if (input == null) {sendInfo(sender); return;} // Check if build team exists - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(input); if (buildTeam.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Build team could not be found!")); return; diff --git a/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java b/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java deleted file mode 100644 index bb3d9cf1..00000000 --- a/src/main/java/com/alpsbte/plotsystem/utils/enums/Category.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.alpsbte.plotsystem.utils.enums; - -public enum Category { - ACCURACY, BLOCKPALETTE, DETAILING, TECHNIQUE, ALL -} From e7db515e17fe0ef76d13e4b488d0172cce0181c7 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Mon, 20 Oct 2025 11:06:00 +0200 Subject: [PATCH 144/175] reuse tryParse output --- .../plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 943fcd4f..c7163e22 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -165,7 +165,7 @@ public void onCommand(CommandSender sender, String[] args) { Integer input = AlpsUtils.tryParseInt(args[1]); if (input == null) {sendInfo(sender); return;} - Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(Integer.parseInt(args[1])); + Optional buildTeam = DataProvider.BUILD_TEAM.getBuildTeam(input); // Check if build team exists if (buildTeam.isEmpty()) { From a213019af6a00b737deb1e0e363f615590aa0525 Mon Sep 17 00:00:00 2001 From: cinnazeyy Date: Tue, 21 Oct 2025 21:11:37 +0200 Subject: [PATCH 145/175] update version in plugin.yml to 5.0.0 --- src/main/resources/plugin.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 6d5150ac..78aa2570 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,5 +1,5 @@ main: com.alpsbte.plotsystem.PlotSystem -version: 4.1.3 +version: 5.0.0 api-version: "1.21" name: Plot-System author: R3tuxn, Cinnazeyy & Zoriot From 33d0778e9c569c4a9019577add46969d46f9eea1 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 23 Oct 2025 17:15:36 +0200 Subject: [PATCH 146/175] refactor: use project properties for version and description in plugin.yml --- build.gradle.kts | 4 ++-- src/main/resources/plugin.yml | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 23250c3c..f7dd808c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -104,8 +104,8 @@ tasks.processResources { from("src/main/resources/plugin.yml") { expand( mapOf( - "version" to version, - "description" to description + "version" to project.version, + "description" to project.description ) ) } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 78aa2570..a9a177fd 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,7 +1,8 @@ main: com.alpsbte.plotsystem.PlotSystem -version: 5.0.0 +version: "${version}" api-version: "1.21" name: Plot-System +description: "${description}" author: R3tuxn, Cinnazeyy & Zoriot depend: [ LangLibs, FancyNpcs, VoidGen, FastAsyncWorldEdit, Multiverse-Core, DecentHolograms, WorldGuard, HeadDatabase ] From 994917ab4b59d2ec193bf7d1e5a7a45d3cd547b9 Mon Sep 17 00:00:00 2001 From: cinnazeyy Date: Fri, 24 Oct 2025 23:34:26 +0200 Subject: [PATCH 147/175] increase feedback text length to 512 for backwards compatibility since old db was 420 --- src/main/resources/DATABASE.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/DATABASE.sql b/src/main/resources/DATABASE.sql index c79c3fcf..2ab7ca16 100644 --- a/src/main/resources/DATABASE.sql +++ b/src/main/resources/DATABASE.sql @@ -126,7 +126,7 @@ CREATE TABLE IF NOT EXISTS plot_review plot_id INT NOT NULL, rating VARCHAR(7) NOT NULL, score INT NOT NULL DEFAULT 0, - feedback VARCHAR(256) NULL, + feedback VARCHAR(512) NULL, reviewed_by VARCHAR(36) NOT NULL, review_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (review_id), From b5daa43240ee36f17fc9b9fdcc6364907e3e12ae Mon Sep 17 00:00:00 2001 From: cinnazeyy Date: Sat, 1 Nov 2025 15:39:35 +0100 Subject: [PATCH 148/175] upgrade alpslib utils to 1.3.6 and use the getConfiguredItem method from there. --- gradle/libs.versions.toml | 2 +- pom.xml | 2 +- src/main/java/com/alpsbte/plotsystem/core/system/Country.java | 4 ++-- src/main/java/com/alpsbte/plotsystem/utils/Utils.java | 1 - .../java/com/alpsbte/plotsystem/utils/items/BaseItems.java | 4 ++-- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 88765ce6..0af5093b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,7 +4,7 @@ [versions] com-alpsbte-alpslib-alpslib-hologram = "1.1.1" com-alpsbte-alpslib-alpslib-io = "1.2.0" -com-alpsbte-alpslib-alpslib-utils = "1.3.5" +com-alpsbte-alpslib-alpslib-utils = "1.3.6" com-alpsbte-canvas = "1.3" com-arcaniax-headdatabase-api = "1.3.2" com-github-decentsoftware-eu-decentholograms = "2.9.2" diff --git a/pom.xml b/pom.xml index 579ed4fc..bbcc0a99 100644 --- a/pom.xml +++ b/pom.xml @@ -120,7 +120,7 @@ com.alpsbte.alpslib alpslib-utils - 1.3.5 + 1.3.6 compile diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java index 509c8ba0..ca771786 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Country.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Country.java @@ -1,7 +1,7 @@ package com.alpsbte.plotsystem.core.system; +import com.alpsbte.alpslib.utils.item.ItemUtils; import com.alpsbte.plotsystem.core.database.DataProvider; -import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Continent; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; @@ -49,6 +49,6 @@ public boolean setMaterialAndModelData(String material, @Nullable String customM } public ItemStack getCountryItem() { - return Utils.getConfiguredItem(material, customModelData); + return ItemUtils.getConfiguredItem(material, customModelData); } } \ No newline at end of file diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index da10f9aa..32bf9812 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -87,7 +87,6 @@ public static void updatePlayerInventorySlots(Player player) { }); } - // TODO: extract to alpsLibs? public static ItemStack getConfiguredItem(@NotNull String material, Object customModelData) { ItemStack base; if (material.startsWith("head(") && material.endsWith(")")) { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index c72e523c..717e98ee 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -1,6 +1,6 @@ package com.alpsbte.plotsystem.utils.items; -import com.alpsbte.plotsystem.utils.Utils; +import com.alpsbte.alpslib.utils.item.ItemUtils; import com.alpsbte.plotsystem.utils.io.ConfigUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemFlag; @@ -71,7 +71,7 @@ public enum BaseItems { String materialString = ConfigUtil.getInstance().configs[2].getString(configPath + ".material"); materialString = materialString == null ? Material.BARRIER.name() : materialString; Object customModelData = ConfigUtil.getInstance().configs[2].get(configPath + ".modelId"); - itemStack = Utils.getConfiguredItem(materialString, customModelData); + itemStack = ItemUtils.getConfiguredItem(materialString, customModelData); itemStack.getItemMeta().setAttributeModifiers(null); itemStack.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ADDITIONAL_TOOLTIP, ItemFlag.HIDE_ENCHANTS); From 89f8b168ab7c8e2b646776ea0c5154fe5be17720 Mon Sep 17 00:00:00 2001 From: cinnazeyy Date: Sat, 1 Nov 2025 15:40:24 +0100 Subject: [PATCH 149/175] use one separate line for each variable declaration --- .../plotsystem/core/system/tutorial/utils/TutorialUtils.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java index f8ebd445..3896e567 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialUtils.java @@ -16,7 +16,8 @@ import static net.kyori.adventure.text.format.NamedTextColor.GRAY; public class TutorialUtils { - public static final String TEXT_HIGHLIGHT_START = "", TEXT_HIGHLIGHT_END = ""; + public static final String TEXT_HIGHLIGHT_START = ""; + public static final String TEXT_HIGHLIGHT_END = ""; public static final String TEXT_CLICK_HIGHLIGHT = ""; public static final Component CHAT_PREFIX_COMPONENT = text("»", DARK_GRAY) From 3bda9ffac548d8ace866756b162bb417becc74e3 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sun, 2 Nov 2025 19:47:39 +0100 Subject: [PATCH 150/175] fix: fix relocation configuration in build.gradle.kts --- build.gradle.kts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index f7dd808c..75856788 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -85,8 +85,11 @@ tasks.shadowJar { exclude("org/slf4j/**") exclude("META-INF/**") archiveClassifier = "" - enableAutoRelocation = true - relocationPrefix = "alpsplotsystem.libs." + + val relocationPrefix = "alpsplotsystem.libs" + relocate("com.alpsbte.alpslib", "$relocationPrefix.com.alpsbte.alpslib") + relocate("org.mariadb.jdbc", "$relocationPrefix.org.mariadb.jdbc") + relocate("com.zaxxer.hikari", "$relocationPrefix.com.zaxxer.hikari") } tasks.assemble { From 6ca84fcdfa1e9190596b22b46a4fc7a938647c7f Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 6 Nov 2025 13:10:36 +0100 Subject: [PATCH 151/175] refactor: replace ItemBuilder instances with Utils.DEFAULT_ITEM for consistency and correctly use default item Before we sometimes set no item at all which is confusing. Signed-off-by: Zoriot --- .../core/menus/BuilderUtilitiesMenu.java | 2 +- .../plotsystem/core/menus/FeedbackMenu.java | 6 +- .../core/menus/PlayerPlotsMenu.java | 5 +- .../core/menus/PlotActionsMenu.java | 62 ++++++++++--------- .../plotsystem/core/menus/PlotMemberMenu.java | 2 +- .../plotsystem/core/menus/PlotTypeMenu.java | 10 ++- .../plotsystem/core/menus/ReviewPlotMenu.java | 0 .../plotsystem/core/menus/SettingsMenu.java | 4 +- .../core/menus/SpecialToolsMenu.java | 3 +- .../core/menus/companion/CityProjectMenu.java | 32 +++++----- .../core/menus/companion/ContinentMenu.java | 5 +- .../core/menus/companion/CountryMenu.java | 8 +-- .../core/menus/review/ReviewMenu.java | 15 +++-- .../core/menus/review/ReviewPlotMenu.java | 3 +- .../menus/review/ReviewPlotTogglesMenu.java | 9 ++- .../menus/tutorial/TutorialStagesMenu.java | 3 +- .../core/menus/tutorial/TutorialsMenu.java | 7 +-- .../com/alpsbte/plotsystem/utils/Utils.java | 1 + 18 files changed, 80 insertions(+), 97 deletions(-) delete mode 100644 src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java index 7a0b5fb9..1c3f26ac 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/BuilderUtilitiesMenu.java @@ -77,7 +77,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern("111101111") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index bc620ab7..504d37f4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -83,7 +83,7 @@ protected void setMenuItemsAsync() { getMenu().getSlot(14).setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA, BOLD)) .setLore(new LoreBuilder() - .addLine(feedbackText.replaceAll("//", " "), true) + .addLine(feedbackText.replace("//", " "), true) .build()) .build()); @@ -95,12 +95,12 @@ protected void setMenuItemsAsync() { } @Override - protected void setItemClickEventsAsync() {} + protected void setItemClickEventsAsync(/* Not needed */) {} @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern(Utils.FULL_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index 2a585e52..d5d1452e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Optional; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.AQUA; import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; @@ -109,7 +108,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("111101111") .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) @@ -167,7 +166,7 @@ protected Mask getMask() { loreBuilder.addLine(text(LangUtil.getInstance().get(p, LangPaths.Review.FEEDBACK) + ":", GRAY)); String feedback = review.get().getFeedback() == null ? LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.NO_FEEDBACK) - : review.get().getFeedback().replaceAll("//", " "); + : review.get().getFeedback().replace("//", " "); loreBuilder.addLine(text(feedback, WHITE), true); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index bc0ad058..5ea28fd0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -12,12 +12,11 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; -import net.kyori.adventure.text.Component; -import org.bukkit.Material; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; +import org.jetbrains.annotations.NotNull; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.AQUA; @@ -30,12 +29,14 @@ public class PlotActionsMenu extends AbstractMenu { private final Plot plot; private final boolean hasReview; + FileConfiguration config; - public PlotActionsMenu(Player menuPlayer, Plot plot) { + public PlotActionsMenu(Player menuPlayer, @NotNull Plot plot) { super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getID() + " | " + plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), menuPlayer); this.plot = plot; hasReview = plot.getLatestReview().isPresent(); + config = PlotSystem.getPlugin().getConfig(); } @Override @@ -79,18 +80,15 @@ protected void setMenuItemsAsync() { .build()); // Set plot feedback item - if (hasReview) { getMenu().getSlot(16) - .setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) + .setItem(hasReview ? new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder().addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.FEEDBACK), true).build()) - .build()); - } - + .build() : Utils.DEFAULT_ITEM); + // Set plot members item - if (!plot.isReviewed()) { - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + if (!plot.isReviewed() && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin"))) { getMenu().getSlot(22) .setItem(new ItemBuilder(BaseItems.MENU_ADD.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.MANAGE_MEMBERS), AQUA).decoration(BOLD, true)) @@ -111,6 +109,8 @@ protected void setMenuItemsAsync() { .build()) .build()); } + } else { + getMenu().getSlot(22).setItem(Utils.DEFAULT_ITEM); } } @@ -147,30 +147,32 @@ protected void setItemClickEventsAsync() { } // Set click event for plot members item - getMenu().getSlot(22).setClickHandler((clickPlayer, clickInformation) -> { - if (plot.isReviewed()) return; - if (plot.getStatus() != Status.unfinished) { - clickPlayer.closeInventory(); - clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.CAN_ONLY_MANAGE_MEMBERS_UNFINISHED))); - return; - } - - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { - new PlotMemberMenu(plot, clickPlayer); - } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { - // Leave Plot - clickPlayer.closeInventory(); - plot.removePlotMember(Builder.byUUID(clickPlayer.getUniqueId())); - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.LEFT_PLOT, Integer.toString(plot.getID())))); - } - }); + if (!plot.isReviewed() && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + getMenu().getSlot(22).setClickHandler((clickPlayer, clickInformation) -> { + if (plot.isReviewed()) return; + if (plot.getStatus() != Status.unfinished) { + clickPlayer.closeInventory(); + clickPlayer.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.CAN_ONLY_MANAGE_MEMBERS_UNFINISHED))); + return; + } + + FileConfiguration config = PlotSystem.getPlugin().getConfig(); + if ((getMenuPlayer() == plot.getPlotOwner().getPlayer() || getMenuPlayer().hasPermission("plotsystem.admin")) && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + new PlotMemberMenu(plot, clickPlayer); + } else if (plot.getPlotMembers().stream().anyMatch(m -> m.getUUID().equals(getMenuPlayer().getUniqueId()))) { + // Leave Plot + clickPlayer.closeInventory(); + plot.removePlotMember(Builder.byUUID(clickPlayer.getUniqueId())); + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.LEFT_PLOT, Integer.toString(plot.getID())))); + } + }); + } } @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern(Utils.FULL_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index d272c4b8..3a1c2966 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -142,7 +142,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern("111101111") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java index a28aa952..a44216cf 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotTypeMenu.java @@ -59,8 +59,7 @@ protected void setMenuItemsAsync() { .build()); boolean inspirationModeDisabled = PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DISABLE_CITY_INSPIRATION_MODE); // TODO remove or enhance as soon CIM is working again - if (!inspirationModeDisabled) { - getMenu().getSlot(15).setItem( + getMenu().getSlot(15).setItem(!inspirationModeDisabled ? new ItemBuilder(BaseItems.PLOT_CITY_INSPIRATION_MODE.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuTitle.SELECT_CITY_INSPIRATION_MODE), GOLD, BOLD) .append(text(" [", DARK_GRAY).append(text("BETA", RED).append(text("]", DARK_GRAY))))) // temporary BETA tag @@ -68,8 +67,8 @@ protected void setMenuItemsAsync() { .addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.SELECT_CITY_INSPIRATION_MODE), true) .build()) .setEnchanted(builder.getPlotType().getId() == PlotType.CITY_INSPIRATION_MODE.getId()) - .build()); - } + .build() : Utils.DEFAULT_ITEM); + // Set selected glass pane @@ -80,7 +79,6 @@ protected void setMenuItemsAsync() { selectedPlotTypeSlot = 15; getMenu().getSlot(selectedPlotTypeSlot - 9).setItem(new ItemBuilder(Material.LIME_STAINED_GLASS_PANE, 1).setName(empty()).build()); - // Set back item getMenu().getSlot(22).setItem(MenuItems.backMenuItem(getMenuPlayer())); } @@ -119,7 +117,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern("111101111") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/ReviewPlotMenu.java deleted file mode 100644 index e69de29b..00000000 diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java index 74dfc848..546d6128 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SettingsMenu.java @@ -7,14 +7,12 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; import java.util.function.Consumer; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.GOLD; import static net.kyori.adventure.text.format.TextDecoration.BOLD; @@ -70,7 +68,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern("111101111") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java index b41a26d1..0db6c788 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/SpecialToolsMenu.java @@ -6,7 +6,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; @@ -50,7 +49,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern("111101111") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index a705108a..ac37adca 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -1,6 +1,5 @@ package com.alpsbte.plotsystem.core.menus.companion; -import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractPaginatedMenu; @@ -17,8 +16,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; @@ -52,15 +49,13 @@ protected void setPreviewItems() { // Set tutorial item getMenu().getSlot(7).setItem(PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE) ? - TutorialsMenu.getTutorialItem(getMenuPlayer()) : new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()); + TutorialsMenu.getTutorialItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); // Set previous page item - if (hasPreviousPage()) - getMenu().getSlot(45).setItem(MenuItems.previousPageItem(getMenuPlayer())); + getMenu().getSlot(45).setItem(hasPreviousPage() ? MenuItems.previousPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); // Set next page item - if (hasNextPage()) - getMenu().getSlot(53).setItem(MenuItems.nextPageItem(getMenuPlayer())); + getMenu().getSlot(53).setItem(hasNextPage() ? MenuItems.nextPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); super.setPreviewItems(); } @@ -76,19 +71,20 @@ protected void setItemClickEventsAsync() { getMenu().getSlot(1).setClickHandler((clickPlayer, clickInformation) -> new CountryMenu(clickPlayer, country.getContinent(), selectedPlotDifficulty)); // Set click event for previous page item - getMenu().getSlot(45).setClickHandler((clickPlayer, clickInformation) -> { - if (hasPreviousPage()) { + if (hasPreviousPage()) { + getMenu().getSlot(45).setClickHandler((clickPlayer, clickInformation) -> { previousPage(); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - } - }); + }); + } // Set click event for next page item - getMenu().getSlot(53).setClickHandler((clickPlayer, clickInformation) -> { - if (!hasNextPage()) return; - nextPage(); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - }); + if (hasNextPage()) { + getMenu().getSlot(53).setClickHandler((clickPlayer, clickInformation) -> { + nextPage(); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); + }); + } Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())); footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); @@ -144,7 +140,7 @@ public static List getValidCityProjects(PlotDifficulty selectedPlot @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("001111001") .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java index 893afd20..e125c827 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java @@ -1,6 +1,5 @@ package com.alpsbte.plotsystem.core.menus.companion; -import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractMenu; import com.alpsbte.plotsystem.utils.Utils; @@ -8,8 +7,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; @@ -74,7 +71,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("011111111") .pattern("010101010") .pattern("111101111") diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index 80191bf7..df16a9a1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -16,7 +16,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; @@ -27,7 +26,6 @@ import java.util.List; import java.util.Map; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.AQUA; import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; @@ -61,7 +59,7 @@ protected void setPreviewItems() { // Set tutorial item getMenu().getSlot(7).setItem(PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE) ? - TutorialsMenu.getTutorialItem(getMenuPlayer()) : new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()); + TutorialsMenu.getTutorialItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)); footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); @@ -121,7 +119,7 @@ public static boolean generateRandomPlot(Player clickPlayer, @NotNull List source) { @Override protected void setMenuItemsAsync() { // Set previous page item - if (hasPreviousPage()) getMenu().getSlot(46).setItem(MenuItems.previousPageItem(getMenuPlayer())); + getMenu().getSlot(46).setItem(hasPreviousPage() ? MenuItems.previousPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); // Set next page item - if (hasNextPage()) getMenu().getSlot(52).setItem(MenuItems.nextPageItem(getMenuPlayer())); + getMenu().getSlot(52).setItem(hasNextPage() ? MenuItems.nextPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); } @Override @@ -122,29 +121,29 @@ protected void setItemClickEventsAsync() { }); // Set click event for previous page item + if (hasPreviousPage()) { getMenu().getSlot(46).setClickHandler((clickPlayer, clickInformation) -> { - if (hasPreviousPage()) { previousPage(); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - } }); + } // Set click event for close item getMenu().getSlot(49).setClickHandler((clickPlayer, clickInformation) -> clickPlayer.closeInventory()); // Set click event for next page item + if (hasNextPage()) { getMenu().getSlot(52).setClickHandler((clickPlayer, clickInformation) -> { - if (hasNextPage()) { nextPage(); clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - } }); + } } @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern(Utils.FULL_MASK) .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index 29c80eab..a2da0d05 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -27,7 +27,6 @@ import java.util.List; import java.util.Objects; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.DARK_GREEN; import static net.kyori.adventure.text.format.NamedTextColor.GOLD; @@ -182,7 +181,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("111101111") .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 68e96739..8ba4cdab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -25,17 +25,16 @@ import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextDecoration; import org.bukkit.Bukkit; -import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; +import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import static net.kyori.adventure.text.Component.empty; import static net.kyori.adventure.text.Component.text; public class ReviewPlotTogglesMenu extends AbstractMenu { @@ -43,7 +42,7 @@ public class ReviewPlotTogglesMenu extends AbstractMenu { private final ReviewRating rating; private List buildTeamCriteria = new ArrayList<>(); - public ReviewPlotTogglesMenu(Player player, Plot plot, ReviewRating rating) { + public ReviewPlotTogglesMenu(Player player, @NotNull Plot plot, ReviewRating rating) { super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); this.plot = plot; this.rating = rating; @@ -103,7 +102,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("111101111") .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) @@ -207,7 +206,7 @@ private boolean acceptPlot(int score, int splitScore) { return true; } - private ItemStack getToggleItem(ToggleCriteria criteria, boolean checked) { + private ItemStack getToggleItem(@NotNull ToggleCriteria criteria, boolean checked) { Player p = getMenuPlayer(); ItemStack baseItem = checked ? BaseItems.REVIEW_TOGGLE_CHECKED.getItem() diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java index eb964d53..e7aaf745 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialStagesMenu.java @@ -14,7 +14,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; import net.md_5.bungee.api.ChatColor; import org.bukkit.Material; import org.bukkit.Sound; @@ -158,7 +157,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("111101111") .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java index 630a9723..04e27069 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/tutorial/TutorialsMenu.java @@ -17,7 +17,6 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; -import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; @@ -82,8 +81,8 @@ protected void setMenuItemsAsync() { ); // Set back item - if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) || isBeginnerTutorialCompleted) - getMenu().getSlot(49).setItem(MenuItems.backMenuItem(getMenuPlayer())); + getMenu().getSlot(49).setItem(!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_REQUIRE_BEGINNER_TUTORIAL) + || isBeginnerTutorialCompleted ? MenuItems.backMenuItem( getMenuPlayer()) : Utils.DEFAULT_ITEM); } @Override @@ -106,7 +105,7 @@ protected void setItemClickEventsAsync() { @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) - .item(new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE).setName(Component.empty()).build()) + .item(Utils.DEFAULT_ITEM) .pattern("111101111") .pattern(Utils.EMPTY_MASK) .pattern(Utils.EMPTY_MASK) diff --git a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java index 32bf9812..d2f9dbaf 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/Utils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/Utils.java @@ -60,6 +60,7 @@ private Utils() {} private static Random random; public static final String EMPTY_MASK = "000000000"; public static final String FULL_MASK = "111111111"; + public static final ItemStack DEFAULT_ITEM = new ItemBuilder(Material.GRAY_STAINED_GLASS_PANE, 1).setName(Component.empty()).build(); // Spawn Location public static Location getSpawnLocation() { From 4ca4a671dcf353198bdd949412df9b2c1019d695 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 6 Nov 2025 13:11:24 +0100 Subject: [PATCH 152/175] fix: conditionally register CMD_Plot_Invite based on group support configuration Signed-off-by: Zoriot --- .../com/alpsbte/plotsystem/commands/plot/CMD_Plot.java | 4 +++- .../plotsystem/commands/plot/CMD_Plot_Invite.java | 9 --------- 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java index 765c61cf..35e22b73 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java @@ -1,6 +1,8 @@ package com.alpsbte.plotsystem.commands.plot; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; @@ -13,7 +15,7 @@ public CMD_Plot() { registerSubCommand(new CMD_Plot_Links(this)); registerSubCommand(new CMD_Plot_Submit(this)); registerSubCommand(new CMD_Plot_Abandon(this)); - registerSubCommand(new CMD_Plot_Invite(this)); + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) registerSubCommand(new CMD_Plot_Invite(this)); registerSubCommand(new CMD_Plot_Feedback(this)); registerSubCommand(new CMD_Plot_UndoSubmit(this)); registerSubCommand(new CMD_Plot_Members(this)); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java index 67450e91..402b0578 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Invite.java @@ -1,16 +1,13 @@ package com.alpsbte.plotsystem.commands.plot; -import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.utils.PlotMemberInvitation; import com.alpsbte.plotsystem.utils.Utils; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import static net.kyori.adventure.text.Component.text; @@ -34,12 +31,6 @@ public void onCommand(CommandSender sender, String[] args) { return; } - // TODO: don't register command if this config value is false - FileConfiguration config = PlotSystem.getPlugin().getConfig(); - if (!config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { - return; - } - PlotMemberInvitation invite = null; for (PlotMemberInvitation item : PlotMemberInvitation.invitationsList) { if (!item.invitee.getUniqueId().toString().equals(player.getUniqueId().toString())) { From ea608d17c5f303bc021d03766b214ebb360ad745 Mon Sep 17 00:00:00 2001 From: Cinnazeyy Date: Thu, 6 Nov 2025 14:16:24 +0100 Subject: [PATCH 153/175] restructure CMD_Review.java to open the reviewplot menu directly when already on a plot and not specifying an id --- .../commands/review/CMD_Review.java | 45 ++++++++++--------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 4330d5d0..039f6114 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -41,54 +41,59 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - if (args.length == 0) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); - return; - } + Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); + AbstractPlot currentPlot = PlotUtils.getCurrentPlot(builder); - if (AlpsUtils.tryParseInt(args[0]) == null) { - sendInfo(sender); + if (args.length == 0 && !(currentPlot instanceof Plot)) { + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewMenu(player)); return; } - Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - if (plot == null || plot.getStatus() != Status.unreviewed) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, - LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); - return; + Plot plotToReview; + if (args.length == 0) plotToReview = (Plot) currentPlot; + else { + Integer id = AlpsUtils.tryParseInt(args[0]); + if (id == null) { + sendInfo(sender); + return; + } + + plotToReview = DataProvider.PLOT.getPlotById(id); + if (plotToReview == null || plotToReview.getStatus() != Status.unreviewed) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.PLOT_DOES_NOT_EXIST))); + return; + } } - if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_LOAD_LEGACY_PLOT))); + if (plotToReview.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_LOAD_LEGACY_PLOT))); return; } - Builder builder = DataProvider.BUILDER.getBuilderByUUID(player.getUniqueId()); - if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plot) && !sender.hasPermission("plotsystem.admin")) { + if (DataProvider.BUILDER.canNotReviewPlot(builder.getUUID(), plotToReview) && !sender.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_HAS_NO_PERMISSIONS))); return; } // Players cannot review their own plots - boolean isParticipant = plot.getPlotOwner().getUUID() == player.getUniqueId() || plot.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId()); + boolean isParticipant = plotToReview.getPlotOwner().getUUID() == player.getUniqueId() || plotToReview.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId()); if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) && isParticipant) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); } // Check if the reviewer is on the plot - AbstractPlot currentPlot = PlotUtils.getCurrentPlot(builder, Status.unreviewed); boolean teleportPlayer = false; if (currentPlot instanceof Plot) { - if (plot.getID() != currentPlot.getID()) teleportPlayer = true; + if (plotToReview.getID() != currentPlot.getID()) teleportPlayer = true; } else teleportPlayer = true; // If the reviewer is not on the plot, teleport the player if (teleportPlayer) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> plot.getWorld().teleportPlayer(player)); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> plotToReview.getWorld().teleportPlayer(player)); return; } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewPlotMenu(player, plot)); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewPlotMenu(player, plotToReview)); }); return true; } From 90ce70a40c5580eceff30650fc00ff1b9f8e6ba4 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 6 Nov 2025 14:50:22 +0100 Subject: [PATCH 154/175] refactor: standardize plot ID accessors and improve code consistency Signed-off-by: Zoriot --- .../plotsystem/commands/BaseCommand.java | 2 +- .../alpsbte/plotsystem/commands/CMD_Tpll.java | 5 ++- .../plotsystem/commands/CommandManager.java | 39 +++++++++---------- .../admin/setup/CMD_Setup_BuildTeam.java | 2 +- .../commands/admin/setup/CMD_Setup_City.java | 2 +- .../commands/plot/CMD_Plot_Abandon.java | 2 +- .../commands/plot/CMD_Plot_Feedback.java | 2 +- .../commands/plot/CMD_Plot_Members.java | 4 +- .../commands/plot/CMD_Plot_Submit.java | 4 +- .../commands/plot/CMD_Plot_UndoSubmit.java | 2 +- .../commands/review/CMD_EditFeedback.java | 2 +- .../commands/review/CMD_EditPlot.java | 4 +- .../commands/review/CMD_Review.java | 2 +- .../commands/review/CMD_UndoReview.java | 2 +- .../plotsystem/core/EventListener.java | 2 +- .../database/providers/BuilderProvider.java | 2 +- .../providers/CityProjectProvider.java | 2 +- .../core/database/providers/PlotProvider.java | 6 +-- .../database/providers/ReviewProvider.java | 4 +- .../plotsystem/core/menus/AbstractMenu.java | 12 ++++-- .../core/menus/AbstractPaginatedMenu.java | 2 +- .../plotsystem/core/menus/FeedbackMenu.java | 3 -- .../core/menus/PlayerPlotsMenu.java | 2 +- .../core/menus/PlotActionsMenu.java | 12 +++--- .../plotsystem/core/menus/PlotMemberMenu.java | 4 +- .../core/menus/companion/CityProjectMenu.java | 16 ++++---- .../core/menus/companion/CompanionMenu.java | 2 +- .../core/menus/companion/ContinentMenu.java | 4 +- .../core/menus/companion/CountryMenu.java | 4 +- .../core/menus/companion/FooterItem.java | 13 ++----- .../core/menus/review/ReviewItems.java | 9 ++++- .../core/menus/review/ReviewMenu.java | 8 ++-- .../core/menus/review/ReviewPlotMenu.java | 4 +- .../menus/review/ReviewPlotTogglesMenu.java | 14 +++---- .../plotsystem/core/system/Builder.java | 6 +-- .../plotsystem/core/system/CityProject.java | 18 ++++----- .../core/system/plot/AbstractPlot.java | 22 +++++------ .../plotsystem/core/system/plot/Plot.java | 26 ++++++------- .../plot/generator/DefaultPlotGenerator.java | 2 +- .../core/system/plot/utils/PlotUtils.java | 26 ++++++------- .../core/system/plot/world/CityPlotWorld.java | 16 ++++---- .../core/system/plot/world/OnePlotWorld.java | 6 +-- .../core/system/review/PlotReview.java | 28 +++++++++---- .../system/tutorial/AbstractPlotTutorial.java | 8 +++- .../system/tutorial/AbstractTutorial.java | 24 +++--------- .../tutorial/AbstractTutorialHologram.java | 12 +++--- .../system/tutorial/BeginnerTutorial.java | 24 ++++++++---- .../tutorial/stage/AbstractPlotStage.java | 2 +- .../system/tutorial/stage/StageTimeline.java | 13 ------- .../tutorial/stage/tasks/AbstractTask.java | 9 +---- .../stage/tasks/events/BuildEventTask.java | 8 ++-- .../events/commands/AbstractCmdEventTask.java | 16 ++++---- .../stage/tasks/message/ChatMessageTask.java | 23 +++++------ .../system/tutorial/utils/TutorialNPC.java | 8 ---- .../utils/PlotMemberInvitation.java | 4 +- .../utils/conversion/MathUtils.java | 38 +++++++++--------- .../plotsystem/utils/io/LangPaths.java | 4 -- .../plotsystem/utils/items/BaseItems.java | 7 ++-- 58 files changed, 264 insertions(+), 285 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java b/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java index 37098a61..9f696a6d 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/BaseCommand.java @@ -75,7 +75,7 @@ public List getSubCommands() { * @return null if sender is not a player */ protected Player getPlayer(CommandSender sender) { - return sender instanceof Player ? (Player) sender : null; + return sender instanceof Player p ? p : null; } /** diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index de3fa0a5..de91f1e7 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -107,7 +107,10 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } catch (IOException | OutOfProjectionBoundsException ex) { PlotSystem.getPlugin().getComponentLogger().error(text("A coordinate conversion error occurred!"), ex); player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); - } catch (InterruptedException | ExecutionException ex) { + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + sendInfo(sender); + } catch (ExecutionException ex) { sendInfo(sender); } }); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java index 4eef4a05..95b4634f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java @@ -16,32 +16,33 @@ import java.util.Objects; public class CommandManager { - - public final List baseCommands = new ArrayList<>() {{ + public final List baseCommands = new ArrayList<>(); + + public CommandManager() { // Default Commands - add(new CMD_CancelChat()); - add(new CMD_Companion()); - add(new CMD_Plots()); - add(new CMD_Tpll()); + baseCommands.add(new CMD_CancelChat()); + baseCommands.add(new CMD_Companion()); + baseCommands.add(new CMD_Plots()); + baseCommands.add(new CMD_Tpll()); // Plot Commands - add(new CMD_Plot()); + baseCommands.add(new CMD_Plot()); // Review Commands - add(new CMD_Review()); - add(new CMD_UndoReview()); - add(new CMD_EditFeedback()); - add(new CMD_EditPlot()); + baseCommands.add(new CMD_Review()); + baseCommands.add(new CMD_UndoReview()); + baseCommands.add(new CMD_EditFeedback()); + baseCommands.add(new CMD_EditPlot()); // Admin Commands - add(new CMD_DeletePlot()); - add(new CMD_SetLeaderboard()); - add(new CMD_PReload()); + baseCommands.add(new CMD_DeletePlot()); + baseCommands.add(new CMD_SetLeaderboard()); + baseCommands.add(new CMD_PReload()); // Admin Setup Commands - add(new CMD_Setup()); - add(new CMD_Tutorial()); - }}; + baseCommands.add(new CMD_Setup()); + baseCommands.add(new CMD_Tutorial()); + } public void init() { for (BaseCommand baseCmd : baseCommands) { @@ -50,8 +51,4 @@ public void init() { } } } - - public List getBaseCommands() { - return baseCommands; - } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index c7163e22..751ea02f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -81,7 +81,7 @@ public void onCommand(CommandSender sender, String[] args) { for (BuildTeam b : buildTeams) { StringJoiner citiesAsString = new StringJoiner(", "); StringJoiner reviewersAsString = new StringJoiner(", "); - b.getCityProjects().forEach(c -> citiesAsString.add(c.getID())); + b.getCityProjects().forEach(c -> citiesAsString.add(c.getId())); b.getReviewers().forEach(r -> reviewersAsString.add(r.getName())); sender.sendMessage(text(" » ", DARK_GRAY) .append(text(b.getId() + " (" + b.getName() + ") ", AQUA)) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index ef647437..f6893ff9 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -77,7 +77,7 @@ public void onCommand(CommandSender sender, String[] args) { sender.sendMessage(text("--------------------------", DARK_GRAY)); for (CityProject c : cities) { sender.sendMessage(text(" » ", DARK_GRAY) - .append(text(c.getID(), AQUA)) + .append(text(c.getId(), AQUA)) .append(text(" - Country: " + c.getCountry().getCode() + " - Server: " + c.getServerName() + " - Build Team: " + c.getBuildTeam().getName() diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java index 0a9f0fbb..7dd10f9a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Abandon.java @@ -68,7 +68,7 @@ public void onCommand(CommandSender sender, String[] args) { Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (PlotUtils.Actions.abandonPlot(plot)) { - sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.ABANDONED_PLOT, plot.getID() + ""))); + sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.ABANDONED_PLOT, plot.getId() + ""))); player.playSound(player.getLocation(), Utils.SoundUtils.ABANDON_PLOT_SOUND, 1, 1); } }); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java index 23f77fe4..1c298ed3 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Feedback.java @@ -66,7 +66,7 @@ public void onCommand(CommandSender sender, String[] args) { return; } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new FeedbackMenu(player, plot.getID())); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new FeedbackMenu(player, plot.getId())); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java index 6d013f95..a1831290 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java @@ -46,8 +46,8 @@ public void onCommand(CommandSender sender, String[] args) { } } else if (PlotUtils.isPlotWorld(player.getWorld())) { AbstractPlot p = PlotUtils.getCurrentPlot(Builder.byUUID(player.getUniqueId()), Status.unfinished, Status.unreviewed); - if (p instanceof Plot) { - plot = (Plot) p; + if (p instanceof Plot pl) { + plot = pl; } else { sendInfo(sender); return; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java index 0dfc8834..dd24a910 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Submit.java @@ -78,7 +78,7 @@ public void onCommand(CommandSender sender, String[] args) { PlotUtils.Actions.submitPlot(plot); if (plotMembers.isEmpty()) { // Plot was made alone - langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), plot.getPlotOwner().getName()); + langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getId()), plot.getPlotOwner().getName()); } else { // Plot was made in a group StringBuilder sb = new StringBuilder(plot.getPlotOwner().getName() + ", "); @@ -88,7 +88,7 @@ public void onCommand(CommandSender sender, String[] args) { plotMembers.get(i).getName() : plotMembers.get(i).getName() + ", "); } - langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getID()), sb.toString()); + langUtil.broadcast(LangPaths.Message.Info.FINISHED_PLOT, String.valueOf(plot.getId()), sb.toString()); } Objects.requireNonNull(player).playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java index d73e2006..a9b89bb9 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_UndoSubmit.java @@ -71,7 +71,7 @@ public void onCommand(CommandSender sender, String[] args) { Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { PlotUtils.Actions.undoSubmit(plot); - sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.UNDID_SUBMISSION, plot.getID() + ""))); + sender.sendMessage(Utils.ChatUtils.getInfoFormat(langUtil.get(sender, LangPaths.Message.Info.UNDID_SUBMISSION, plot.getId() + ""))); player.playSound(player.getLocation(), Utils.SoundUtils.FINISH_PLOT_SOUND, 1, 1); }); }); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index dbce4751..de7cca6b 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -68,7 +68,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } boolean successful = review.get().updateFeedback(feedback.toString()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, plot.getID() + ""))); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, plot.getId() + ""))); else sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.ERROR_OCCURRED))); }); return true; diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 26423934..595904d1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -82,12 +82,12 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N if (!plot.getPermissions().hasBuildingPerms(builder.getUUID())) { plot.getPermissions().addBuilderPerms(builder.getUUID()).save(); - sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.ENABLED_PLOT_PERMISSIONS, plot.getID() + ""))); + sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.ENABLED_PLOT_PERMISSIONS, plot.getId() + ""))); return; } plot.getPermissions().removeBuilderPerms(builder.getUUID()).save(); - sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.DISABLED_PLOT_PERMISSIONS, plot.getID() + ""))); + sender.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Info.DISABLED_PLOT_PERMISSIONS, plot.getId() + ""))); }); }); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 039f6114..8a130d46 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -84,7 +84,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N // Check if the reviewer is on the plot boolean teleportPlayer = false; if (currentPlot instanceof Plot) { - if (plotToReview.getID() != currentPlot.getID()) teleportPlayer = true; + if (plotToReview.getId() != currentPlot.getId()) teleportPlayer = true; } else teleportPlayer = true; // If the reviewer is not on the plot, teleport the player diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index c1c76cf9..f0c47b01 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -77,7 +77,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } boolean successful = review.get().undoReview(); - if (successful) player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.UNDID_REVIEW, plot.getID() + "", plot.getPlotOwner().getName()))); + if (successful) player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.UNDID_REVIEW, plot.getId() + "", plot.getPlotOwner().getName()))); else player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.ERROR_OCCURRED))); }); return true; diff --git a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java index c117c199..0d38d00c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/EventListener.java +++ b/src/main/java/com/alpsbte/plotsystem/core/EventListener.java @@ -197,7 +197,7 @@ public void onPlayerChatEvent(@NotNull AsyncChatEvent event) { feedbackInput.getReview().updateFeedback(messageComp.content()); ChatInput.awaitChatInput.remove(playerUUID); event.getPlayer().sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(event.getPlayer(), - LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, String.valueOf(feedbackInput.getReview().getPlot().getID())))); + LangPaths.Message.Info.UPDATED_PLOT_FEEDBACK, String.valueOf(feedbackInput.getReview().getPlot().getId())))); } else if (input instanceof PlayerInviteeChatInput inviteeInput) { Player player = Bukkit.getPlayer(messageComp.content()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java index c8070258..ad2d6578 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/BuilderProvider.java @@ -156,7 +156,7 @@ public Slot getSlot(@NotNull UUID uuid, int plotId) { } public boolean canNotReviewPlot(@NotNull UUID uuid, Plot plot) { - return DataProvider.BUILD_TEAM.getReviewerCities(uuid).stream().noneMatch(c -> c.getID().equals(plot.getCityProject().getID())); + return DataProvider.BUILD_TEAM.getReviewerCities(uuid).stream().noneMatch(c -> c.getId().equals(plot.getCityProject().getId())); } public List getReviewersByBuildTeam(int buildTeamId) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java index 10e87570..2030e3de 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/CityProjectProvider.java @@ -24,7 +24,7 @@ public CityProjectProvider() { } public Optional getById(String id) { - return CITY_PROJECTS.stream().filter(c -> c.getID().equals(id)).findFirst(); + return CITY_PROJECTS.stream().filter(c -> c.getId().equals(id)).findFirst(); } public List getByCountryCode(String countryCode, boolean onlyVisible) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 00384c0c..140b7b5e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -54,7 +54,7 @@ public List getPlots(@NotNull CityProject city, Status @NotNull ... status query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; String qPlotsWithCityAndStatuses = query; return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qPlotsWithCityAndStatuses, ps -> { - ps.setString(1, city.getID()); + ps.setString(1, city.getId()); for (int i = 0; i < statuses.length; i++) ps.setString(i + 2, statuses[i].name()); ResultSet rs = ps.executeQuery(); List plots = new ArrayList<>(); @@ -66,7 +66,7 @@ public List getPlots(@NotNull CityProject city, Status @NotNull ... status public List getPlots(@NotNull CityProject city, @NotNull PlotDifficulty plotDifficulty, @NotNull Status status) { String qAllByCityDifficultyStatus = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id = ? AND difficulty_id = ? AND status = ?;"; return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qAllByCityDifficultyStatus, ps -> { - ps.setString(1, city.getID()); + ps.setString(1, city.getId()); ps.setString(2, plotDifficulty.name()); ps.setString(3, status.name()); ResultSet rs = ps.executeQuery(); @@ -86,7 +86,7 @@ public List getPlots(@NotNull List cities, Status... statuses return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qPlotsWithCitiesAndStatuses, ps -> { int index = 1; - for (CityProject city : cities) ps.setString(index++, city.getID()); + for (CityProject city : cities) ps.setString(index++, city.getId()); for (Status status : statuses) ps.setString(index++, status.name()); ResultSet rs = ps.executeQuery(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java index f2d5aaac..f5656fff 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/ReviewProvider.java @@ -129,13 +129,13 @@ public boolean updateFeedback(int reviewId, String newFeedback) { } public PlotReview createReview(@NotNull Plot plot, ReviewRating rating, int score, UUID reviewerUUID) { - boolean result = DataProvider.PLOT.setMcVersion(plot.getID()); + boolean result = DataProvider.PLOT.setMcVersion(plot.getId()); if (!result) return null; // Create Review String qInsert = "INSERT INTO plot_review (plot_id, rating, score, reviewed_by) VALUES (?, ?, ?, ?);"; result = Boolean.TRUE.equals(Utils.handleSqlException(false, () -> SqlHelper.runQuery(qInsert, ps -> { - ps.setInt(1, plot.getID()); + ps.setInt(1, plot.getId()); ps.setString(2, rating.getRatingDatabaseString()); ps.setInt(3, score); ps.setString(4, reviewerUUID.toString()); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java index fd0df002..0b3c2f21 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractMenu.java @@ -14,11 +14,11 @@ public abstract class AbstractMenu { private final Player menuPlayer; private final String title; - public AbstractMenu(int rows, String title, Player menuPlayer) { + protected AbstractMenu(int rows, String title, Player menuPlayer) { this(rows, title, menuPlayer, true); } - public AbstractMenu(int rows, String title, Player menuPlayer, boolean reload) { + protected AbstractMenu(int rows, String title, Player menuPlayer, boolean reload) { this.title = title; this.menuPlayer = menuPlayer; this.menu = ChestMenu.builder(rows).title(text(title)).redraw(true).build(); @@ -29,12 +29,16 @@ public AbstractMenu(int rows, String title, Player menuPlayer, boolean reload) { /** * Places items asynchronously in the menu after it is opened */ - protected abstract void setMenuItemsAsync(); + protected void setMenuItemsAsync() { + // Default just does nothing, for use-cases which doesn't need it. + } /** * Sets click events for the items placed in the menu async after it is opened */ - protected abstract void setItemClickEventsAsync(); + protected void setItemClickEventsAsync() { + // Default just does nothing, for use-cases which doesn't need it. + } /** * Places pre-defined items in the menu before it is opened diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java index 4fc32722..57231c60 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/AbstractPaginatedMenu.java @@ -12,7 +12,7 @@ public abstract class AbstractPaginatedMenu extends AbstractMenu { private int totalItemsAmount; private int currentPage = 0; - public AbstractPaginatedMenu(int rows, int pagedRows, String title, Player menuPlayer) { + protected AbstractPaginatedMenu(int rows, int pagedRows, String title, Player menuPlayer) { super(rows, title, menuPlayer, false); this.maxItemsPerPage = pagedRows * 9; reloadMenuAsync(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java index 504d37f4..88a162a6 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/FeedbackMenu.java @@ -94,9 +94,6 @@ protected void setMenuItemsAsync() { .build()); } - @Override - protected void setItemClickEventsAsync(/* Not needed */) {} - @Override protected Mask getMask() { return BinaryMask.builder(getMenu()) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java index d5d1452e..09b11c68 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlayerPlotsMenu.java @@ -84,7 +84,7 @@ protected void setMenuItemsAsync() { getMenu().getSlot(9 + i) .setItem(new ItemBuilder(item) - .setName(text(plot.getCityProject().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), AQUA).decoration(BOLD, true)) + .setName(text(plot.getCityProject().getName(getMenuPlayer()) + " | " + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.PLOT_NAME) + " #" + plot.getId(), AQUA).decoration(BOLD, true)) .setLore(getLore(plot, getMenuPlayer()).build()) .build()); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 5ea28fd0..0c5016ce 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -29,10 +29,10 @@ public class PlotActionsMenu extends AbstractMenu { private final Plot plot; private final boolean hasReview; - FileConfiguration config; + final FileConfiguration config; public PlotActionsMenu(Player menuPlayer, @NotNull Plot plot) { - super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getID() + " | " + plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), menuPlayer); + super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getId() + " | " + plot.getStatus().name().substring(0, 1).toUpperCase() + plot.getStatus().name().substring(1), menuPlayer); this.plot = plot; hasReview = plot.getLatestReview().isPresent(); @@ -119,7 +119,7 @@ protected void setItemClickEventsAsync() { // Set click event for submit or undo submit plot item getMenu().getSlot(10).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); - clickPlayer.performCommand("plot " + (plot.getStatus().equals(Status.unreviewed) ? "undosubmit " : "submit ") + plot.getID()); + clickPlayer.performCommand("plot " + (plot.getStatus().equals(Status.unreviewed) ? "undosubmit " : "submit ") + plot.getId()); }); // Set click event for teleport to plot item @@ -135,14 +135,14 @@ protected void setItemClickEventsAsync() { // Set click event for abandon plot item getMenu().getSlot(hasReview ? 14 : 16).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); - clickPlayer.performCommand("plot abandon " + plot.getID()); + clickPlayer.performCommand("plot abandon " + plot.getId()); }); // Set click event for feedback menu button if (hasReview) { getMenu().getSlot(16).setClickHandler((clickPlayer, clickInformation) -> { clickPlayer.closeInventory(); - clickPlayer.performCommand("plot feedback " + plot.getID()); + clickPlayer.performCommand("plot feedback " + plot.getId()); }); } @@ -163,7 +163,7 @@ protected void setItemClickEventsAsync() { // Leave Plot clickPlayer.closeInventory(); plot.removePlotMember(Builder.byUUID(clickPlayer.getUniqueId())); - clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.LEFT_PLOT, Integer.toString(plot.getID())))); + clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.LEFT_PLOT, Integer.toString(plot.getId())))); } }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index 3a1c2966..bdfd219a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -38,7 +38,7 @@ public class PlotMemberMenu extends AbstractMenu { private List builders; public PlotMemberMenu(@NotNull Plot plot, Player menuPlayer) { - super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.MenuTitle.MANAGE_MEMBERS) + " | " + LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getID(), menuPlayer); + super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.MenuTitle.MANAGE_MEMBERS) + " | " + LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getId(), menuPlayer); this.plot = plot; } @@ -122,7 +122,7 @@ protected void setItemClickEventsAsync() { Builder builder = builders.get(itemSlot - 12); plot.removePlotMember(builder); clickPlayer.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), - LangPaths.Message.Info.REMOVED_PLOT_MEMBER, builder.getName(), Integer.toString(plot.getID())))); + LangPaths.Message.Info.REMOVED_PLOT_MEMBER, builder.getName(), Integer.toString(plot.getId())))); reloadMenuAsync(); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java index ac37adca..e9ab62ab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CityProjectMenu.java @@ -20,6 +20,7 @@ import org.ipvp.canvas.mask.BinaryMask; import org.ipvp.canvas.mask.Mask; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; import java.util.List; import java.util.Map; @@ -30,7 +31,7 @@ public class CityProjectMenu extends AbstractPaginatedMenu { List projects; private PlotDifficulty selectedPlotDifficulty; - CityProjectMenu(Player player, Country country, PlotDifficulty selectedPlotDifficulty) { + CityProjectMenu(Player player, @NotNull Country country, PlotDifficulty selectedPlotDifficulty) { super(6, 4, country.getName(player) + " → " + LangUtil.getInstance().get(player, LangPaths.MenuTitle.COMPANION_SELECT_CITY), player); this.country = country; this.selectedPlotDifficulty = selectedPlotDifficulty; @@ -42,7 +43,7 @@ protected void setPreviewItems() { getMenu().getSlot(1).setItem(MenuItems.backMenuItem(getMenuPlayer())); Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())); - footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item())); // Set loading item for plots difficulty item getMenu().getSlot(6).setItem(CompanionMenu.getDifficultyItem(getMenuPlayer(), selectedPlotDifficulty)); @@ -60,9 +61,6 @@ protected void setPreviewItems() { super.setPreviewItems(); } - @Override - protected void setMenuItemsAsync() {} - @Override protected void setItemClickEventsAsync() { getMenu().getSlot(0).setClickHandler((clickPlayer, clickInformation) -> @@ -87,7 +85,7 @@ protected void setItemClickEventsAsync() { } Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, country.getContinent())); - footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler())); // Set click event for plots difficulty item getMenu().getSlot(6).setClickHandler(((clickPlayer, clickInformation) -> { @@ -121,7 +119,7 @@ public static boolean generateRandomPlot(Player player, @NotNull List getValidCityProjects(PlotDifficulty selectedPlotDifficulty, Player player, Country country) { + public static @NotNull @Unmodifiable List getValidCityProjects(PlotDifficulty selectedPlotDifficulty, Player player, @NotNull Country country) { return DataProvider.CITY_PROJECT.getByCountryCode(country.getCode(), true).stream().filter(test -> { if (!(test instanceof CityProject project)) return false; var pd = selectedPlotDifficulty; @@ -157,7 +155,7 @@ protected List getSource() { } @Override - protected void setPaginatedMenuItemsAsync(List source) { + protected void setPaginatedMenuItemsAsync(@NotNull List source) { List cities = source.stream().map(l -> (CityProject) l).toList(); int slot = 9; for (CityProject city : cities) { @@ -167,7 +165,7 @@ protected void setPaginatedMenuItemsAsync(List source) { } @Override - protected void setPaginatedItemClickEventsAsync(List source) { + protected void setPaginatedItemClickEventsAsync(@NotNull List source) { List cities = source.stream().map(l -> (CityProject) l).toList(); int slot = 9; for (CityProject city : cities) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index af88582e..72d40fa5 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -208,7 +208,7 @@ public static ItemStack getPlotMenuItem(Plot plot, int slotIndex, Player langPla .decoration(BOLD, true) .append(text(statusText, GRAY)); lore = new LoreBuilder() - .addLines(text(plotIdText + ": ", GRAY).append(text(plot.getID(), WHITE)), + .addLines(text(plotIdText + ": ", GRAY).append(text(plot.getId(), WHITE)), text(plotCityText + ": ", GRAY).append(text(plot.getCityProject().getName(langPlayer), WHITE)), text(plotDifficultyText + ": ", GRAY).append(text(plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase(), WHITE)), empty(), diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java index e125c827..381dbe73 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/ContinentMenu.java @@ -34,7 +34,7 @@ protected void setPreviewItems() { getMenu().getSlot(0).setItem(MenuItems.getRandomItem(getMenuPlayer())); // Set random selection item Map footerItems = CompanionMenu.getFooterItems(9 * 4, getMenuPlayer(), ContinentMenu::new); - footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item())); super.setPreviewItems(); } @@ -65,7 +65,7 @@ protected void setItemClickEventsAsync() { } Map footerItems = CompanionMenu.getFooterItems(9 * 4, getMenuPlayer(), ContinentMenu::new); - footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler())); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java index df16a9a1..91e500a7 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CountryMenu.java @@ -62,7 +62,7 @@ protected void setPreviewItems() { TutorialsMenu.getTutorialItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)); - footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setItem(footerItem.item())); super.setPreviewItems(); } @@ -104,7 +104,7 @@ protected void setItemClickEventsAsync() { } Map footerItems = CompanionMenu.getFooterItems(45, getMenuPlayer(), player -> new CountryMenu(player, selectedContinent)); - footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler)); + footerItems.forEach((index, footerItem) -> getMenu().getSlot(index).setClickHandler(footerItem.clickHandler())); } public static boolean generateRandomPlot(Player clickPlayer, @NotNull List countryProjects, PlotDifficulty selectedPlotDifficulty) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java index f1d93330..1ef6480c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/FooterItem.java @@ -1,18 +1,11 @@ package com.alpsbte.plotsystem.core.menus.companion; import org.bukkit.inventory.ItemStack; +import org.ipvp.canvas.slot.Slot; -public class FooterItem { - public final ItemStack item; - public final org.ipvp.canvas.slot.Slot.ClickHandler clickHandler; - - FooterItem(ItemStack item, org.ipvp.canvas.slot.Slot.ClickHandler clickHandler) { - this.item = item; - this.clickHandler = clickHandler; - } +public record FooterItem(ItemStack item, Slot.ClickHandler clickHandler) { FooterItem(ItemStack item) { - this.item = item; - this.clickHandler = null; + this(item, null); } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java index f2afdcb5..e4e5c5ca 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewItems.java @@ -10,7 +10,12 @@ import org.bukkit.inventory.ItemStack; import static net.kyori.adventure.text.Component.text; -import static net.kyori.adventure.text.format.NamedTextColor.*; +import static net.kyori.adventure.text.format.NamedTextColor.AQUA; +import static net.kyori.adventure.text.format.NamedTextColor.GRAY; +import static net.kyori.adventure.text.format.NamedTextColor.GREEN; +import static net.kyori.adventure.text.format.NamedTextColor.RED; +import static net.kyori.adventure.text.format.NamedTextColor.WHITE; +import static net.kyori.adventure.text.format.NamedTextColor.YELLOW; import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class ReviewItems { @@ -48,7 +53,7 @@ public static ItemStack getPlotInfoItem(Player player, Plot plot) { .color(AQUA) .decoration(BOLD, true)) .setLore(new LoreBuilder() - .addLine(text(LangUtil.getInstance().get(player, LangPaths.Plot.ID) + ": ", GRAY).append(text(plot.getID(), WHITE))) + .addLine(text(LangUtil.getInstance().get(player, LangPaths.Plot.ID) + ": ", GRAY).append(text(plot.getId(), WHITE))) .emptyLine() .addLines(text(LangUtil.getInstance().get(player, LangPaths.Plot.OWNER) + ": ", GRAY).append(text(plotOwner, WHITE)), text(LangUtil.getInstance().get(player, LangPaths.Plot.CITY) + ": ", GRAY).append(text(city, WHITE)), diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index f72ce089..7b618833 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -60,7 +60,7 @@ protected void setPaginatedMenuItemsAsync(List source) { for (int i = 0; i < plots.size(); i++) { Plot plot = plots.get(i); List lines = new ArrayList<>(); - lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.ID) + ": §f" + plot.getID()); + lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.ID) + ": §f" + plot.getId()); lines.add(""); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.OWNER) + ": §f" + plot.getPlotOwner().getName()); if (!plot.getPlotMembers().isEmpty()) { @@ -89,7 +89,7 @@ protected void setPaginatedItemClickEventsAsync(List source) { return; } - player.performCommand("review " + plot.getID()); + player.performCommand("review " + plot.getId()); }); } } @@ -156,7 +156,7 @@ protected Mask getMask() { private List getFilteredPlots(@NotNull List plots) { List filteredPlots = plots.stream().map(p -> (Plot) p).toList(); if (filteredCityProject != null) - filteredPlots = filteredPlots.stream().filter(p -> p.getCityProject().getID().equals(filteredCityProject.getID())).toList(); + filteredPlots = filteredPlots.stream().filter(p -> p.getCityProject().getId().equals(filteredCityProject.getId())).toList(); return filteredPlots; } @@ -166,7 +166,7 @@ private ItemStack getFilterItem(Player langPlayer) { LegacyLoreBuilder.emptyLine(); cityProjects.forEach(c -> { - if (filteredCityProject != null && filteredCityProject.getID().equals(c.getID())) { + if (filteredCityProject != null && filteredCityProject.getId().equals(c.getId())) { LegacyLoreBuilder.addLine("§b§l> §f§l" + filteredCityProject.getName(langPlayer)); } else LegacyLoreBuilder.addLine("§7" + c.getName(langPlayer)); }); diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java index a2da0d05..595bb507 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotMenu.java @@ -43,7 +43,7 @@ public class ReviewPlotMenu extends AbstractMenu { boolean sentWarning = false; public ReviewPlotMenu(Player player, Plot plot, ReviewRating rating) { - super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); + super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getId())), player); this.plot = plot; this.rating = rating; } @@ -132,7 +132,7 @@ protected void setItemClickEventsAsync() { plot.setStatus(Status.unfinished); Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { clickPlayer.closeInventory(); - clickPlayer.performCommand("plot abandon " + plot.getID()); + clickPlayer.performCommand("plot abandon " + plot.getId()); }); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java index 8ba4cdab..91e949de 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewPlotTogglesMenu.java @@ -43,7 +43,7 @@ public class ReviewPlotTogglesMenu extends AbstractMenu { private List buildTeamCriteria = new ArrayList<>(); public ReviewPlotTogglesMenu(Player player, @NotNull Plot plot, ReviewRating rating) { - super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getID())), player); + super(6, LangUtil.getInstance().get(player, LangPaths.MenuTitle.REVIEW_PLOT, Integer.toString(plot.getId())), player); this.plot = plot; this.rating = rating; } @@ -127,10 +127,10 @@ private void submitReview() { Component reviewerConfirmationMessage; if (!isRejected) { - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getID()), getParticipantsString())); + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_MARKED_REVIEWED, Integer.toString(plot.getId()), getParticipantsString())); if(!acceptPlot(review.getScore(), review.getSplitScore())) return; } else { - reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getID()), getParticipantsString())); + reviewerConfirmationMessage = Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Info.PLOT_REJECTED, Integer.toString(plot.getId()), getParticipantsString())); PlotUtils.Actions.undoSubmit(plot); } @@ -174,17 +174,17 @@ private boolean acceptPlot(int score, int splitScore) { try { if (!PlotUtils.savePlotAsSchematic(plot)) { getMenuPlayer().sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Message.Error.ERROR_OCCURRED))); - PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!")); + PlotSystem.getPlugin().getComponentLogger().warn(text("Could not save finished plot schematic (ID: " + plot.getId() + ")!")); } } catch (IOException | WorldEditException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getID() + ")!"), ex); + PlotSystem.getPlugin().getComponentLogger().error(text("Could not save finished plot schematic (ID: " + plot.getId() + ")!"), ex); } }); plot.setStatus(Status.completed); // Remove Plot from Owner - if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plot.getID()), -1)) return false; + if (!plot.getPlotOwner().setSlot(plot.getPlotOwner().getSlotByPlotId(plot.getId()), -1)) return false; if (plot.getPlotMembers().isEmpty()) { // Plot was made alone @@ -200,7 +200,7 @@ private boolean acceptPlot(int score, int splitScore) { if (!builder.addScore(splitScore)) return false; // Remove Slot from Member - if (!builder.setSlot(builder.getSlotByPlotId(plot.getID()), -1)) return false; + if (!builder.setSlot(builder.getSlotByPlotId(plot.getId()), -1)) return false; } } return true; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java index 9171c7f0..62c8809b 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/Builder.java @@ -20,8 +20,8 @@ public class Builder { private int thirdSlot; private int plotType; - public Builder(UUID UUID, String name, int score, int firstSlot, int secondSlot, int thirdSlot, int plotType) { - this.uuid = UUID; + public Builder(UUID uniqueId, String name, int score, int firstSlot, int secondSlot, int thirdSlot, int plotType) { + this.uuid = uniqueId; this.name = name; this.score = score; this.firstSlot = firstSlot; @@ -74,7 +74,7 @@ public Plot getSlot(Slot slot) { } public Slot getSlot(Plot plot) { - return DataProvider.BUILDER.getSlot(this.uuid, plot.getID()); + return DataProvider.BUILDER.getSlot(this.uuid, plot.getId()); } @SuppressWarnings("BooleanMethodIsAlwaysInverted") diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java index cd1adaf2..4bde770d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/CityProject.java @@ -29,22 +29,22 @@ import static net.kyori.adventure.text.format.TextDecoration.BOLD; public class CityProject { - private final String ID; + private final String id; private final String countryCode; private String serverName; private boolean isVisible; private int buildTeamId; public CityProject(String id, String countryCode, String serverName, boolean isVisible, int buildTeamId) { - this.ID = id; + this.id = id; this.countryCode = countryCode; this.serverName = serverName; this.isVisible = isVisible; this.buildTeamId = buildTeamId; } - public String getID() { - return ID; + public String getId() { + return id; } public Country getCountry() { @@ -57,7 +57,7 @@ public String getServerName() { } public boolean setServer(String serverName) { - if (DataProvider.CITY_PROJECT.setServer(ID, serverName)) { + if (DataProvider.CITY_PROJECT.setServer(id, serverName)) { this.serverName = serverName; return true; } @@ -69,7 +69,7 @@ public boolean isVisible() { } public boolean setVisible(boolean isVisible) { - if (DataProvider.CITY_PROJECT.setVisibility(ID, isVisible)) { + if (DataProvider.CITY_PROJECT.setVisibility(id, isVisible)) { this.isVisible = isVisible; return true; } @@ -77,11 +77,11 @@ public boolean setVisible(boolean isVisible) { } public String getName(Player player) { - return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + ID + ".name"); + return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + id + ".name"); } public String getDescription(Player player) { - return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + ID + ".description"); + return LangUtil.getInstance().get(player, LangPaths.Database.CITY_PROJECT + "." + id + ".description"); } public BuildTeam getBuildTeam() { @@ -89,7 +89,7 @@ public BuildTeam getBuildTeam() { } public boolean setBuildTeam(int buildTeamId) { - if (DataProvider.CITY_PROJECT.setBuildTeam(ID, buildTeamId)) { + if (DataProvider.CITY_PROJECT.setBuildTeam(id, buildTeamId)) { this.buildTeamId = buildTeamId; return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java index 6b652386..a88643c9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/AbstractPlot.java @@ -35,7 +35,7 @@ public abstract class AbstractPlot { public static final ClipboardFormat CLIPBOARD_FORMAT = BuiltInClipboardFormat.FAST_V2; public static final double LEGACY_VERSION_THRESHOLD = 3; - private final int ID; + private final int id; protected Builder plotOwner; protected OnePlotWorld onePlotWorld; @@ -46,16 +46,16 @@ public abstract class AbstractPlot { protected List outline; protected List blockOutline; - public AbstractPlot(int id, UUID plotOwnerUUID) { - this.ID = id; + protected AbstractPlot(int id, UUID plotOwnerUUID) { + this.id = id; this.plotOwner = plotOwnerUUID != null ? DataProvider.BUILDER.getBuilderByUUID(plotOwnerUUID) : null; } /** * @return plot id */ - public int getID() { - return ID; + public int getId() { + return id; } /** @@ -200,18 +200,18 @@ public final List getBlockOutline() { return this.blockOutline; List points = new ArrayList<>(); - List outline = getOutline(); + List correctOutline = getOutline(); - for (int i = 0; i < outline.size() - 1; i++) { - BlockVector2 b1 = outline.get(i); - BlockVector2 b2 = outline.get(i + 1); + for (int i = 0; i < correctOutline.size() - 1; i++) { + BlockVector2 b1 = correctOutline.get(i); + BlockVector2 b2 = correctOutline.get(i + 1); int distance = (int) b1.distance(b2); points.addAll(Utils.getLineBetweenPoints(b1, b2, distance)); } - BlockVector2 first = outline.getFirst(); - BlockVector2 last = outline.getLast(); + BlockVector2 first = correctOutline.getFirst(); + BlockVector2 last = correctOutline.getLast(); points.addAll(Utils.getLineBetweenPoints(last, first, (int) first.distance(last))); this.blockOutline = points; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java index cd5f2265..eaee4697 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/Plot.java @@ -54,7 +54,7 @@ public Status getStatus() { @Override public boolean setStatus(@NotNull Status status) { - if (DataProvider.PLOT.setStatus(getID(), status)) { + if (DataProvider.PLOT.setStatus(getId(), status)) { this.status = status; return true; } @@ -71,7 +71,7 @@ public PlotDifficulty getDifficulty() { @Override public boolean setPlotOwner(@Nullable Builder plotOwner) { - if (DataProvider.PLOT.setPlotOwner(getID(), plotOwner == null ? null : plotOwner.getUUID())) { + if (DataProvider.PLOT.setPlotOwner(getId(), plotOwner == null ? null : plotOwner.getUUID())) { this.plotOwner = plotOwner; return true; } @@ -101,7 +101,7 @@ public LocalDate getLastActivity() { @Override public boolean setLastActivity(boolean setNull) { LocalDate activityDate = setNull ? null : LocalDate.now(); - if (DataProvider.PLOT.setLastActivity(getID(), activityDate)) { + if (DataProvider.PLOT.setLastActivity(getId(), activityDate)) { this.lastActivity = activityDate; return true; } @@ -118,7 +118,7 @@ public PlotType getPlotType() { } public boolean setPlotType(PlotType type) { - if (DataProvider.PLOT.setPlotType(getID(), type)) { + if (DataProvider.PLOT.setPlotType(getId(), type)) { this.plotType = type; return true; } @@ -139,19 +139,19 @@ public T getWorld() { @Override public byte[] getInitialSchematicBytes() { - return DataProvider.PLOT.getInitialSchematic(getID()); + return DataProvider.PLOT.getInitialSchematic(getId()); } public byte[] getCompletedSchematic() { - return DataProvider.PLOT.getCompletedSchematic(getID()); + return DataProvider.PLOT.getCompletedSchematic(getId()); } public List getReviewHistory() { - return DataProvider.REVIEW.getPlotReviewHistory(getID()); + return DataProvider.REVIEW.getPlotReviewHistory(getId()); } public Optional getLatestReview() { - return DataProvider.REVIEW.getLatestReview(getID()); + return DataProvider.REVIEW.getLatestReview(getId()); } public boolean isReviewed() { @@ -163,7 +163,7 @@ public boolean isRejected() { } public boolean setPasted(boolean pasted) { - return DataProvider.PLOT.setPasted(getID(), pasted); + return DataProvider.PLOT.setPasted(getId(), pasted); } public boolean addPlotMember(Builder member) { @@ -172,8 +172,8 @@ public boolean addPlotMember(Builder member) { Slot slot = member.getFreeSlot(); if (slot != null) { plotMembers.add(member); - if (DataProvider.PLOT.addPlotMember(getID(), member)) { - if (!member.setSlot(slot, getID())) return false; + if (DataProvider.PLOT.addPlotMember(getId(), member)) { + if (!member.setSlot(slot, getId())) return false; getPermissions().addBuilderPerms(member.getUUID()); return true; } @@ -186,8 +186,8 @@ public boolean removePlotMember(Builder member) { List plotMembers = getPlotMembers(); if (!plotMembers.isEmpty() && plotMembers.contains(member)) { plotMembers.remove(member); - if (DataProvider.PLOT.removePlotMember(getID(), member)) { - Slot slot = member.getSlotByPlotId(getID()); + if (DataProvider.PLOT.removePlotMember(getId(), member)) { + Slot slot = member.getSlotByPlotId(getId()); if (slot != null && !member.setSlot(slot, -1)) return false; if (getWorld().isWorldGenerated()) getPermissions().removeBuilderPerms(member.getUUID()); return true; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 3071a704..0a0455e8 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -109,7 +109,7 @@ protected void onComplete(boolean failed, boolean unloadWorld) { super.onComplete(failed, false); if (failed) return; - if (!getBuilder().setSlot(getBuilder().getFreeSlot(), plot.getID())) return; + if (!getBuilder().setSlot(getBuilder().getFreeSlot(), plot.getId())) return; if (!plot.setStatus(Status.unfinished)) return; if (!((Plot) plot).setPlotType(plotType)) return; if (!plot.setPlotOwner(getBuilder())) return; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 45905dfa..7b9bb14e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -242,7 +242,7 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException } // Set Completed Schematic - boolean successful = DataProvider.PLOT.setCompletedSchematic(plot.getID(), outputStream.toByteArray()); + boolean successful = DataProvider.PLOT.setCompletedSchematic(plot.getId(), outputStream.toByteArray()); if (!successful) return false; // If plot was created in a void world, copy the result to the city world @@ -302,9 +302,9 @@ public static void checkPlotsForLastActivity() { Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (Actions.abandonPlot(plot)) { - PlotSystem.getPlugin().getComponentLogger().info(text("Abandoned plot #" + plot.getID() + " due to inactivity!")); + PlotSystem.getPlugin().getComponentLogger().info(text("Abandoned plot #" + plot.getId() + " due to inactivity!")); } else { - PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while abandoning plot #" + plot.getID() + " due to inactivity!")); + PlotSystem.getPlugin().getComponentLogger().warn(text("An error occurred while abandoning plot #" + plot.getId() + " due to inactivity!")); } }); } @@ -396,7 +396,7 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { } } } catch (IOException | WorldEditException ex) { - PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!"), ex); + PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getId() + "!"), ex); return false; } @@ -404,7 +404,7 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { if (plot.getPlotType() == PlotType.TUTORIAL) return; Plot dPlot = (Plot) plot; boolean successful; - successful = DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getID()); + successful = DataProvider.REVIEW.removeAllReviewsOfPlot(dPlot.getId()); for (Builder builder : dPlot.getPlotMembers()) { if (!successful) break; @@ -423,9 +423,9 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { && dPlot.setPlotType(PlotType.LOCAL_INSPIRATION_MODE); } - successful = successful && DataProvider.PLOT.setCompletedSchematic(plot.getID(), null); + successful = successful && DataProvider.PLOT.setCompletedSchematic(plot.getId(), null); - if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getID() + "!")); + if (!successful) PlotSystem.getPlugin().getComponentLogger().error(text("Failed to abandon plot with the ID " + plot.getId() + "!")); }); return true; } @@ -433,12 +433,12 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { public static boolean deletePlot(Plot plot) { if (abandonPlot(plot)) { CompletableFuture.runAsync(() -> { - if (DataProvider.PLOT.deletePlot(plot.getID())) return; - PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to abandon plot with the ID " + plot.getID() + "!")); + if (DataProvider.PLOT.deletePlot(plot.getId())) return; + PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to abandon plot with the ID " + plot.getId() + "!")); }); return true; } - PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to abandon plot with the ID " + plot.getID() + "!")); + PlotSystem.getPlugin().getComponentLogger().warn(text("Failed to abandon plot with the ID " + plot.getId() + "!")); return false; } } @@ -608,7 +608,7 @@ public static void sendGroupTipMessage(@NotNull Plot plot, Player player) { if (plot.getPlotMembers().isEmpty() && PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { Component tc = text("» ", DARK_GRAY) .append(text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_PLAY_WITH_FRIENDS), GRAY)) - .clickEvent(ClickEvent.runCommand("/plot members " + plot.getID())) + .clickEvent(ClickEvent.runCommand("/plot members " + plot.getId())) .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.MEMBERS))); player.sendMessage(tc); @@ -620,10 +620,10 @@ public static void sendFeedbackMessage(@NotNull List notific player.sendMessage(text(MSG_LINE, DARK_GRAY)); for (ReviewNotification notification : notifications) { PlotReview review = DataProvider.REVIEW.getReview(notification.reviewId()).orElseThrow(); - player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(review.getPlot().getID())), GREEN))); + player.sendMessage(text("» ", DARK_GRAY).append(text(LangUtil.getInstance().get(player, LangPaths.Message.Info.REVIEWED_PLOT, String.valueOf(review.getPlot().getId())), GREEN))); Component tc = text(LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_SHOW_FEEDBACK), GOLD) - .clickEvent(ClickEvent.runCommand("/plot feedback " + review.getPlot().getID())) + .clickEvent(ClickEvent.runCommand("/plot feedback " + review.getPlot().getId())) .hoverEvent(text(LangUtil.getInstance().get(player, LangPaths.Plot.PLOT_NAME) + " " + LangUtil.getInstance().get(player, LangPaths.Review.FEEDBACK))); player.sendMessage(tc); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java index 446d2710..d37dcccc 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/CityPlotWorld.java @@ -19,7 +19,7 @@ public class CityPlotWorld extends PlotWorld { public CityPlotWorld(@NotNull Plot plot) { - super("C-" + plot.getCityProject().getID(), plot); + super("C-" + plot.getCityProject().getId(), plot); } @Override @@ -30,7 +30,7 @@ public boolean teleportPlayer(@NotNull Player player) { player.setFlying(true); if (getPlot() != null) { - player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getID())))); + player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getId())))); Utils.updatePlayerInventorySlots(player); PlotUtils.ChatFormatting.sendLinkMessages(getPlot(), player); @@ -47,7 +47,7 @@ public boolean teleportPlayer(@NotNull Player player) { @Override public String getRegionName() { - return super.getRegionName() + "-" + getPlot().getID(); + return super.getRegionName() + "-" + getPlot().getId(); } @@ -79,13 +79,13 @@ public int getWorldHeight() throws IOException { if (clipboard != null) { int plotHeight = clipboard.getMinimumPoint().y(); - /// Minimum building height for a plot (this should be configurable depending on minecraft build limit) - /// This is in the case that a plot is created at y level 300 where the max build limit is 318, - /// so you don't want builder to only be able to build for 18 blocks + // Minimum building height for a plot (this should be configurable depending on minecraft build limit) + // This is in the case that a plot is created at y level 300 where the max build limit is 318, + // so you don't want builder to only be able to build for 18 blocks int minBuildingHeight = 128; - /// Negative y level of the current minecraft version (1.21) - /// Additional ground layer the plot use to save as schematic need to be included for plot's y-level + // Negative y level of the current minecraft version (1.21) + // Additional ground layer the plot use to save as schematic need to be included for plot's y-level int groundLayer = 64; // Plots created outside of vanilla build limit or the build-able height is too small diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java index 8ea21905..2f439bec 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/world/OnePlotWorld.java @@ -24,7 +24,7 @@ public class OnePlotWorld extends PlotWorld { private final Builder plotOwner; public OnePlotWorld(@NotNull AbstractPlot plot) { - super((plot instanceof TutorialPlot ? "T-" : "P-") + plot.getID(), plot); + super((plot instanceof TutorialPlot ? "T-" : "P-") + plot.getId(), plot); this.plotOwner = plot.getPlotOwner(); } @@ -62,7 +62,7 @@ protected void onComplete(boolean failed, boolean unloadWorld) { }; if (!isWorldGenerated() || !isWorldLoaded()) { - PlotSystem.getPlugin().getComponentLogger().warn(text("Could not regenerate world " + getWorldName() + " for plot " + getPlot().getID() + "!")); + PlotSystem.getPlugin().getComponentLogger().warn(text("Could not regenerate world " + getWorldName() + " for plot " + getPlot().getId() + "!")); return false; } return true; @@ -90,7 +90,7 @@ public boolean teleportPlayer(@NotNull Player player) { if (getPlot() == null) return true; if (getPlot().getPlotType() != PlotType.TUTORIAL) { - player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getID())))); + player.sendMessage(Utils.ChatUtils.getInfoFormat(LangUtil.getInstance().get(player, LangPaths.Message.Info.TELEPORTING_PLOT, String.valueOf(getPlot().getId())))); PlotUtils.ChatFormatting.sendLinkMessages(getPlot(), player); } Utils.updatePlayerInventorySlots(player); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java index 6771b769..bc58723c 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/review/PlotReview.java @@ -1,5 +1,6 @@ package com.alpsbte.plotsystem.core.system.review; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.system.Builder; import com.alpsbte.plotsystem.core.system.plot.Plot; @@ -75,24 +76,37 @@ public boolean undoReview() { // remove owner score and remove plot from slot if (!plot.getPlotOwner().addScore(splitScore == -1 ? -score : -splitScore)) return false; - Slot slot = plot.getPlotOwner().getSlotByPlotId(plot.getID()); // get slot if plot is still in slots (rejected) + Slot slot = plot.getPlotOwner().getSlotByPlotId(plot.getId()); // get slot if plot is still in slots (rejected) if (slot == null) slot = plot.getPlotOwner().getFreeSlot(); // get new slot otherwise (completed) if (slot == null) return false; - if (!plot.getPlotOwner().setSlot(slot, plot.getID())) return false; + if (!plot.getPlotOwner().setSlot(slot, plot.getId())) return false; // remove members score and remove plot from slot for (Builder member : plot.getPlotMembers()) { if (!member.addScore(-splitScore)) return false; - Slot memberSlot = member.getSlotByPlotId(plot.getID()); + Slot memberSlot = member.getSlotByPlotId(plot.getId()); if (memberSlot == null) memberSlot = member.getFreeSlot(); - if (memberSlot == null || member.setSlot(memberSlot, plot.getID())) return false; + if (memberSlot == null || member.setSlot(memberSlot, plot.getId())) return false; } - plot.setStatus(Status.unreviewed); - plot.setPasted(false); + boolean successful = true; + if (!plot.setStatus(Status.unreviewed)) { + successful = false; + PlotSystem.getPlugin().getComponentLogger().error("Failed to set plot status to unreviewed while undoing review for plot ID {}", plot.getId()); + } + + if (!plot.setPasted(false)) { + successful = false; + PlotSystem.getPlugin().getComponentLogger().error("Failed to set plot pasted status to false while undoing review for plot ID {}", plot.getId()); + } + + if (!DataProvider.REVIEW.removeReview(reviewId)) { + successful = false; + PlotSystem.getPlugin().getComponentLogger().error("Failed to remove plot review with ID {} from database!", reviewId); + } - return DataProvider.REVIEW.removeReview(reviewId); + return successful; } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index 4a275a7d..c6b6fcab 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -77,7 +77,7 @@ protected AbstractPlotTutorial(Player player, int tutorialId, int stageId) { @Override protected TutorialNPC initNpc() { return new TutorialNPC( - "ps-tutorial-" + tutorialPlot.getID(), + "ps-tutorial-" + tutorialPlot.getId(), ChatColor.GOLD + ChatColor.BOLD.toString() + PlotSystem.getPlugin().getConfig().getString(ConfigPaths.TUTORIAL_NPC_NAME), ChatColor.GRAY + "(" + LangUtil.getInstance().get(getPlayer(), LangPaths.Note.Action.RIGHT_CLICK) + ")", PlotSystem.getPlugin().getConfig().getString(ConfigPaths.TUTORIAL_NPC_TEXTURE), @@ -140,7 +140,11 @@ public void saveTutorial(int stageId) { Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { if (stageId >= stages.size()) { if (!tutorialPlot.isComplete()) tutorialPlot.setComplete(); - } else if (stageId > tutorialPlot.getStageID()) tutorialPlot.setStageID(stageId); + } else if (stageId > tutorialPlot.getStageID()) { + if (!tutorialPlot.setStageID(stageId)) { + PlotSystem.getPlugin().getComponentLogger().error("Could not save tutorial progress for tutorial plot #{}!", tutorialPlot.getId()); + } + } }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java index 85d1fe45..124e03a1 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorial.java @@ -9,6 +9,7 @@ import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; @@ -16,7 +17,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.stream.Collectors; import static net.kyori.adventure.text.Component.text; @@ -115,7 +115,7 @@ protected interface PrepareStageAction { */ protected abstract void prepareStage(PrepareStageAction action); - protected AbstractTutorial(Player player, int tutorialId, int stageId) { + protected AbstractTutorial(@NotNull Player player, int tutorialId, int stageId) { this.tutorialId = tutorialId; this.playerUUID = player.getUniqueId(); this.player = player; @@ -161,7 +161,7 @@ public List getActiveHolograms() { .filter(AbstractTutorialHologram.class::isInstance) .filter(holo -> holo.isVisible(playerUUID)) .map(h -> (AbstractTutorialHologram) h) - .collect(Collectors.toList()); + .toList(); } @Override @@ -203,10 +203,8 @@ protected void nextStage() { // Ge the timeline of the current stage stageTimeline = currentStage.getTimeline(); - prepareStage(() -> { - // Start tasks timeline - stageTimeline.StartTimeline(); - }); + // Start tasks timeline + prepareStage(stageTimeline::StartTimeline); } catch (Exception ex) { onException(ex); } @@ -251,7 +249,7 @@ public void onException(Exception ex) { PlotSystem.getPlugin().getComponentLogger().error(text("An error occurred while processing tutorial!"), ex); // Send player back to hub after 3 seconds if an error occurred - Bukkit.getScheduler().runTaskLater(PlotSystem.getPlugin(), () -> onTutorialStop(player.getUniqueId()), 20 * 3); + Bukkit.getScheduler().runTaskLater(PlotSystem.getPlugin(), () -> onTutorialStop(player.getUniqueId()), 20L * 3); } /** @@ -263,16 +261,6 @@ public List> getStages() { return stages; } - /** - * Gets all registered worlds of the tutorial. - * - * @return list of all worlds - */ - public List getWorlds() { - return worlds; - } - - /** * Gets all active tutorials currently being run by a player. * diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java index 80ef5b10..c0bf920a 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractTutorialHologram.java @@ -27,9 +27,9 @@ public interface ClickAction { void onClick(@NotNull HologramClickEvent clickEvent); } - private final static int MAX_HOLOGRAM_LENGTH = 48; // The maximum length of a line in the hologram - private final static String HOLOGRAM_LINE_BREAKER = "%newline%"; - private final static String EMPTY_TAG = "&f"; + private static final int MAX_HOLOGRAM_LENGTH = 48; // The maximum length of a line in the hologram + private static final String HOLOGRAM_LINE_BREAKER = "%newline%"; + private static final String EMPTY_TAG = "&f"; protected final Player player; protected final int holoId; @@ -42,7 +42,7 @@ public interface ClickAction { private ClickAction markAsReadClickAction; private boolean isMarkAsReadClicked = false; - public AbstractTutorialHologram(Player player, int tutorialId, int holoId, String content, int readMoreId) { + protected AbstractTutorialHologram(@NotNull Player player, int tutorialId, int holoId, String content, int readMoreId) { super("ps-tutorial-" + tutorialId + "-" + holoId, null, true); this.holoId = holoId; this.player = player; @@ -87,7 +87,7 @@ public AbstractTutorialHologram(Player player, int tutorialId, int holoId, Strin protected abstract String getMarkAsReadClickedActionText(); @Override - public void create(Player player) { + public void create(@NotNull Player player) { setLocation(new Location(player.getWorld(), vectorPos.getX(), vectorPos.getY(), vectorPos.getZ())); super.create(player); } @@ -103,7 +103,7 @@ public String getTitle(UUID playerUUID) { } @Override - public boolean hasViewPermission(UUID uuid) { + public boolean hasViewPermission(@NotNull UUID uuid) { return player.getUniqueId().toString().equals(uuid.toString()); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java index 5695ffe4..a9594303 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/BeginnerTutorial.java @@ -32,6 +32,10 @@ import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.util.Vector; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; import java.io.IOException; import java.util.ArrayList; @@ -129,8 +133,9 @@ protected List setTasks() { TEXT_HIGHLIGHT_END); } + @Contract(pure = true) @Override - protected List setHolograms() { + protected @Nullable List setHolograms() { return null; } @@ -178,8 +183,9 @@ protected List setTasks() { return LangUtil.getInstance().getList(getPlayer(), LangPaths.Tutorials.Beginner.STAGE2_TASKS); } + @Contract(pure = true) @Override - protected List setHolograms() { + protected @Nullable List setHolograms() { return null; } @@ -231,8 +237,9 @@ protected List setTasks() { TEXT_HIGHLIGHT_START + "/tpll" + TEXT_HIGHLIGHT_END); } + @Contract(" -> new") @Override - protected List setHolograms() { + protected @NotNull @Unmodifiable List setHolograms() { return Collections.singletonList( new PlotTutorialHologram(getPlayer(), getId(), 0, getMessages().get(4), 3) ); @@ -289,8 +296,9 @@ protected List setTasks() { TEXT_HIGHLIGHT_START + "//wand" + TEXT_HIGHLIGHT_END); } + @Contract(pure = true) @Override - protected List setHolograms() { + protected @Nullable List setHolograms() { return null; } @@ -333,8 +341,9 @@ protected List setTasks() { TEXT_HIGHLIGHT_START + "//line " + BASE_BLOCKS.getFirst() + TEXT_HIGHLIGHT_END); } + @Contract(pure = true) @Override - protected List setHolograms() { + protected @Nullable List setHolograms() { return null; } @@ -400,13 +409,14 @@ protected List setTasks() { return LangUtil.getInstance().getList(getPlayer(), LangPaths.Tutorials.Beginner.STAGE6_TASKS); } + @Contract(" -> new") @Override - protected List setHolograms() { + protected @NotNull @Unmodifiable List setHolograms() { return Collections.singletonList(new PlotTutorialHologram(getPlayer(), getId(), 13, getMessages().get(7), 4)); } @Override - public StageTimeline getTimeline() throws IOException { + public @NotNull StageTimeline getTimeline() throws IOException { StageTimeline stage = new StageTimeline(getPlayer()) .delay(Delay.TIMELINE_START) .sendChatMessage(deserialize(getMessages().get(0)), Sound.NPC_TALK, true) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java index 33cd80c3..48e0c76d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/AbstractPlotStage.java @@ -8,7 +8,7 @@ public abstract class AbstractPlotStage extends AbstractStage { private final int initSchematicId; protected AbstractPlotStage(Player player, int initWorldIndex, TutorialPlot plot, int initSchematicId) { - super(player, plot.getID(), initWorldIndex); + super(player, plot.getId(), initWorldIndex); this.plot = plot; this.initSchematicId = initSchematicId; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java index 607e98f0..ae1fa2a9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/StageTimeline.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -242,18 +241,6 @@ public StageTimeline createHolograms(Component assignmentMessage, AbstractTutori return this; } - /** - * Adds a DeleteHologramTask to the timeline. - * Deletes a specific tutorial hologram from the stage. - * - * @param hologram hologram to delete from the current stage - * @see AbstractStage#getHolograms() - */ - public StageTimeline deleteHologram(AbstractTutorialHologram hologram) { - tasks.add(new DeleteHologramTask(player, Collections.singletonList(hologram))); - return this; - } - /** * Adds a DeleteHologramTask to the timeline. * Deletes all tutorial holograms from the current stage. diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java index f8bf5a10..bc3cef0d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/AbstractTask.java @@ -8,11 +8,6 @@ import org.bukkit.entity.Player; public abstract class AbstractTask { - @FunctionalInterface - public interface TaskAction { - void performAction(T t); - } - @FunctionalInterface public interface BiTaskAction { void performAction(T t, R r); @@ -30,7 +25,7 @@ public interface BiTaskAction { * * @param player The player who is doing the task. */ - public AbstractTask(Player player) { + protected AbstractTask(Player player) { this(player, null, 0); } @@ -41,7 +36,7 @@ public AbstractTask(Player player) { * @param assignmentMessage The message which is displayed in the action bar and chat. * @param totalAssignments The total assignment progress which is needed to complete the task. */ - public AbstractTask(Player player, Component assignmentMessage, int totalAssignments) { + protected AbstractTask(Player player, Component assignmentMessage, int totalAssignments) { this.player = player; this.assignmentMessage = assignmentMessage; this.totalAssignments = totalAssignments; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java index d920cd6d..cf0c06d4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/BuildEventTask.java @@ -48,10 +48,10 @@ public void performEvent(Event event) { Block placedBlock = buildEvent.getBlockPlaced(); Vector placedBlockVector = new Vector(placedBlock.getX(), placedBlock.getY(), placedBlock.getZ()); - for (Vector blockVector : blocksToBuild.keySet()) { - if (blockVector.equals(placedBlockVector)) { - if (placedBlock.getBlockData().matches(blocksToBuild.get(blockVector))) { - removeBlockToBuild(blockVector); + for (Map.Entry vectorBlock : blocksToBuild.entrySet()) { + if (vectorBlock.getKey().equals(placedBlockVector)) { + if (placedBlock.getBlockData().matches(vectorBlock.getValue())) { + removeBlockToBuild(vectorBlock.getKey()); return; } onPlacedBlockAction.performAction(placedBlockVector, false); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java index 573d598d..5e5d9904 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/events/commands/AbstractCmdEventTask.java @@ -16,11 +16,11 @@ public abstract class AbstractCmdEventTask extends AbstractTask implements Event private final boolean isCancelCmdEvent; - public AbstractCmdEventTask(Player player, String expectedCommand, Component assignmentMessage, int totalAssignments, boolean cancelCmdEvent) { + protected AbstractCmdEventTask(Player player, String expectedCommand, Component assignmentMessage, int totalAssignments, boolean cancelCmdEvent) { this(player, expectedCommand, null, assignmentMessage, totalAssignments, cancelCmdEvent); } - public AbstractCmdEventTask(Player player, String expectedCommand, String[] args1, Component assignmentMessage, int totalAssignments, boolean cancelCmdEvent) { + protected AbstractCmdEventTask(Player player, String expectedCommand, String[] args1, Component assignmentMessage, int totalAssignments, boolean cancelCmdEvent) { super(player, assignmentMessage, totalAssignments); this.expectedCommand = expectedCommand; this.args1 = args1; @@ -36,20 +36,18 @@ public void performTask() { @Override public void performEvent(Event event) { - if (event instanceof PlayerCommandPreprocessEvent cmdEvent) { - if (cmdEvent.getMessage().toLowerCase().startsWith(expectedCommand.toLowerCase())) { + if (event instanceof PlayerCommandPreprocessEvent cmdEvent && cmdEvent.getMessage().toLowerCase().startsWith(expectedCommand.toLowerCase())) { if (isCancelCmdEvent) cmdEvent.setCancelled(true); // Check if the expected args are used String[] args = cmdEvent.getMessage().toLowerCase().replaceFirst(expectedCommand.toLowerCase(), "").trim().split(" "); - if (args1 != null && args1.length > 0) { - if (args.length == 0 || Arrays.stream(args1).noneMatch(arg -> arg.equalsIgnoreCase(args[0]))) { + if (args1 != null && args1.length > 0 && (args.length == 0 || Arrays.stream(args1).noneMatch(arg -> arg.equalsIgnoreCase(args[0])))) { onCommand(false, args); return; } - } - onCommand(true, args); + + onCommand(true, args); } - } + } } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java index 4ec67f7d..77817207 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/stage/tasks/message/ChatMessageTask.java @@ -10,6 +10,7 @@ import net.kyori.adventure.text.event.HoverEvent; import org.bukkit.Sound; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.DARK_GRAY; @@ -44,7 +45,7 @@ public boolean isWaitToContinue() { return isWaitToContinue; } - public static void sendTaskMessage(Player player, Object[] messages, boolean waitToContinue) { + public static void sendTaskMessage(@NotNull Player player, Object[] messages, boolean waitToContinue) { AbstractTutorial tutorial = AbstractTutorial.getActiveTutorial(player.getUniqueId()); if (tutorial == null || tutorial.getNPC() == null) return; @@ -53,12 +54,12 @@ public static void sendTaskMessage(Player player, Object[] messages, boolean wai player.sendMessage(text(tutorial.getNPC().getDisplayName() + " ") .append(TutorialUtils.CHAT_PREFIX_COMPONENT)); for (Object message : messages) { - if (message instanceof ClickableTaskMessage) { - player.sendMessage(((ClickableTaskMessage) message).getComponent()); - } else if (message instanceof Component) { - player.sendMessage(((Component) message).color(GRAY)); - } else if (message instanceof String) { - player.sendMessage(text((String) message).color(GRAY)); + if (message instanceof ClickableTaskMessage ctm) { + player.sendMessage(ctm.getComponent()); + } else if (message instanceof Component c) { + player.sendMessage(c.color(GRAY)); + } else if (message instanceof String s) { + player.sendMessage(text(s).color(GRAY)); } } @@ -68,7 +69,7 @@ public static void sendTaskMessage(Player player, Object[] messages, boolean wai LangUtil.getInstance().get(player, LangPaths.Note.Action.CLICK_TO_PROCEED))); } - public static Component getContinueButtonComponent(String text, String hoverText) { + public static @NotNull Component getContinueButtonComponent(String text, String hoverText) { return text("[", DARK_GRAY).append(text(text, GREEN).append(text("]", DARK_GRAY))) .hoverEvent(HoverEvent.showText(text(hoverText, GRAY))).clickEvent(ClickEvent.runCommand("/tutorial continue")); } @@ -79,12 +80,6 @@ public static class ClickableTaskMessage { private final Component hoverTextComponent; private final ClickEvent clickEvent; - public ClickableTaskMessage(String message, String hoverText, ClickEvent clickEvent) { - this.messageComponent = text(message); - this.hoverTextComponent = text(hoverText); - this.clickEvent = clickEvent; - } - public ClickableTaskMessage(Component messageComponent, Component hoverTextComponent, ClickEvent clickEvent) { this.messageComponent = messageComponent; this.hoverTextComponent = hoverTextComponent; diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java index 16751469..a7a03448 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/utils/TutorialNPC.java @@ -122,10 +122,6 @@ public TutorialNPCHologram getHologram() { return hologram; } - public String getId() { - return id; - } - public String getDisplayName() { return displayName; } @@ -133,8 +129,4 @@ public String getDisplayName() { public String getInteractionPrompt() { return interactionPrompt; } - - public SkinData getSkin() { - return skin; - } } diff --git a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java index cc36d77a..89b5aaa9 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/PlotMemberInvitation.java @@ -75,7 +75,9 @@ public PlotMemberInvitation(Player invitee, Plot plot) { public void acceptInvite() { Builder builder = Builder.byUUID(invitee.getUniqueId()); if (builder.getFreeSlot() != null) { - plot.addPlotMember(Builder.byUUID(invitee.getUniqueId())); + if (!plot.addPlotMember(Builder.byUUID(invitee.getUniqueId()))) { + PlotSystem.getPlugin().getComponentLogger().error("Failed to add plot member {} to plot #{}!", invitee.getName(), plot.getId()); + } // Messages Receiver invitee.sendMessage(Utils.ChatUtils.getInfoFormat(AlpsUtils.deserialize(LangUtil.getInstance().get(invitee, diff --git a/src/main/java/com/alpsbte/plotsystem/utils/conversion/MathUtils.java b/src/main/java/com/alpsbte/plotsystem/utils/conversion/MathUtils.java index 82f5fe8a..2ce39ee5 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/conversion/MathUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/conversion/MathUtils.java @@ -1,37 +1,35 @@ package com.alpsbte.plotsystem.utils.conversion; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; + public class MathUtils { /** * Square root of 3 */ public static final double ROOT3 = Math.sqrt(3); - /** - * Two times pi - */ - public static final double TAU = 2 * Math.PI; - - /** * Converts geographic latitude and longitude coordinates to spherical coordinates on a sphere of radius 1. * * @param geo - geographic coordinates as a double array of length 2, {longitude, latitude}, in degrees * @return the corresponding spherical coordinates in radians: {longitude, colatitude} */ - public static double[] geo2Spherical(double[] geo) { + @Contract("_ -> new") + public static double @NotNull [] geo2Spherical(double @NotNull [] geo) { double lambda = Math.toRadians(geo[0]); double phi = Math.toRadians(90 - geo[1]); return new double[]{lambda, phi}; } - /** * Converts spherical coordinates to geographic coordinates on a sphere of radius 1. * * @param spherical - spherical coordinates in radians as a double array of length 2: {longitude, colatitude} * @return the corresponding geographic coordinates in degrees: {longitude, latitude} */ - public static double[] spherical2Geo(double[] spherical) { + @Contract("_ -> new") + public static double @NotNull [] spherical2Geo(double @NotNull [] spherical) { double lon = Math.toDegrees(spherical[0]); double lat = 90 - Math.toDegrees(spherical[1]); return new double[]{lon, lat}; @@ -44,7 +42,8 @@ public static double[] spherical2Geo(double[] spherical) { * @param spherical - spherical coordinates in radians as a double array of length 2: {longitude, colatitude} * @return the corresponding Cartesian coordinates: {x, y, z} */ - public static double[] spherical2Cartesian(double[] spherical) { + @Contract("_ -> new") + public static double @NotNull [] spherical2Cartesian(double @NotNull [] spherical) { double sinphi = Math.sin(spherical[1]); double x = sinphi * Math.cos(spherical[0]); double y = sinphi * Math.sin(spherical[0]); @@ -58,7 +57,8 @@ public static double[] spherical2Cartesian(double[] spherical) { * @param cartesian - Cartesian coordinates as double array of length 3: {x, y, z} * @return the spherical coordinates of the corresponding normalized vector */ - public static double[] cartesian2Spherical(double[] cartesian) { + @Contract("_ -> new") + public static double @NotNull [] cartesian2Spherical(double @NotNull [] cartesian) { double lambda = Math.atan2(cartesian[1], cartesian[0]); double phi = Math.atan2(Math.sqrt(cartesian[0] * cartesian[0] + cartesian[1] * cartesian[1]), cartesian[2]); return new double[]{lambda, phi}; @@ -66,14 +66,15 @@ public static double[] cartesian2Spherical(double[] cartesian) { /** - * TODO produceZYZRotationMatrix javadoc + * Generates a Z\-Y\-Z Euler rotation matrix for angles a, b, c (in radians). * - * @param a - * @param b - * @param c - * @return + * @param a rotation about the Z\-axis (first Z rotation) in radians + * @param b rotation about the Y\-axis (tilt, beta) in radians + * @param c rotation about the Z\-axis (second Z rotation) in radians + * @return a new 3x3 rotation matrix as double[][] in format matrix[row][col] + * corresponding to the composition Rz(a) * Ry(b) * Rz(c) */ - public static double[][] produceZYZRotationMatrix(double a, double b, double c) { + public static double[] @NotNull [] produceZYZRotationMatrix(double a, double b, double c) { double sina = Math.sin(a); double cosa = Math.cos(a); @@ -106,7 +107,8 @@ public static double[][] produceZYZRotationMatrix(double a, double b, double c) * @param vector - the vector as double array of length n * @return the result of the multiplication as an array of double on length n */ - public static double[] matVecProdD(double[][] matrix, double[] vector) { + @Contract(pure = true) + public static double @NotNull [] matVecProdD(double[][] matrix, double @NotNull [] vector) { double[] result = new double[vector.length]; for (int i = 0; i < result.length; i++) { for (int j = 0; j < matrix[i].length; j++) { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index c4c165df..1be8f8d7 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -285,7 +285,6 @@ private Error() {} public static final String CAN_ONLY_UNDO_SUBMISSIONS_UNREVIEWED_PLOTS = ERROR_PREFIX + "can-only-undo-submissions-unreviewed-plots"; public static final String CAN_ONLY_MANAGE_MEMBERS_UNFINISHED = ERROR_PREFIX + "can-only-manage-members-unfinished-plots"; public static final String CANNOT_TELEPORT_OUTSIDE_PLOT = ERROR_PREFIX + "cannot-teleport-outside-plot"; - public static final String CANNOT_UNDO_REVIEW = ERROR_PREFIX + "cannot-undo-review"; public static final String CANNOT_SEND_FEEDBACK = ERROR_PREFIX + "cannot-send-feedback"; public static final String CANNOT_REVIEW_OWN_PLOT = ERROR_PREFIX + "cannot-review-own-plot"; public static final String CANNOT_MODIFY_LEGACY_PLOT = ERROR_PREFIX + "cannot-modify-legacy-plot"; @@ -322,9 +321,6 @@ public static final class Leaderboards { private Leaderboards() {} private static final String LBS = "leaderboards."; public static final String PAGES = LBS + "pages."; - public static final String ACTIONBAR_POSITION = LBS + "actionbar-position"; - public static final String ACTIONBAR_PERCENTAGE = LBS + "actionbar-percentage"; - public static final String NOT_ON_LEADERBOARD = LBS + "not-on-leaderboard"; } public static final class Tutorials { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java index 717e98ee..e3c08e01 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/items/BaseItems.java @@ -5,11 +5,11 @@ import org.bukkit.Material; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; public enum BaseItems { COMPANION_ITEM("companion-item"), - LEADERBOARD_PLOT("leaderboard-plot"), LEADERBOARD_SCORE("leaderboard-score"), PLOT_UNFINISHED("plot-unfinished"), @@ -42,7 +42,6 @@ public enum BaseItems { REVIEW_POINT_FOUR("review-point-four"), REVIEW_POINT_FIVE("review-point-five"), REVIEW_SUBMIT("review-submit"), - REVIEW_CANCEL("review-cancel"), REVIEW_INFO("review-info"), REVIEW_INFO_PLOT("review-info-plot"), REVIEW_TOGGLE_OPTIONAL("review-toggle-optional"), @@ -74,10 +73,10 @@ public enum BaseItems { itemStack = ItemUtils.getConfiguredItem(materialString, customModelData); itemStack.getItemMeta().setAttributeModifiers(null); - itemStack.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ADDITIONAL_TOOLTIP, ItemFlag.HIDE_ENCHANTS); + itemStack.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_ENCHANTS); } - public ItemStack getItem() { + public @NotNull ItemStack getItem() { return itemStack.clone(); } } From 1b7a305bb7811e9eaf7df494dd45e737f001290d Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 6 Nov 2025 20:31:46 +0100 Subject: [PATCH 155/175] fix: fix the next button in the review menu We used to set the items SetAsync where the source and other stuff weren't. Also improved the plot filtering. Mainly written by GitHub CoPilot. --- .../core/menus/review/ReviewMenu.java | 60 ++++++++++--------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index 7b618833..9aba9ea9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -37,8 +37,16 @@ public ReviewMenu(Player player) { protected List getSource() { List plots = new ArrayList<>(); cityProjects = DataProvider.BUILD_TEAM.getReviewerCities(getMenuPlayer().getUniqueId()); - plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unreviewed)); - plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unfinished)); + + // Get plots based on city filter + if (filteredCityProject != null) { + plots.addAll(DataProvider.PLOT.getPlots(List.of(filteredCityProject), Status.unreviewed)); + plots.addAll(DataProvider.PLOT.getPlots(List.of(filteredCityProject), Status.unfinished)); + } else { + plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unreviewed)); + plots.addAll(DataProvider.PLOT.getPlots(cityProjects, Status.unfinished)); + } + return plots; } @@ -75,6 +83,12 @@ protected void setPaginatedMenuItemsAsync(List source) { .setLore(lines) .build()); } + + // Set previous page item + getMenu().getSlot(46).setItem(hasPreviousPage() ? MenuItems.previousPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); + + // Set next page item + getMenu().getSlot(52).setItem(hasNextPage() ? MenuItems.nextPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); } @Override @@ -92,15 +106,22 @@ protected void setPaginatedItemClickEventsAsync(List source) { player.performCommand("review " + plot.getId()); }); } - } - @Override - protected void setMenuItemsAsync() { - // Set previous page item - getMenu().getSlot(46).setItem(hasPreviousPage() ? MenuItems.previousPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); + // Set click event for previous page item + if (hasPreviousPage()) { + getMenu().getSlot(46).setClickHandler((clickPlayer, clickInformation) -> { + previousPage(); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); + }); + } - // Set next page item - getMenu().getSlot(52).setItem(hasNextPage() ? MenuItems.nextPageItem(getMenuPlayer()) : Utils.DEFAULT_ITEM); + // Set click event for next page item + if (hasNextPage()) { + getMenu().getSlot(52).setClickHandler((clickPlayer, clickInformation) -> { + nextPage(); + clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); + }); + } } @Override @@ -120,24 +141,8 @@ protected void setItemClickEventsAsync() { reloadMenuAsync(false); }); - // Set click event for previous page item - if (hasPreviousPage()) { - getMenu().getSlot(46).setClickHandler((clickPlayer, clickInformation) -> { - previousPage(); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - }); - } - // Set click event for close item getMenu().getSlot(49).setClickHandler((clickPlayer, clickInformation) -> clickPlayer.closeInventory()); - - // Set click event for next page item - if (hasNextPage()) { - getMenu().getSlot(52).setClickHandler((clickPlayer, clickInformation) -> { - nextPage(); - clickPlayer.playSound(clickPlayer.getLocation(), Utils.SoundUtils.INVENTORY_CLICK_SOUND, 1, 1); - }); - } } @Override @@ -154,10 +159,7 @@ protected Mask getMask() { } private List getFilteredPlots(@NotNull List plots) { - List filteredPlots = plots.stream().map(p -> (Plot) p).toList(); - if (filteredCityProject != null) - filteredPlots = filteredPlots.stream().filter(p -> p.getCityProject().getId().equals(filteredCityProject.getId())).toList(); - return filteredPlots; + return plots.stream().map(p -> (Plot) p).toList(); } private ItemStack getFilterItem(Player langPlayer) { From 39f04b722cb0cf8140d79a50409e299efd4e062a Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 6 Nov 2025 22:55:56 +0100 Subject: [PATCH 156/175] fix: improve plot ID handling and add owner validation in plot member management Otherwise /p members doesn't work at all without id. --- .../commands/plot/CMD_Plot_Members.java | 27 +++++++++++++++---- .../plotsystem/core/menus/PlotMemberMenu.java | 7 ++--- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java index a1831290..3b61e769 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Members.java @@ -1,6 +1,7 @@ package com.alpsbte.plotsystem.commands.plot; import com.alpsbte.alpslib.utils.AlpsUtils; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.commands.BaseCommand; import com.alpsbte.plotsystem.commands.SubCommand; import com.alpsbte.plotsystem.core.database.DataProvider; @@ -38,10 +39,18 @@ public void onCommand(CommandSender sender, String[] args) { CompletableFuture.runAsync(() -> { Plot plot; - if (args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null) { - plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); - if (plot == null) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("This plot does not exist!")); + + // Use tryParseInt result (avoids double parsing) and handle null safely + if (args.length > 0) { + Integer id = AlpsUtils.tryParseInt(args[0]); + if (id != null) { + plot = DataProvider.PLOT.getPlotById(id); + if (plot == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("This plot does not exist!")); + return; + } + } else { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Invalid plot ID.")); return; } } else if (PlotUtils.isPlotWorld(player.getWorld())) { @@ -57,6 +66,12 @@ public void onCommand(CommandSender sender, String[] args) { return; } + // Guard against missing owner data + if (plot.getPlotOwner() == null || plot.getPlotOwner().getUUID() == null) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("This plot has no owner assigned. Contact an admin.")); + return; + } + if (!plot.getPlotOwner().getUUID().equals(player.getUniqueId()) && !player.hasPermission("plotsystem.admin")) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("You don't have permission to manage this plot's members!")); return; @@ -66,7 +81,9 @@ public void onCommand(CommandSender sender, String[] args) { return; } - new PlotMemberMenu(plot, player); + // Switch to main thread for menu creation (GUI operations must be on main thread) + Plot finalPlot = plot; + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new PlotMemberMenu(finalPlot, player)); }); } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index bdfd219a..a03b6174 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -13,7 +13,6 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; import com.alpsbte.plotsystem.utils.items.MenuItems; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryCloseEvent; @@ -48,14 +47,16 @@ protected void setPreviewItems() { getMenu().getSlot(10).setItem(MenuItems.loadingItem(Material.PLAYER_HEAD, getMenuPlayer())); // Set loading item for plot member items - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + if (plot != null) { List plotMembers = plot.getPlotMembers(); for (int i = 1; i <= 3; i++) { getMenu().getSlot(11 + i).setItem(plotMembers.size() >= i ? MenuItems.loadingItem(Material.PLAYER_HEAD, getMenuPlayer()) : emptyMemberSlotItem); } - }); + } else { + PlotSystem.getPlugin().getComponentLogger().warn(text("PlotMemberMenu: plot is null in setPreviewItems")); + } // Set add plot member item ItemStack addItem = BaseItems.MENU_ADD.getItem(); From 2d08c673efc9cf36177576f61932e5a6d40bf37a Mon Sep 17 00:00:00 2001 From: Zoriot Date: Fri, 7 Nov 2025 22:06:02 +0100 Subject: [PATCH 157/175] feat(review): order by plot_id + add when the plot will be deleted --- .../core/database/providers/PlotProvider.java | 2 +- .../core/menus/review/ReviewMenu.java | 11 +++++++++ .../plotsystem/utils/io/LangPaths.java | 23 +++++++++---------- src/main/resources/lang/de_DE.yml | 1 + src/main/resources/lang/en_GB.yml | 1 + 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java index 140b7b5e..c06507f4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java +++ b/src/main/java/com/alpsbte/plotsystem/core/database/providers/PlotProvider.java @@ -81,7 +81,7 @@ public List getPlots(@NotNull List cities, Status... statuses String cityPlaceholders = "?,".repeat(cities.size() - 1) + "?"; String query = "SELECT " + PLOT_SQL_COLUMNS + " FROM plot WHERE city_project_id IN (" + cityPlaceholders + ")"; - query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?);" : ";"; + query += statuses.length > 0 ? " AND status IN (" + "?,".repeat(statuses.length - 1) + "?) ORDER BY plot.plot_id;" : ";"; String qPlotsWithCitiesAndStatuses = query; return Utils.handleSqlException(List.of(), () -> SqlHelper.runQuery(qPlotsWithCitiesAndStatuses, ps -> { diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index 9aba9ea9..abde5b05 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -2,6 +2,7 @@ import com.alpsbte.alpslib.utils.item.ItemBuilder; import com.alpsbte.alpslib.utils.item.LegacyLoreBuilder; +import com.alpsbte.plotsystem.PlotSystem; import com.alpsbte.plotsystem.core.database.DataProvider; import com.alpsbte.plotsystem.core.menus.AbstractPaginatedMenu; import com.alpsbte.plotsystem.core.menus.PlotActionsMenu; @@ -10,6 +11,7 @@ import com.alpsbte.plotsystem.core.system.plot.Plot; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import com.alpsbte.plotsystem.utils.items.BaseItems; @@ -21,10 +23,13 @@ import org.ipvp.canvas.mask.Mask; import org.jetbrains.annotations.NotNull; +import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import static java.time.temporal.ChronoUnit.DAYS; + public class ReviewMenu extends AbstractPaginatedMenu { private List cityProjects = new ArrayList<>(); private CityProject filteredCityProject = null; @@ -77,6 +82,12 @@ protected void setPaginatedMenuItemsAsync(List source) { lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.CITY) + ": §f" + plot.getCityProject().getName(getMenuPlayer())); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.COUNTRY) + ": §f" + plot.getCityProject().getCountry().getName(getMenuPlayer())); lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": §f" + plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase()); + lines.add(""); + + long inactivityIntervalDays = PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.INACTIVITY_INTERVAL); + long rejectedInactivityIntervalDays = (PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) != -1) ? PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) : inactivityIntervalDays; + long interval = plot.isRejected() ? rejectedInactivityIntervalDays : inactivityIntervalDays; + if (interval > -1) lines.add(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ABANDONED_IN_DAYS, String.valueOf(DAYS.between(LocalDate.now(), plot.getLastActivity().plusDays(interval))))); getMenu().getSlot(i + 9).setItem(new ItemBuilder(plot.getStatus() == Status.unfinished ? Material.MAP : Material.FILLED_MAP, 1) .setName("§b§l" + LangUtil.getInstance().get(getMenuPlayer(), plot.getStatus() == Status.unfinished ? LangPaths.Review.MANAGE_PLOT : LangPaths.Review.REVIEW_PLOT)) diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index 1be8f8d7..fc27cd52 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -19,8 +19,8 @@ private Plot() {} public static final String SCORE = PLOT_PREFIX + "score"; public static final String TOTAL_SCORE = PLOT_PREFIX + "total-score"; public static final String COMPLETED_PLOTS = PLOT_PREFIX + "completed-plots"; - public static final class GroupSystem { + private GroupSystem() {} private static final String GROUP_SYSTEM = PLOT_PREFIX + "group-system."; @@ -28,8 +28,8 @@ private GroupSystem() {} public static final String SHARED_BY_MEMBERS = GROUP_SYSTEM + "shared-by-members"; } } - public static final class CityProject { + private CityProject() {} private static final String CITY_PROJECT = "city-project."; public static final String CITIES = CITY_PROJECT + "cities"; @@ -40,15 +40,15 @@ private CityProject() {} public static final String PROJECT_NO_PLOTS_AVAILABLE = CITY_PROJECT + "no-plots-available"; public static final String FOR_YOUR_DIFFICULTY = CITY_PROJECT + "for-your-difficulty"; } - public static final class Country { + private Country() {} private static final String COUNTRY_PREFIX = "country."; public static final String COUNTRIES = COUNTRY_PREFIX + "countries"; } - public static final class Continent { + private Continent() {} private static final String CONTINENT_PREFIX = "continent."; @@ -59,16 +59,16 @@ private Continent() {} public static final String SOUTH_AMERICA = CONTINENT_PREFIX + "south-america"; public static final String NORTH_AMERICA = CONTINENT_PREFIX + "north-america"; } - public static final class Difficulty { + private Difficulty() {} private static final String DIFFICULTY_PREFIX = "difficulty."; public static final String AUTOMATIC = DIFFICULTY_PREFIX + "automatic"; public static final String SCORE_MULTIPLIER = DIFFICULTY_PREFIX + "score-multiplier"; } - public static final class MenuTitle { + private MenuTitle() {} private static final String MENU_TITLES = "menu-title."; public static final String CLOSE = MENU_TITLES + "close"; @@ -117,8 +117,8 @@ private MenuTitle() {} public static final String TUTORIAL_BEGINNER = MENU_TITLES + "tutorial-beginner"; public static final String COMPANION_RANDOM = MENU_TITLES + "companion-random"; } - public static final class MenuDescription { + private MenuDescription() {} private static final String MENU_DESCRIPTIONS = "menu-description."; public static final String ERROR = MENU_DESCRIPTIONS + "error-desc"; @@ -152,8 +152,8 @@ private MenuDescription() {} public static final String TUTORIAL_BEGINNER = MENU_DESCRIPTIONS + "tutorial-beginner-desc"; public static final String COMPANION_RANDOM = MENU_DESCRIPTIONS + "companion-random-desc"; } - public static final class Review { + private Review() {} private static final String REVIEW_PREFIX = "review."; @@ -171,10 +171,9 @@ private Review() {} public static final String BLOCK_PALETTE_POINTS = REVIEW_PREFIX + "block-palette-points"; public static final String TOGGLE_POINTS = REVIEW_PREFIX + "toggle-points"; public static final String TOTAL_POINTS = REVIEW_PREFIX + "total-points"; - + public static final String ABANDONED_IN_DAYS = REVIEW_PREFIX + "abandoned-in-days"; public static final class Criteria { private Criteria() {} - private static final String CRITERIA_PREFIX = REVIEW_PREFIX + "criteria."; public static final String ACCURACY = CRITERIA_PREFIX + "accuracy"; public static final String ACCURACY_DESC = CRITERIA_PREFIX + "accuracy-desc"; @@ -182,8 +181,8 @@ private Criteria() {} public static final String BLOCK_PALETTE_DESC = CRITERIA_PREFIX + "block-palette-desc"; } } - public static final class Note { + private Note() {} private static final String NOTES = "note."; public static final String TIP = NOTES + "tip"; @@ -196,8 +195,8 @@ private Note() {} public static final String CRITERIA_FULFILLED = NOTES + "criteria-fulfilled"; public static final String CRITERIA_NOT_FULFILLED = NOTES + "criteria-not-fulfilled"; public static final String LEGACY = NOTES + "legacy"; - public static final class Action { + private Action() {} private static final String ACTION_PREFIX = NOTES + "action."; public static final String READ = ACTION_PREFIX + "read"; diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index 1f031735..3bee8124 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -164,6 +164,7 @@ review: block-palette-points: "Block palette points" toggle-points: "Toggle points" total-points: "Total points" + abandoned-in-days: "§6Wird in §6{0} Tagen gelöscht" criteria: accuracy: "Genauigkeit" accuracy-desc: "Wie akkurat ist das Gebäude?%newline%%newline%- Sieht aus wie in RL%newline%- Korrekte Umrisse%newline%- Korrekte Höhen%newline%- Ist vollständig" diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 5b171631..7ace968f 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -164,6 +164,7 @@ review: block-palette-points: "Block palette points" toggle-points: "Toggle points" total-points: "Total points" + abandoned-in-days: "§6Abandoned in §6{0} days" criteria: accuracy: "Accuracy" accuracy-desc: "How accurate is the building?%newline%%newline%- Looks like in RL%newline%- Correct outlines%newline%- Correct height%newline%- Is completed" From 6f6ee721c7002656efce2dafc7990d2e48c7ed69 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 13 Nov 2025 23:41:36 +0100 Subject: [PATCH 158/175] fix: fix plot action abandon item --- .../com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java index 0c5016ce..d2924c14 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotActionsMenu.java @@ -80,11 +80,13 @@ protected void setMenuItemsAsync() { .build()); // Set plot feedback item + if (hasReview) { getMenu().getSlot(16) - .setItem(hasReview ? new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) + .setItem(new ItemBuilder(BaseItems.REVIEW_FEEDBACK.getItem()) .setName(text(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.FEEDBACK), AQUA).decoration(BOLD, true)) .setLore(new LoreBuilder().addLine(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.MenuDescription.FEEDBACK), true).build()) - .build() : Utils.DEFAULT_ITEM); + .build()); + } // Set plot members item if (!plot.isReviewed() && config.getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { From 4d174c1c2daf2d8b8094d015da89cb47b771e31c Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sat, 15 Nov 2025 00:39:23 +0100 Subject: [PATCH 159/175] fix(review): improve teleportation logic and add error handling for null plots --- .../commands/review/CMD_Review.java | 48 ++++++++++++++++--- .../plotsystem/core/menus/PlotMemberMenu.java | 5 ++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 8a130d46..075f59a2 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -24,6 +24,7 @@ import java.util.concurrent.CompletableFuture; +import static net.kyori.adventure.text.Component.text; import static net.kyori.adventure.text.format.NamedTextColor.RED; public class CMD_Review extends BaseCommand { @@ -79,21 +80,56 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N boolean isParticipant = plotToReview.getPlotOwner().getUUID() == player.getUniqueId() || plotToReview.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId()); if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) && isParticipant) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); + return; } // Check if the reviewer is on the plot boolean teleportPlayer = false; - if (currentPlot instanceof Plot) { - if (plotToReview.getId() != currentPlot.getId()) teleportPlayer = true; - } else teleportPlayer = true; + if (currentPlot instanceof Plot currentPlotCast) { + if (plotToReview.getId() != currentPlotCast.getId()) { + teleportPlayer = true; + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Player on different plot, will teleport. Current: " + currentPlotCast.getId() + ", Target: " + plotToReview.getId())); + } + } else { + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Player on target plot " + plotToReview.getId() + ", opening menu directly")); + } + } + } else { + teleportPlayer = true; + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Player not on any plot, will teleport to plot " + plotToReview.getId())); + } + } + + Plot finalPlotToReview = plotToReview; - // If the reviewer is not on the plot, teleport the player + // If the reviewer is not on the plot, teleport the player first if (teleportPlayer) { - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> plotToReview.getWorld().teleportPlayer(player)); + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + plotToReview.getWorld().teleportPlayer(player); + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Teleported player, scheduling menu open in 20 ticks")); + } + // Open menu after teleportation completes + Bukkit.getScheduler().runTaskLater(PlotSystem.getPlugin(), () -> { + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Opening ReviewPlotMenu for plot " + finalPlotToReview.getId())); + } + new ReviewPlotMenu(player, finalPlotToReview); + }, 20L); + }); return; } - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new ReviewPlotMenu(player, plotToReview)); + // Player is already on the plot, open menu on main thread + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Opening ReviewPlotMenu for plot " + finalPlotToReview.getId() + " (no teleport needed)")); + } + new ReviewPlotMenu(player, finalPlotToReview); + }); }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index a03b6174..9444e920 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -78,6 +78,11 @@ protected void setPreviewItems() { @Override protected void setMenuItemsAsync() { + if (plot == null) { + PlotSystem.getPlugin().getComponentLogger().error(text("PlotMemberMenu: plot is null in setMenuItemsAsync, cannot load menu items")); + return; + } + // Set plot owner item getMenu().getSlot(10) .setItem(new ItemBuilder(AlpsHeadUtils.getPlayerHead(plot.getPlotOwner().getUUID())) From 6de6b899c6712978a098d6bbe5fc5117cbfe931c Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sat, 15 Nov 2025 01:09:35 +0100 Subject: [PATCH 160/175] fix(build): simplify version string by removing branch name --- build.gradle.kts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 75856788..6013616a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -63,10 +63,7 @@ val versionDetails: groovy.lang.Closure Date: Sat, 15 Nov 2025 22:54:40 +0100 Subject: [PATCH 161/175] refactor(review): streamline menu opening and enhance plot retrieval logic --- .../commands/review/CMD_Review.java | 7 --- .../plotsystem/core/menus/PlotMemberMenu.java | 12 ++++- .../core/system/plot/utils/PlotUtils.java | 53 +++++++++++++++---- 3 files changed, 52 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 075f59a2..ac8b9ec0 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -112,13 +112,6 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { PlotSystem.getPlugin().getComponentLogger().info(text("Review: Teleported player, scheduling menu open in 20 ticks")); } - // Open menu after teleportation completes - Bukkit.getScheduler().runTaskLater(PlotSystem.getPlugin(), () -> { - if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { - PlotSystem.getPlugin().getComponentLogger().info(text("Review: Opening ReviewPlotMenu for plot " + finalPlotToReview.getId())); - } - new ReviewPlotMenu(player, finalPlotToReview); - }, 20L); }); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java index 9444e920..1fc54aff 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/PlotMemberMenu.java @@ -37,8 +37,15 @@ public class PlotMemberMenu extends AbstractMenu { private List builders; public PlotMemberMenu(@NotNull Plot plot, Player menuPlayer) { - super(3, LangUtil.getInstance().get(menuPlayer, LangPaths.MenuTitle.MANAGE_MEMBERS) + " | " + LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getId(), menuPlayer); + // Avoid opening the menu before 'plot' is assigned + super(3, + LangUtil.getInstance().get(menuPlayer, LangPaths.MenuTitle.MANAGE_MEMBERS) + " | " + + LangUtil.getInstance().get(menuPlayer, LangPaths.Plot.PLOT_NAME) + " #" + plot.getId(), + menuPlayer, + false); this.plot = plot; + // Now that 'plot' is set, we can safely load the menu + reloadMenuAsync(); } @Override @@ -154,4 +161,5 @@ protected Mask getMask() { .pattern("111101111") .build(); } -} \ No newline at end of file +} + diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 7b9bb14e..d0d2b5b0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -95,23 +95,47 @@ private PlotUtils() {} */ @Nullable public static AbstractPlot getCurrentPlot(@NotNull Builder builder, Status... statuses) { + boolean dev = PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE); + if (dev) { + PlotSystem.getPlugin().getComponentLogger().info(text( + "getCurrentPlot: enter | player=" + (builder.isOnline() ? builder.getPlayer().getName() : builder.getUUID()) + + ", statuses=" + (statuses == null ? "null" : java.util.Arrays.toString(statuses)) + )); + } + if (builder.isOnline()) { String worldName = builder.getPlayer().getWorld().getName(); + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: worldName=" + worldName)); if (PlotWorld.isOnePlotWorld(worldName)) { - int id = Integer.parseInt(worldName.substring(2)); - AbstractPlot plot = worldName.toLowerCase(Locale.ROOT).startsWith("p-") - ? DataProvider.PLOT.getPlotById(id) - : DataProvider.TUTORIAL_PLOT.getById(id).orElseThrow(); - if (statuses == null) return plot; - for (Status status : statuses) if (status == plot.getStatus()) return plot; - return null; + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: detected OnePlotWorld")); + try { + int id = Integer.parseInt(worldName.substring(2)); + AbstractPlot plot = worldName.toLowerCase(Locale.ROOT).startsWith("p-") + ? DataProvider.PLOT.getPlotById(id) + : DataProvider.TUTORIAL_PLOT.getById(id).orElse(null); + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: one-plot id=" + id + ", resolved=" + (plot == null ? "null" : (plot.getClass().getSimpleName() + "#" + plot.getId() + " status=" + plot.getStatus())))); + + if (plot == null) return null; + if (statuses == null || statuses.length == 0) return plot; + for (Status status : statuses) if (status == plot.getStatus()) return plot; + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: status filter did not match for plot #" + plot.getId())); + return null; + } catch (NumberFormatException ex) { + if (dev) PlotSystem.getPlugin().getComponentLogger().warn(text("getCurrentPlot: failed to parse plot id from worldName=" + worldName), ex); + return null; + } } else if (PlotWorld.isCityPlotWorld(worldName)) { + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: detected CityPlotWorld")); String cityID = worldName.substring(2); Optional city = DataProvider.CITY_PROJECT.getById(cityID); - if (city.isEmpty()) return null; + if (city.isEmpty()) { + if (dev) PlotSystem.getPlugin().getComponentLogger().warn(text("getCurrentPlot: city not found for id=" + cityID)); + return null; + } List plots = DataProvider.PLOT.getPlots(city.get(), statuses); + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: candidate plots in city=" + city.get().getName(builder.isOnline() ? builder.getPlayer() : null) + ", count=" + plots.size())); if (plots.isEmpty()) return null; if (plots.size() == 1) return plots.getFirst(); @@ -119,19 +143,26 @@ public static AbstractPlot getCurrentPlot(@NotNull Builder builder, Status... st Location playerLoc = builder.getPlayer().getLocation().clone(); Vector3 playerVector = Vector3.at(playerLoc.getX(), playerLoc.getY(), playerLoc.getZ()); - double distance = 100000000; + double distance = Double.MAX_VALUE; Plot chosenPlot = plots.getFirst(); for (Plot plot : plots) { if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE) continue; BlockVector3 plotCenter = plot.getCenter(); - if (plotCenter.withY((int) playerVector.y()).distance(playerVector.toBlockPoint()) < distance) { - distance = plotCenter.distance(playerVector.toBlockPoint()); + double currentDistance = plotCenter.withY((int) playerVector.y()).distance(playerVector.toBlockPoint()); + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: candidate #" + plot.getId() + " center=" + plotCenter + " distance=" + currentDistance)); + if (currentDistance < distance) { + distance = currentDistance; chosenPlot = plot; } } + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: chosen plot id=" + chosenPlot.getId() + ", distance=" + distance)); return chosenPlot; + } else { + if (dev) PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: world is not a plot world")); } + } else if (dev) { + PlotSystem.getPlugin().getComponentLogger().info(text("getCurrentPlot: builder is offline")); } return null; } From 4f3b13061978c13c4b169e31f0098260029bbe21 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 17 Nov 2025 18:23:19 +0100 Subject: [PATCH 162/175] fix(plot): adjust paste position calculation for clipboard origin --- .../core/system/plot/generator/AbstractPlotGenerator.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index 6b168e97..b8268362 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -285,12 +285,16 @@ public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile clipboard = reader.read(); } + BlockVector3 clipboardOrigin = clipboard.getOrigin(); + if (clipboardOrigin == null) clipboardOrigin = clipboard.getMinimumPoint(); + int pasteY = world.getPlotHeight() - clipboard.getMinimumPoint().y() + clipboardOrigin.y(); + // paste schematic try (EditSession editSession = WorldEdit.getInstance().newEditSession(BukkitAdapter.adapt(world.getBukkitWorld()))) { if (pasteMask != null) editSession.setMask(pasteMask); Operation clipboardHolder = new ClipboardHolder(clipboard) .createPaste(editSession) - .to(BlockVector3.at(world.getPlot().getCenter().x(), world.getPlotHeight(), world.getPlot().getCenter().z())) + .to(BlockVector3.at(world.getPlot().getCenter().x(), pasteY, world.getPlot().getCenter().z())) .build(); Operations.complete(clipboardHolder); } From 07584d6c68d53f076e1f728c4f94316933322c60 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 20 Nov 2025 23:22:41 +0100 Subject: [PATCH 163/175] fix(plot): add offset parameter to pasteSchematic for improved pasting control --- .../plot/generator/AbstractPlotGenerator.java | 17 +++++++++++------ .../plot/generator/DefaultPlotGenerator.java | 2 +- .../core/system/plot/utils/PlotUtils.java | 9 +++++++-- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java index b8268362..5b4ec0cd 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/AbstractPlotGenerator.java @@ -132,10 +132,10 @@ private AbstractPlotGenerator(@NotNull AbstractPlot plot, @NotNull Builder build */ protected void generateOutlines() throws IOException { if (plotVersion >= 3 && plotType.hasEnvironment()) { - pasteSchematic(null, plot.getInitialSchematicBytes(), world, false); + pasteSchematic(null, plot.getInitialSchematicBytes(), world, false, false); } else { Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); - pasteSchematic(airMask, PlotUtils.getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true); + pasteSchematic(airMask, PlotUtils.getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true, false); } } @@ -263,8 +263,9 @@ public Builder getBuilder() { * @param schematicFile - plot/environment schematic file * @param world - world to paste in * @param clearArea - clears the plot area with air before pasting + * @param offset - offset for the paste operation */ - public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, @NotNull PlotWorld world, boolean clearArea) throws IOException { + public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile, @NotNull PlotWorld world, boolean clearArea, boolean offset) throws IOException { // load world if (!world.loadWorld()) return; World weWorld = new BukkitWorld(world.getBukkitWorld()); @@ -285,9 +286,13 @@ public static void pasteSchematic(@Nullable Mask pasteMask, byte[] schematicFile clipboard = reader.read(); } - BlockVector3 clipboardOrigin = clipboard.getOrigin(); - if (clipboardOrigin == null) clipboardOrigin = clipboard.getMinimumPoint(); - int pasteY = world.getPlotHeight() - clipboard.getMinimumPoint().y() + clipboardOrigin.y(); + int pasteY = world.getPlotHeight(); + + if (offset) { + BlockVector3 clipboardOrigin = clipboard.getOrigin(); + if (clipboardOrigin == null) clipboardOrigin = clipboard.getMinimumPoint(); + pasteY = world.getPlotHeight() - clipboard.getMinimumPoint().y() + clipboardOrigin.y(); + } // paste schematic try (EditSession editSession = WorldEdit.getInstance().newEditSession(BukkitAdapter.adapt(world.getBukkitWorld()))) { diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java index 0a0455e8..617777f9 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/generator/DefaultPlotGenerator.java @@ -75,7 +75,7 @@ protected void generateOutlines() throws IOException, WorldEditException { if (completedSchematic != null) { PlotSystem.getPlugin().getComponentLogger().info("Found completed schematic, pasting only that."); Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(world.getBukkitWorld()), BlockTypes.AIR); - pasteSchematic(airMask, completedSchematic, world, false); + pasteSchematic(airMask, completedSchematic, world, false, true); } else super.generateOutlines(); } else super.generateOutlines(); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index d0d2b5b0..9588b148 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -30,6 +30,8 @@ import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.extent.clipboard.io.ClipboardWriter; +import com.sk89q.worldedit.function.mask.BlockTypeMask; +import com.sk89q.worldedit.function.mask.Mask; import com.sk89q.worldedit.function.operation.ForwardExtentCopy; import com.sk89q.worldedit.function.operation.Operations; import com.sk89q.worldedit.math.BlockVector2; @@ -38,6 +40,7 @@ import com.sk89q.worldedit.math.transform.AffineTransform; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Polygonal2DRegion; +import com.sk89q.worldedit.world.block.BlockTypes; import com.sk89q.worldguard.WorldGuard; import com.sk89q.worldguard.protection.managers.RegionManager; import com.sk89q.worldguard.protection.regions.ProtectedRegion; @@ -278,7 +281,9 @@ public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException // If plot was created in a void world, copy the result to the city world if (plot.getPlotType() != PlotType.CITY_INSPIRATION_MODE) { - AbstractPlotGenerator.pasteSchematic(null, outputStream.toByteArray(), new CityPlotWorld(plot), false); + var cpw = new CityPlotWorld(plot); + Mask airMask = new BlockTypeMask(BukkitAdapter.adapt(cpw.getBukkitWorld()), BlockTypes.AIR); + AbstractPlotGenerator.pasteSchematic(airMask, outputStream.toByteArray(), cpw, false, true); } return true; } @@ -419,7 +424,7 @@ public static boolean abandonPlot(@NotNull AbstractPlot plot) { if (regionManager.hasRegion(world.getRegionName())) regionManager.removeRegion(world.getRegionName()); if (regionManager.hasRegion(world.getRegionName() + "-1")) regionManager.removeRegion(world.getRegionName() + "-1"); - AbstractPlotGenerator.pasteSchematic(null, getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true); + AbstractPlotGenerator.pasteSchematic(null, getOutlinesSchematicBytes(plot, world.getBukkitWorld()), world, true, false); } else PlotSystem.getPlugin().getComponentLogger().warn(text("Region Manager is null!")); playersToTeleport.forEach(p -> p.teleport(Utils.getSpawnLocation())); From 2fea26c25d1c8d2a113535fdd15e080f3e8ad988 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Sat, 6 Dec 2025 22:55:23 +0100 Subject: [PATCH 164/175] fix(plot): add CMD_Plot_Members registration under group support --- .../java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java index 35e22b73..37935dbc 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot.java @@ -15,10 +15,12 @@ public CMD_Plot() { registerSubCommand(new CMD_Plot_Links(this)); registerSubCommand(new CMD_Plot_Submit(this)); registerSubCommand(new CMD_Plot_Abandon(this)); - if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) registerSubCommand(new CMD_Plot_Invite(this)); + if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.ENABLE_GROUP_SUPPORT)) { + registerSubCommand(new CMD_Plot_Invite(this)); + registerSubCommand(new CMD_Plot_Members(this)); + } registerSubCommand(new CMD_Plot_Feedback(this)); registerSubCommand(new CMD_Plot_UndoSubmit(this)); - registerSubCommand(new CMD_Plot_Members(this)); } @Override From 53b3dca0e03d364fdc2500faa3a1b076fdedc055 Mon Sep 17 00:00:00 2001 From: cinnazeyy Date: Mon, 15 Dec 2025 18:33:23 +0100 Subject: [PATCH 165/175] add check for errors in console info message to all error messages. Use variables for commonly used args lookups --- .../admin/setup/CMD_Setup_BuildTeam.java | 12 ++++++------ .../commands/admin/setup/CMD_Setup_City.java | 15 ++++++++------- .../commands/admin/setup/CMD_Setup_Country.java | 8 ++++---- .../admin/setup/CMD_Setup_Difficulty.java | 4 ++-- .../admin/setup/CMD_Setup_ReviewCriteria.java | 17 +++++++++-------- .../commands/admin/setup/CMD_Setup_Server.java | 13 +++++++------ 6 files changed, 36 insertions(+), 33 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java index 751ea02f..d80acb73 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_BuildTeam.java @@ -129,7 +129,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = DataProvider.BUILD_TEAM.addBuildTeam(name); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added build team with name '" + name + "'!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -228,7 +228,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = buildTeam.get().setName(name); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed name of build team with ID " + args[1] + " to '" + name + "'!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -278,7 +278,7 @@ public void onCommand(CommandSender sender, String[] args) { } boolean successful = buildTeam.get().addReviewer(builder); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added '" + builder.getName() + "' as reviewer to build team with ID " + buildTeam.get().getName() + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -330,7 +330,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = buildTeam.get().removeReviewer(builder.getUUID().toString()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed '" + builder.getName() + "' as reviewer from build team with ID " + args[1] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -430,7 +430,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = DataProvider.REVIEW.assignBuildTeamToggleCriteria(buildTeam.get().getId(), criteria.get()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully assigned criteria '" + criteria.get().criteriaName() + "' to build team with ID '" + args[1] + "'!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -483,7 +483,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = DataProvider.REVIEW.removeBuildTeamToggleCriteria(buildTeam.get().getId(), criteria.get()); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed criteria '" + criteria.get().criteriaName() + "' from build team with ID '" + args[1] + "'!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java index f6893ff9..34e6b5b1 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_City.java @@ -150,7 +150,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean added = DataProvider.CITY_PROJECT.add(cityProjectId, buildTeamId, country.get().getCode(), serverName); if (!added) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while adding City Project! Check console for any exceptions.")); return; } sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added City Project with Name '" + cityProjectId + "' under country with the code " + countryCode + "!")); @@ -198,7 +198,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean removed = DataProvider.CITY_PROJECT.remove(cityProjectId); if (removed) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed City Project with ID " + cityProjectId + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while removing city project!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while removing city project! Check console for any exceptions.")); } @Override @@ -249,7 +249,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = cityProject.get().setServer(serverName); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed server of City Project with ID " + args[1] + " to '" + serverName + "'!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project server!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project server! Check console for any exceptions.")); } @Override @@ -293,7 +293,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = cityProject.get().setBuildTeam(buildTeamId); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set Build Team of City Project with ID " + args[1] + " to " + buildTeamId + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project build team!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project build team! Check console for any exceptions.")); } @Override @@ -325,17 +325,18 @@ public CMD_Setup_City_SetVisible(BaseCommand baseCommand, SubCommand subCommand) @Override public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2) {sendInfo(sender); return;} + String id = args[1]; // Check if City Project exits - Optional cityProject = DataProvider.CITY_PROJECT.getById(args[1]); + Optional cityProject = DataProvider.CITY_PROJECT.getById(id); if (cityProject.isEmpty()) return; if (!args[2].equalsIgnoreCase("true") && !args[2].equalsIgnoreCase("false")) return; boolean isVisible = args[2].equalsIgnoreCase("true"); boolean successful = cityProject.get().setVisible(isVisible); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set visibility of City Project with ID " + args[1] + " to " + args[2].toUpperCase() + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project visibility!")); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set visibility of City Project with ID " + id + " to " + args[2].toUpperCase() + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while updating city project visibility! Check console for any exceptions.")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java index f9bcfe22..bd23d125 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Country.java @@ -176,7 +176,7 @@ public void onCommand(CommandSender sender, String[] args) { } boolean successful = DataProvider.COUNTRY.removeCountry(code); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed country!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -219,14 +219,14 @@ public void onCommand(CommandSender sender, String[] args) { // Check if country exists Optional country = DataProvider.COUNTRY.getCountryByCode(code); if (country.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with name " + args[1] + "!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any country with code " + code + "!")); sendInfo(sender); return; } boolean successful = country.get().setMaterialAndModelData(material, customModelData); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully updated country with code " + country + "! Material: " + material + " CustomModelData: " + (customModelData == null ? "NULL" : customModelData))); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully updated country with code " + code + "! Material: " + material + " CustomModelData: " + (customModelData == null ? "NULL" : customModelData))); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java index 599e40c5..a040cd3a 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Difficulty.java @@ -112,7 +112,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = difficulty.get().setMultiplier(Double.parseDouble(args[2])); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set multiplier of Difficulty with ID " + args[1] + " to " + args[2] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -154,7 +154,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = difficulty.get().setScoreRequirement(Integer.parseInt(args[2])); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully set score requirement of Difficulty with ID " + args[1] + " to " + args[2] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java index e8054840..ef05a1f0 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_ReviewCriteria.java @@ -149,18 +149,19 @@ public CMD_Setup_ReviewCriteria_Remove(BaseCommand baseCommand, SubCommand subCo @Override public void onCommand(CommandSender sender, String[] args) { if (args.length <= 1) {sendInfo(sender); return;} + String name = args[1]; // Check if criteria exists - Optional criteria = DataProvider.REVIEW.getToggleCriteria(args[1]); + Optional criteria = DataProvider.REVIEW.getToggleCriteria(name); if (criteria.isEmpty()) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any toggle criteria with name " + args[1] + "!")); + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any toggle criteria with name " + name + "!")); sendInfo(sender); return; } boolean successful = DataProvider.REVIEW.removeToggleCriteria(criteria.get().criteriaName()); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed build team with ID " + args[1] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed toggle criteria with name " + name + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -192,20 +193,21 @@ public CMD_Setup_ReviewCriteria_SetOptional(BaseCommand baseCommand, SubCommand @Override public void onCommand(CommandSender sender, String[] args) { if (args.length <= 2) {sendInfo(sender); return;} + String name = args[1]; // Check if criteria exits - Optional criteria = DataProvider.REVIEW.getToggleCriteria(args[1]); + Optional criteria = DataProvider.REVIEW.getToggleCriteria(name); if (criteria.isEmpty()) { sender.sendMessage(Utils.ChatUtils.getAlertFormat("Toggle criteria could not be found!")); return; } - String name = args[1]; + boolean isOptional = args[2].equalsIgnoreCase("true"); boolean successful = DataProvider.REVIEW.setToggleCriteriaOptional(name, isOptional); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully changed optionality of toggle criteria with name " + name + " to '" + isOptional + "'!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -228,5 +230,4 @@ public String getPermission() { return "plotsystem.admin.pss.buildteam.setoptional"; } } - } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index cded4398..f8082113 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -118,7 +118,7 @@ public void onCommand(CommandSender sender, String[] args) { boolean successful = DataProvider.SERVER.addServer(serverName, buildTeamId); if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully added server!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override @@ -150,17 +150,18 @@ public CMD_Setup_Server_Remove(BaseCommand baseCommand, SubCommand subCommand) { @Override public void onCommand(CommandSender sender, String[] args) { if (args.length <= 1) {sendInfo(sender); return;} + String name = args[1]; // Check if server exists - if (!DataProvider.SERVER.serverExists(args[1])) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with ID " + args[1] + "!")); + if (!DataProvider.SERVER.serverExists(name)) { + sender.sendMessage(Utils.ChatUtils.getAlertFormat("Could not find any server with name " + name + "!")); sendInfo(sender); return; } - boolean successful = DataProvider.SERVER.removeServer(args[1]); - if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed server with ID " + args[1] + "!")); - else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command!")); + boolean successful = DataProvider.SERVER.removeServer(name); + if (successful) sender.sendMessage(Utils.ChatUtils.getInfoFormat("Successfully removed server with name " + name + "!")); + else sender.sendMessage(Utils.ChatUtils.getAlertFormat("An error occurred while executing command! Check console for any exceptions.")); } @Override From 5138ca882eccdf86cac8cfbfaff4a911c19920d9 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 15 Dec 2025 18:34:06 +0100 Subject: [PATCH 166/175] fix(commands): improve argument validation and error messaging for plot commands --- .../plotsystem/commands/admin/CMD_DeletePlot.java | 9 +++++++-- .../plotsystem/commands/review/CMD_EditFeedback.java | 11 +++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java index 72d6539b..35775b98 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_DeletePlot.java @@ -22,12 +22,17 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - if (!(args.length > 0 && AlpsUtils.tryParseInt(args[0]) != null)) { + if (args.length == 0) { sendInfo(sender); return true; } - int plotID = Integer.parseInt(args[0]); + Integer plotID = AlpsUtils.tryParseInt(args[0]); + + if (plotID == null) { + sendInfo(sender); + return true; + } CompletableFuture.runAsync(() -> { Plot plot = DataProvider.PLOT.getPlotById(plotID); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java index de7cca6b..d9081916 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditFeedback.java @@ -38,12 +38,19 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return; } - if (args.length < 1 || AlpsUtils.tryParseInt(args[0]) == null) { + if (args.length < 1) { sendInfo(sender); return; } - Plot plot = DataProvider.PLOT.getPlotById(Integer.parseInt(args[0])); + Integer plotId = AlpsUtils.tryParseInt(args[0]); + + if (plotId == null) { + sendInfo(sender); + return; + } + + Plot plot = DataProvider.PLOT.getPlotById(plotId); if (plot.getVersion() <= AbstractPlot.LEGACY_VERSION_THRESHOLD) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.CANNOT_MODIFY_LEGACY_PLOT))); From 577da57b61bb9f5d9fabb793854c0d6d8bf88506 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 15 Dec 2025 18:39:42 +0100 Subject: [PATCH 167/175] fix(review): add unfinished plots check in review menu for remaining days line --- .../plotsystem/core/menus/review/ReviewMenu.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java index abde5b05..b16691d3 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/review/ReviewMenu.java @@ -84,10 +84,13 @@ protected void setPaginatedMenuItemsAsync(List source) { lines.add("§7" + LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Plot.DIFFICULTY) + ": §f" + plot.getDifficulty().name().charAt(0) + plot.getDifficulty().name().substring(1).toLowerCase()); lines.add(""); - long inactivityIntervalDays = PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.INACTIVITY_INTERVAL); - long rejectedInactivityIntervalDays = (PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) != -1) ? PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) : inactivityIntervalDays; - long interval = plot.isRejected() ? rejectedInactivityIntervalDays : inactivityIntervalDays; - if (interval > -1) lines.add(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ABANDONED_IN_DAYS, String.valueOf(DAYS.between(LocalDate.now(), plot.getLastActivity().plusDays(interval))))); + if (plot.getStatus() == Status.unfinished) { + long inactivityIntervalDays = PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.INACTIVITY_INTERVAL); + long rejectedInactivityIntervalDays = (PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) != -1) ? PlotSystem.getPlugin().getConfig().getLong(ConfigPaths.REJECTED_INACTIVITY_INTERVAL) : inactivityIntervalDays; + long interval = plot.isRejected() ? rejectedInactivityIntervalDays : inactivityIntervalDays; + if (interval > -1) lines.add(LangUtil.getInstance().get(getMenuPlayer(), LangPaths.Review.ABANDONED_IN_DAYS, String.valueOf(DAYS.between(LocalDate.now(), plot.getLastActivity().plusDays(interval))))); + + } getMenu().getSlot(i + 9).setItem(new ItemBuilder(plot.getStatus() == Status.unfinished ? Material.MAP : Material.FILLED_MAP, 1) .setName("§b§l" + LangUtil.getInstance().get(getMenuPlayer(), plot.getStatus() == Status.unfinished ? LangPaths.Review.MANAGE_PLOT : LangPaths.Review.REVIEW_PLOT)) From 55389e524f83fbb22edc69a213b846df9bfe56e0 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 15 Dec 2025 20:32:30 +0100 Subject: [PATCH 168/175] fix(review): update ReviewPlotMenu logic to check plot status before opening --- .../alpsbte/plotsystem/commands/review/CMD_Review.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index ac8b9ec0..2de04f5f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -119,9 +119,13 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N // Player is already on the plot, open menu on main thread Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { if (PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE)) { - PlotSystem.getPlugin().getComponentLogger().info(text("Review: Opening ReviewPlotMenu for plot " + finalPlotToReview.getId() + " (no teleport needed)")); + PlotSystem.getPlugin().getComponentLogger().info(text("Review: Opening ReviewPlotMenu for plot if status is unreviewed" + finalPlotToReview.getId() + " (no teleport needed)")); + } + if (finalPlotToReview.getStatus() == Status.unreviewed) { + new ReviewPlotMenu(player, finalPlotToReview); + } else { + new ReviewMenu(player); } - new ReviewPlotMenu(player, finalPlotToReview); }); }); return true; From 57b021ee5778fb12b69d339e76a91aac476bb478 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 15 Dec 2025 21:20:10 +0100 Subject: [PATCH 169/175] fix(review): correct participant check to use equals for UUID comparison --- .../java/com/alpsbte/plotsystem/commands/review/CMD_Review.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 2de04f5f..01b234db 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -77,7 +77,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } // Players cannot review their own plots - boolean isParticipant = plotToReview.getPlotOwner().getUUID() == player.getUniqueId() || plotToReview.getPlotMembers().stream().anyMatch(b -> b.getUUID() == player.getUniqueId()); + boolean isParticipant = plotToReview.getPlotOwner().getUUID().equals(player.getUniqueId()) || plotToReview.getPlotMembers().stream().anyMatch(b -> b.getUUID().equals(player.getUniqueId())); if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.DEV_MODE) && isParticipant) { player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(player, LangPaths.Message.Error.CANNOT_REVIEW_OWN_PLOT))); return; From 5418ae26b2db4ec843bce3fff50f53b2115ccc7c Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 12 Jan 2026 20:08:00 +0100 Subject: [PATCH 170/175] fix(commands): add config-based enable/disable logic for CMD_EditPlot and improve command error messaging --- .../plotsystem/commands/CMD_Companion.java | 8 +++++++- .../alpsbte/plotsystem/commands/CMD_Plots.java | 15 ++++++--------- .../com/alpsbte/plotsystem/commands/CMD_Tpll.java | 12 ++++-------- .../alpsbte/plotsystem/commands/CMD_Tutorial.java | 3 +-- .../plotsystem/commands/CommandManager.java | 6 +++++- .../commands/admin/CMD_SetLeaderboard.java | 3 +-- .../commands/admin/setup/CMD_Setup_Server.java | 6 +++--- .../commands/plot/CMD_Plot_Teleport.java | 2 +- .../plotsystem/commands/review/CMD_EditPlot.java | 10 +--------- .../plotsystem/commands/review/CMD_Review.java | 4 ++-- .../commands/review/CMD_UndoReview.java | 3 +-- .../core/menus/companion/CompanionMenu.java | 6 +++--- .../alpsbte/plotsystem/utils/io/LangPaths.java | 1 - src/main/resources/commands.yml | 2 +- src/main/resources/lang/de_DE.yml | 1 - src/main/resources/lang/en_GB.yml | 1 - src/main/resources/lang/fr_FR.yml | 1 - src/main/resources/lang/he_IL.yml | 1 - src/main/resources/lang/ko_KR.yml | 1 - src/main/resources/lang/pt_PT.yml | 1 - src/main/resources/lang/ru_RU.yml | 1 - src/main/resources/lang/zh_CN.yml | 1 - src/main/resources/lang/zh_TW.yml | 1 - 23 files changed, 36 insertions(+), 54 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java index 006d06a7..2e8d7d6b 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Companion.java @@ -10,6 +10,8 @@ import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -24,7 +26,11 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } Player player = getPlayer(sender); - if (player == null) return true; + + if (player == null) { + sender.sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + return true; + } Tutorial tutorial = AbstractTutorial.getActiveTutorial(player.getUniqueId()); if (tutorial != null) { diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java index 4d895582..b63792ec 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Plots.java @@ -21,7 +21,7 @@ public class CMD_Plots extends BaseCommand { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { Player player = getPlayer(sender); if (player == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + sender.sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return true; } @@ -39,14 +39,11 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N CompletableFuture.runAsync(() -> { Builder builder = Builder.byName(args[0]); - Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> { - if (builder == null) { - player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); - return; - } - - new PlayerPlotsMenu(player, builder); - }); + if (builder == null) { + player.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.PLAYER_NOT_FOUND))); + return; + } + Bukkit.getScheduler().runTask(PlotSystem.getPlugin(), () -> new PlayerPlotsMenu(player, builder)); }); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java index de91f1e7..64763773 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tpll.java @@ -19,6 +19,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; import java.io.IOException; import java.math.RoundingMode; @@ -117,15 +118,10 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } - private static int getHighestY(World playerWorld, double[] plotCoordinates) { - int highestY = 0; + private static int getHighestY(World playerWorld, double @NonNull [] plotCoordinates) { Location block = new Location(playerWorld, plotCoordinates[0], 0, plotCoordinates[1]); - for (int i = 1; i < 256; i++) { - block.add(0, 1, 0); - if (!block.getBlock().isEmpty()) { - highestY = i; - } - } + int highestY = playerWorld.getHighestBlockYAt(block); + if (highestY < PlotWorld.MIN_WORLD_HEIGHT) { highestY = PlotWorld.MIN_WORLD_HEIGHT; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java index 595ce97b..4801a001 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CMD_Tutorial.java @@ -14,7 +14,6 @@ import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.jetbrains.annotations.NotNull; @@ -28,7 +27,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N return true; } if (getPlayer(sender) == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + sender.sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return true; } if (!PlotSystem.getPlugin().getConfig().getBoolean(ConfigPaths.TUTORIAL_ENABLE)) { diff --git a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java index 95b4634f..3ceb9465 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/CommandManager.java @@ -10,6 +10,8 @@ import com.alpsbte.plotsystem.commands.review.CMD_EditPlot; import com.alpsbte.plotsystem.commands.review.CMD_Review; import com.alpsbte.plotsystem.commands.review.CMD_UndoReview; +import com.alpsbte.plotsystem.utils.io.ConfigPaths; +import com.alpsbte.plotsystem.utils.io.ConfigUtil; import java.util.ArrayList; import java.util.List; @@ -32,7 +34,9 @@ public CommandManager() { baseCommands.add(new CMD_Review()); baseCommands.add(new CMD_UndoReview()); baseCommands.add(new CMD_EditFeedback()); - baseCommands.add(new CMD_EditPlot()); + if (ConfigUtil.getInstance().configs[1].getBoolean(ConfigPaths.EDITPLOT_ENABLED)) { + baseCommands.add(new CMD_EditPlot()); + } // Admin Commands baseCommands.add(new CMD_DeletePlot()); diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java index f2d18813..d67122a4 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/CMD_SetLeaderboard.java @@ -7,7 +7,6 @@ import com.alpsbte.plotsystem.utils.Utils; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; -import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -23,7 +22,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @N } if (getPlayer(sender) == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + sender.sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java index f8082113..4fc79bd8 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/admin/setup/CMD_Setup_Server.java @@ -65,12 +65,12 @@ public void onCommand(CommandSender sender, String[] args) { return; } - sender.sendMessage(Utils.ChatUtils.getInfoFormat("There are currently " + servers.size() + " Servers registered in the database:")); + var msg = Utils.ChatUtils.getInfoFormat("There are currently " + servers.size() + " Servers registered in the database:").appendNewline(); for (String server : servers) { - sender.sendMessage(text(" » ", DARK_GRAY).append(text(server, AQUA))); + msg = msg.append(text(" » ", DARK_GRAY).append(text(server, AQUA))).appendNewline(); } - sender.sendMessage(text("--------------------------", DARK_GRAY)); + sender.sendMessage(msg.append(text("--------------------------", DARK_GRAY))); } @Override diff --git a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java index b4c9033b..4f4b1883 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/plot/CMD_Plot_Teleport.java @@ -32,7 +32,7 @@ public CMD_Plot_Teleport(BaseCommand baseCommand) { public void onCommand(CommandSender sender, String[] args) { Player player = getPlayer(sender); if (player == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); + sender.sendMessage(Component.text("This command can only be used as a player!", NamedTextColor.RED)); return; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java index 595904d1..8a4fe938 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_EditPlot.java @@ -10,8 +10,6 @@ import com.alpsbte.plotsystem.core.system.plot.utils.PlotUtils; import com.alpsbte.plotsystem.utils.Utils; import com.alpsbte.plotsystem.utils.enums.Status; -import com.alpsbte.plotsystem.utils.io.ConfigPaths; -import com.alpsbte.plotsystem.utils.io.ConfigUtil; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.Component; @@ -31,13 +29,7 @@ public class CMD_EditPlot extends BaseCommand { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { Player player = getPlayer(sender); if (player == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); - return true; - } - - // TODO: don't register command if this config value is false - if (!ConfigUtil.getInstance().configs[1].getBoolean(ConfigPaths.EDITPLOT_ENABLED)) { - sender.sendMessage(Utils.ChatUtils.getAlertFormat(LangUtil.getInstance().get(sender, LangPaths.Message.Error.COMMAND_DISABLED))); + sender.sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index 01b234db..d585cee0 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -32,7 +32,7 @@ public class CMD_Review extends BaseCommand { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { Player player = getPlayer(sender); if (player == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); + sender.sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } @@ -148,6 +148,6 @@ public String[] getParameter() { @Override public String getPermission() { - return ""; + return "plotsystem.review"; } } diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java index f0c47b01..1f910433 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_UndoReview.java @@ -14,7 +14,6 @@ import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; import net.kyori.adventure.text.Component; -import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -30,7 +29,7 @@ public class CMD_UndoReview extends BaseCommand { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { Player player = getPlayer(sender); if (player == null) { - Bukkit.getConsoleSender().sendMessage(Component.text("This command can only be used as a player!", RED)); + sender.sendMessage(Component.text("This command can only be used as a player!", RED)); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java index 72d40fa5..c49f64a0 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java +++ b/src/main/java/com/alpsbte/plotsystem/core/menus/companion/CompanionMenu.java @@ -46,7 +46,6 @@ public class CompanionMenu { private CompanionMenu() {throw new IllegalStateException("Utility class");} public static boolean hasContinentView() { - // TODO: make this run async return Arrays.stream(Continent.values()).map(continent -> DataProvider.COUNTRY.getCountriesByContinent(continent).size()).filter(count -> count > 0).count() > 1; } @@ -59,7 +58,6 @@ public static void open(Player player) { if (hasContinentView()) { new ContinentMenu(player); } else { - // TODO: make this run async Optional continent = Arrays.stream(Continent.values()).filter(c -> !DataProvider.COUNTRY.getCountriesByContinent(c).isEmpty()).findFirst(); if (continent.isEmpty()) { @@ -128,7 +126,9 @@ public static ItemStack getDifficultyItem(Player player, PlotDifficulty selected default: break; } - } else item = BaseItems.DIFFICULTY_AUTOMATIC.getItem(); + } + + if (item == null) item = BaseItems.DIFFICULTY_AUTOMATIC.getItem(); Optional difficulty = DataProvider.DIFFICULTY.getDifficultyByEnum(selectedPlotDifficulty); if (difficulty.isEmpty() && selectedPlotDifficulty != null) { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java index fc27cd52..fbf11a5d 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/LangPaths.java @@ -305,7 +305,6 @@ private Error() {} public static final String PLAYER_MISSING_TUTORIAL = MESSAGE_PREFIX + "player-missing-tutorial"; public static final String ERROR_OCCURRED = ERROR_PREFIX + "error-occurred"; - public static final String COMMAND_DISABLED = ERROR_PREFIX + "command-disabled"; public static final String NO_PLOTS_LEFT = ERROR_PREFIX + "no-plots-left"; public static final String PLEASE_WAIT = ERROR_PREFIX + "please-wait"; public static final String ALL_SLOTS_OCCUPIED = ERROR_PREFIX + "all-slots-occupied"; diff --git a/src/main/resources/commands.yml b/src/main/resources/commands.yml index 8f59bd11..ebe6a0a1 100644 --- a/src/main/resources/commands.yml +++ b/src/main/resources/commands.yml @@ -8,7 +8,7 @@ # Allow /editplot on plots for reviewers # NOTE: Reviewers will be able to modify plots -editplot-enabled: false +editplot-enabled: true # Blocked commands for plot owner and plot members on plots blocked-commands-builders: diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index 3bee8124..d71b51e0 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -278,7 +278,6 @@ message: player-needs-higher-score: "Du benötigst einen höheren Punktestand, um in diesem Schwierigkeitsgrad zu bauen." player-missing-tutorial: "Der Spieler muss zuerst das Tutorial abschließen, um hinzugefügt zu werden!" error-occurred: "Ein Fehler ist aufgetreten! Bitte versuche es erneut!" - command-disabled: "Dieser Befehl ist deaktiviert!" no-plots-left: "Für diese Stadt gibt es keine freien Plots mehr. Bitte wähle einen anderen Ort." please-wait: "Bitte warte ein paar Sekunden, bevor du einen weiteren neuen Plot erstellst!" all-slots-occupied: "Alle deine Slots sind belegt! Bitte stelle deine aktuellen Plots fertig, bevor du einen neuen erstellst." diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 7ace968f..93d9c3ae 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -278,7 +278,6 @@ message: player-needs-higher-score: "You need a higher score to build in this difficulty level." player-missing-tutorial: "The player must first complete the tutorial to be added to the plot!" error-occurred: "An error occurred! Please try again!" - command-disabled: "This command is disabled!" no-plots-left: "This city project does not have any more plots left. Please select another project." please-wait: "Please wait a few seconds before creating a new plot!" all-slots-occupied: "All your slots are occupied! Please finish your current plots before creating a new one." diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index 6f78c20b..cad03f6f 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -277,7 +277,6 @@ message: player-needs-higher-score: "Vous avez besoin d'un score plus élevé pour intégrer ce niveau de difficulté." player-missing-tutorial: "Le joueur doit d'abord terminer le tutoriel pour être intégré à l'intrigue!" error-occurred: "Une erreur s'est produite! Veuillez réessayer!" - command-disabled: "Cette commande est désactivée!" no-plots-left: "Ce projet de ville n'a plus de parcelles restantes. Veuillez sélectionner un autre projet." please-wait: "Veuillez patienter quelques secondes avant de créer un nouveau tracé!" all-slots-occupied: "Tous vos slots sont occupés! Veuillez terminer vos tracés actuels avant d'en créer un nouveau." diff --git a/src/main/resources/lang/he_IL.yml b/src/main/resources/lang/he_IL.yml index e36261d4..3f47d6af 100644 --- a/src/main/resources/lang/he_IL.yml +++ b/src/main/resources/lang/he_IL.yml @@ -262,7 +262,6 @@ message: player-needs-to-be-on-plot: "עליך להיות בפלוט כדי להשתמש בזה!" player-needs-higher-score: "אתה צריך ציון גבוה יותר כדי לבנות ברמת קושי זו." error-occurred: "אירעה שגיאה! אנא נסה שוב!" - command-disabled: "פקודה זו מושבתת!" no-plots-left: "אין עוד פלוטים פנויים בפרויקט העיר הזה. נא לבחור בפרויקט אחר." please-wait: "אנא המתן כמה שניות לפני יצירת פלוט חדש!" all-slots-occupied: "כל המקומות שלך תפוסים! סיים את הפלוטים הנוכחיים לפני יצירת חדשים." diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index fd271fe1..5882e5f0 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -277,7 +277,6 @@ message: player-needs-higher-score: "해당 난이도에서 건축하시려면 더 높은 점수가 필요합니다." player-missing-tutorial: "플레이어는 먼저 튜토리얼을 완료해야 플롯에 추가할 수 있습니다!" error-occurred: "에러 발생! 다시 시도해주세요!" - command-disabled: "비활성화된 커맨드입니다!" no-plots-left: "이 도시 프로젝트에 남아있는 플롯이 없습니다. 다른 프로젝트를 선택해주세요." please-wait: "새 플롯이 생성될 때까지 기다려주세요!" all-slots-occupied: "슬롯이 모두 꽉 찼습니다! 새 플롯을 생성하기 전에 현재 남아있는 플롯을 먼저 완성해주세요." diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index 4814dbbc..f02ae958 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -277,7 +277,6 @@ message: player-needs-higher-score: "Você precisa de uma pontuação mais alta para construir neste nível de dificuldade." player-missing-tutorial: "O jogador tem de completar o tutorial primeiro, para ser adicionado ao enredo!" error-occurred: "Um erro ocorreu! Por favor, tente novamente!" - command-disabled: "Este comando está desabilitado!" no-plots-left: "Este projeto da cidade não tem mais terrenos. Por favor, Selecione outro projeto." please-wait: "Aguarde alguns segundos antes de criar um novo terreno!" all-slots-occupied: "Todos os seus slots estão ocupados! Por favor, termine seus terrenos atuais antes de criar um novo." diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index 9b4c5616..1ef1a8ce 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -277,7 +277,6 @@ message: player-needs-higher-score: "Вам нужна более высокая оценка чтобы строить на этом уровне сложности." player-missing-tutorial: "Чтобы стать участником сюжета, игрок должен сначала пройти обучение!" error-occurred: "Произошла ошибка! Пожалуйста, попробуйте снова!" - command-disabled: "Эта команда отключена!!" no-plots-left: "У этого градостроительного проекта больше не осталось участков. Пожалуйста, выберите другой проект." please-wait: "Пожалуйста, подождите несколько секунд перед созданием нового участка!" all-slots-occupied: "Все ваши слоты заняты! Пожалуйста, завершите текущие участки, прежде чем создавать новый." diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index 202502a3..fd96714c 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -277,7 +277,6 @@ message: player-needs-higher-score: "你需要更高的积分来才能在这个难度度建设。" player-missing-tutorial: "玩家必須先完成教學才能加入劇情!" error-occurred: "发生错误!请再次尝试!" - command-disabled: "此命令已禁用!" no-plots-left: "此城市计画区没有剩余更多建地了。请选择其他计画区。" please-wait: "请稍后再创建一个新的建地!" all-slots-occupied: "你的所有槽位都被占用了!请在创建新的建地之前先完成您当前的建地。" diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index 96d37700..a0e4feb4 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -277,7 +277,6 @@ message: player-needs-higher-score: "你需要更高的積分來才能在這個難度下建設。" player-missing-tutorial: "玩家必须先完成教程,才能加入剧情!" error-occurred: "發生錯誤!請再次嘗試!" - command-disabled: "此指令已被禁用!" no-plots-left: "此城市計畫區沒有剩餘更多建地了。請選擇其他計畫區。" please-wait: "請稍後再建立一個新的建地!" all-slots-occupied: "你全部的槽位都被占用了!在建立新的建地前請先完成你當前的建地。" From 8086040df9dc3b17f9af1ca3164a09bf3ca64596 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Mon, 12 Jan 2026 20:29:30 +0100 Subject: [PATCH 171/175] fix(tutorial): add nullability annotations to player UUID and Player parameters make codacy happier --- .../plotsystem/commands/review/CMD_Review.java | 3 +-- .../core/system/tutorial/AbstractPlotTutorial.java | 11 ++++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java index d585cee0..7624061f 100644 --- a/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java +++ b/src/main/java/com/alpsbte/plotsystem/commands/review/CMD_Review.java @@ -15,7 +15,6 @@ import com.alpsbte.plotsystem.utils.io.ConfigPaths; import com.alpsbte.plotsystem.utils.io.LangPaths; import com.alpsbte.plotsystem.utils.io.LangUtil; -import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; @@ -32,7 +31,7 @@ public class CMD_Review extends BaseCommand { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String s, String[] args) { Player player = getPlayer(sender); if (player == null) { - sender.sendMessage(Component.text("This command can only be used as a player!", RED)); + sender.sendMessage(text("This command can only be used as a player!", RED)); return true; } diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index c6b6fcab..4548764e 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -21,6 +21,7 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -91,7 +92,7 @@ public void setStage(int stageId) { } @Override - public void onPlotSchematicPaste(UUID playerUUID, int schematicId) throws IOException { + public void onPlotSchematicPaste(@NotNull UUID playerUUID, int schematicId) throws IOException { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; if (plotGenerator != null && tutorialPlot.getWorld().isWorldGenerated() && tutorialPlot.getWorld().isWorldLoaded()) { plotGenerator.generateOutlines(schematicId); @@ -99,7 +100,7 @@ public void onPlotSchematicPaste(UUID playerUUID, int schematicId) throws IOExce } @Override - public void onPlotPermissionChange(UUID playerUUID, boolean isBuildingAllowed, boolean isWorldEditAllowed) { + public void onPlotPermissionChange(@NotNull UUID playerUUID, boolean isBuildingAllowed, boolean isWorldEditAllowed) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; if (plotGenerator != null) { plotGenerator.setBuildingEnabled(isBuildingAllowed); @@ -149,7 +150,7 @@ public void saveTutorial(int stageId) { } @Override - public void onSwitchWorld(UUID playerUUID, int tutorialWorldIndex) { + public void onSwitchWorld(@NotNull UUID playerUUID, int tutorialWorldIndex) { if (!getPlayerUUID().toString().equals(playerUUID.toString())) return; if (tutorialWorldIndex == 1 && (plotGenerator == null || !plotGenerator.getPlot().getWorld().isWorldGenerated())) { plotGenerator = new TutorialPlotGenerator(tutorialPlot, Builder.byUUID(playerUUID)); @@ -194,7 +195,7 @@ public void onException(Exception ex) { * @param player The player to send the message to. * @param title The title of the stage. */ - protected static void sendStageUnlockedMessage(Player player, String title) { + protected static void sendStageUnlockedMessage(@NotNull Player player, String title) { player.sendMessage(text()); player.sendMessage(text(LangUtil.getInstance().get(player, LangPaths.Tutorials.NEW_STAGE_UNLOCKED)).color(AQUA).decorate(BOLD)); player.sendMessage(text(" ◆ ", WHITE, BOLD).append(text(title).color(GOLD).decorate(BOLD))); @@ -208,7 +209,7 @@ protected static void sendStageUnlockedMessage(Player player, String title) { * @param tutorialName The name of the tutorial. * @see TutorialCategory */ - protected static void sendTutorialCompletedMessage(Player player, String tutorialName) { + protected static void sendTutorialCompletedMessage(@NotNull Player player, String tutorialName) { player.sendMessage(text()); player.sendMessage(text(LangUtil.getInstance().get(player, LangPaths.Tutorials.TUTORIAL_COMPLETED).toUpperCase()).color(AQUA).decorate(BOLD)); player.sendMessage(text(" ◆ ").color(WHITE).decorate(BOLD).append(text(tutorialName).color(GOLD))); From e9c6752a08bad2d3747c7462544f90896dd7b12c Mon Sep 17 00:00:00 2001 From: Zoriot Date: Wed, 14 Jan 2026 13:00:04 +0100 Subject: [PATCH 172/175] feat(translations): update language files from crowdin --- src/main/resources/lang/de_DE.yml | 63 +++++----- src/main/resources/lang/en_GB.yml | 2 +- src/main/resources/lang/fr_FR.yml | 2 +- src/main/resources/lang/he_IL.yml | 74 +++++++++-- src/main/resources/lang/ko_KR.yml | 2 +- src/main/resources/lang/pt_PT.yml | 8 +- src/main/resources/lang/ru_RU.yml | 198 +++++++++++++++--------------- src/main/resources/lang/zh_CN.yml | 2 +- src/main/resources/lang/zh_TW.yml | 60 ++++----- 9 files changed, 233 insertions(+), 178 deletions(-) diff --git a/src/main/resources/lang/de_DE.yml b/src/main/resources/lang/de_DE.yml index d71b51e0..b2062814 100644 --- a/src/main/resources/lang/de_DE.yml +++ b/src/main/resources/lang/de_DE.yml @@ -159,11 +159,11 @@ review: feedback: "Feedback" reviewer: "Reviewer" player-language: "Spielersprache" - no-feedback: "No feedback" - accuracy-points: "Accuracy points" - block-palette-points: "Block palette points" - toggle-points: "Toggle points" - total-points: "Total points" + no-feedback: "Kein Feedback" + accuracy-points: "Genauigkeit Punkte" + block-palette-points: "Block Palette Punkte" + toggle-points: "Schalter Punkte" + total-points: "Gesamtpunkte" abandoned-in-days: "§6Wird in §6{0} Tagen gelöscht" criteria: accuracy: "Genauigkeit" @@ -180,9 +180,9 @@ note: score-will-be-split: "Die Punkte werden bei der Bewertung auf alle Mitglieder aufgeteilt!" player-has-to-be-online: "Spieler muss online sein!" optional: "Optional" - required: "Required" - criteria-fulfilled: "Fulfilled" - criteria-not-fulfilled: "Not fulfilled" + required: "Erforderlich" + criteria-fulfilled: "Erfüllt" + criteria-not-fulfilled: "Nicht erfüllt" legacy: "LEGACY" action: read: 'Gelesen' @@ -207,7 +207,7 @@ note: click-to-play-with-friends: "§7Willst du mit deinen Freunden spielen? §6Klicke hier..." tutorial-show-stages: 'Stages Anzeigen' click-to-open-plots-menu: 'Klicke hier, um das Plot Menü zu öffnen...' - click-to-toggle: "Click to toggle..." + click-to-toggle: "Zum Umschalten klicken..." #----------------------------------------------------- #| Messages #----------------------------------------------------- @@ -232,10 +232,10 @@ message: removed-plot-member: "§a§6{0}§a wurde vom Plot entfernt §6#{1}§a!" left-plot: "§aVerlasse Plot §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lWARNING: §cDieser Plot wird automatisch aufgelassen werden!" - plot-will-be-rejected: "Plot will be rejected!" - plot-will-be-accepted: "Plot will be accepted" - plots-reviewed-singular: "{0} plot has been reviewed!" - plots-reviewed-plural: "{0} plots have been reviewed!" + plot-will-be-rejected: "Plot wird abgelehnt!" + plot-will-be-accepted: "Plot wird akzeptiert" + plots-reviewed-singular: "{0} Plot wurde bewertet!" + plots-reviewed-plural: "{0} Plots wurden bewertet!" saving-plot: "§aSpeichere Plot..." creating-plot: "§aErstelle neuen Plot..." created-new-plot: "§aEin neuer Plot§a wurde für §6{0}§a erstellt!" @@ -257,12 +257,12 @@ message: can-only-submit-unfinished-plots: "Du kannst nur unfertige Plots abgeben!" can-only-undo-submissions-unreviewed-plots: "Du kannst nur Einreichungen von unbewerteten Plots rückgängig machen!" can-only-manage-members-unfinished-plots: "Du kannst nur Mitglieder von unfertigen Plots verwalten!" - cannot-teleport-outside-plot: "Du kannst dich nicht ausserhalb des Plots teleportieren!" + cannot-teleport-outside-plot: "Du kannst dich nicht ausserhalb des Plotes teleportieren!" cannot-undo-review: "Du kannst eine Bewertung nicht rückgängig machen, wenn du sie nicht selbst erstellt hast!" cannot-send-feedback: "Du kannst auf einen Plot kein Feedback geben, wenn du ihn nicht selbst bewertet hast!" cannot-review-own-plot: "Du kannst deine eigenen Plots nicht bewerten!" - cannot-modify-legacy-plot: "Legacy plots cannot be modified!" - cannot-load-legacy-plot: "Legacy plots cannot be loaded!" + cannot-modify-legacy-plot: "Legacy-Plots können nicht geändert werden!" + cannot-load-legacy-plot: "Legacy-Plots können nicht geladen werden!" player-has-no-permissions: "Du hast keine Berechtigung dafür!" player-has-no-invitations: "Du hast keine offenen Einladungen!" player-is-not-allowed: "Du bist dazu nicht berechtigt!" @@ -284,7 +284,7 @@ message: chat-input-expired: "Die Eingabe ist abgelaufen." tutorial-disabled: 'Tutorials sind auf diesem Server deaktiviert.' tutorial-already-running: "Du hast bereits ein Tutorial am Laufen! Schließe dieses ab, bevor du ein neues beginnst." - review-not-found: "Review could not be found!" + review-not-found: "Bewertung konnte nicht gefunden werden!" leaderboards: pages: DAILY: "Heute" @@ -422,29 +422,28 @@ database: name: 'Liechtenstein' difficulty: easy: - name: 'Easy' + name: 'Einfach' medium: - name: 'Medium' + name: 'Normal' hard: - name: 'Hard' + name: 'Schwer' status: unclaimed: name: 'Unclaimed' unfinished: - name: 'Unfinished' + name: 'Unvollendet' unreviewed: - name: 'Unreviewed' + name: 'Nicht bewertet' completed: - name: 'Completed' + name: 'Fertiggestellt' toggle-criteria: - built_on_outlines: 'Built on outlines' - correct_height: 'Correct building height' - correct_facade_colour: 'Correct building colour' - correct_roof_colour: 'Correct roof colour' - correct_roof_shape: 'Correct roof shape' - correct_amount_windows_doors: 'Correct amount of windows and doors' - correct_window_type: 'Correct window types' - windows_blacked_out: 'All windows blacked out' - + built_on_outlines: 'Auf Grundriss gebaut' + correct_height: 'Richtige Gebäudehöhe' + correct_facade_colour: 'Richtige Fassadenfarbe' + correct_roof_colour: 'Richtige Dachfarbe' + correct_roof_shape: 'Richtige Dachform' + correct_amount_windows_doors: 'Korrekte Anzahl von Fenstern und Türen' + correct_window_type: 'Richtige Verstrebungen' + windows_blacked_out: 'Alle Fenster verdunkelt' #NOTE: Do not change config-version: 2.5 \ No newline at end of file diff --git a/src/main/resources/lang/en_GB.yml b/src/main/resources/lang/en_GB.yml index 93d9c3ae..a103e28e 100644 --- a/src/main/resources/lang/en_GB.yml +++ b/src/main/resources/lang/en_GB.yml @@ -447,4 +447,4 @@ database: windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 diff --git a/src/main/resources/lang/fr_FR.yml b/src/main/resources/lang/fr_FR.yml index cad03f6f..6d663c97 100644 --- a/src/main/resources/lang/fr_FR.yml +++ b/src/main/resources/lang/fr_FR.yml @@ -446,4 +446,4 @@ database: windows_blacked_out: 'All windows blacked out' #NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 diff --git a/src/main/resources/lang/he_IL.yml b/src/main/resources/lang/he_IL.yml index 3f47d6af..0583f7ff 100644 --- a/src/main/resources/lang/he_IL.yml +++ b/src/main/resources/lang/he_IL.yml @@ -17,7 +17,7 @@ lang: # ----------------------------------------------------- plot: plot-name: "פלוט" - id: "ID" + id: "מזהה" owner: "בעלי הפלוט" members: "חברי פלוט" member: "חבר פלוט" @@ -69,6 +69,7 @@ difficulty: menu-title: close: 'לסגור' back: 'אחורה' + continue: 'המשך' next-page: 'עמוד הבא' previous-page: 'עמוד קודם' error: 'תקלה' @@ -158,15 +159,16 @@ review: feedback: "משוב" reviewer: "סוקר" player-language: "שפת השחקן" + no-feedback: "אין משוב" + accuracy-points: "Accuracy points" + block-palette-points: "Block palette points" + toggle-points: "" + total-points: "סך הכל נקודות" criteria: accuracy: "דיוק" accuracy-desc: "עד כמה הבנייה מדויקת?%newline%%newline%- נראית כמו במציאות%newline%- קווי המתאר נכונים%newline%- גובה נכון%newline%- מושלמת" block-palette: "פלטת בלוקים" block-palette-desc: "כמה בלוקים שונים נעשה שימוש וכמה זה יצירתי?%newline%%newline%- בחירת צבעים/מרקמים%newline%- בלוקים אקראיים" - detailing: "פרטים" - detailing-desc: "כמה פרטים יש לבנייה?%newline%%newline%- פרטי גג%newline%- פרטים על חזיתות%newline%- ראשים ודגלים" - technique: "טכניקה" - technique-desc: "אילו טכניקות בנייה נעשה בהן שימוש וכמה הן יצירתיות?%newline%%newline%- World-Edit%newline%- בלוקים מיוחדים" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -176,6 +178,11 @@ note: wont-be-able-continue-building: "לא תוכל להמשיך לבנות בפלוט זה!" score-will-be-split: "הציון יחולק בין כל החברים בעת הסקירה!" player-has-to-be-online: "השחקן חייב להיות מחובר!" + optional: "Optional" + required: "חובה" + criteria-fulfilled: "בוצע" + criteria-not-fulfilled: "Not fulfilled" + legacy: "LEGACY" action: read: 'קרא' read-more: 'קרא עוד' @@ -198,6 +205,8 @@ note: click-to-show-plots: "ֲ§6לחץ כאן ֲ§כדי להציג את הפלוטים שלך..." click-to-play-with-friends: "ֲ§7רוצה לשחק עם חברים? ֲ§6לחץ כאן..." tutorial-show-stages: 'הצג שלבים' + click-to-open-plots-menu: 'Click to open the plots menu...' + click-to-toggle: "Click to toggle..." # ----------------------------------------------------- # | Messages # ----------------------------------------------------- @@ -222,7 +231,10 @@ message: removed-plot-member: "ֲ§aהוסר ֲ§6{0}ֲ§a מהפלוט ֲ§6#{1}ֲ§a!" left-plot: "ֲ§aעזבת את הפלוט ֲ§6#{0}ֲ§a!" plot-will-get-abandoned-warning: "ֲ§cֲ§lאזהרה: ֲ§cפלוט זה ייעזב אוטומטית!" - plot-will-get-rejected-warning: "ֲ§cֲ§lאזהרה: ֲ§cפלוט זה יידחה!" + plot-will-be-rejected: "Plot will be rejected!" + plot-will-be-accepted: "Plot will be accepted" + plots-reviewed-singular: "{0} plot has been reviewed!" + plots-reviewed-plural: "{0} plots have been reviewed!" saving-plot: "ֲ§aשומרים את הפלוט..." creating-plot: "ֲ§aיוצרים פלוט חדש..." created-new-plot: "ֲ§aפלוט חדש נוצר עבור ֲ§6{0}ֲ§a!" @@ -248,7 +260,9 @@ message: cannot-undo-review: "אי אפשר לבטל סקירה שלא ביצעת בעצמך!" cannot-send-feedback: "אי אפשר לבטל סקירה שלא ביצעת בעצמך!" cannot-review-own-plot: "אי אפשר לסקור את הפלוט שלך!" - player-has-no-permissions: אין לך הרשאות לבצע זאת!" + cannot-modify-legacy-plot: "Legacy plots cannot be modified!" + cannot-load-legacy-plot: "Legacy plots cannot be loaded!" + player-has-no-permissions: "אין לך הרשאות לבצע זאת!\"" player-has-no-invitations: "אין לך הזמנות!!" player-is-not-allowed: "אתה לא מורשה לעשות זאת!" player-is-plot-owner: "השחקן הזה הוא כבר בעל הפלוט!" @@ -261,6 +275,7 @@ message: player-invite-to-rejected: '{0} דחה את ההזמנה שלך.' player-needs-to-be-on-plot: "עליך להיות בפלוט כדי להשתמש בזה!" player-needs-higher-score: "אתה צריך ציון גבוה יותר כדי לבנות ברמת קושי זו." + player-missing-tutorial: "The player must first complete the tutorial to be added to the plot!" error-occurred: "אירעה שגיאה! אנא נסה שוב!" no-plots-left: "אין עוד פלוטים פנויים בפרויקט העיר הזה. נא לבחור בפרויקט אחר." please-wait: "אנא המתן כמה שניות לפני יצירת פלוט חדש!" @@ -268,6 +283,7 @@ message: chat-input-expired: "הזנת הצ'אט פגה." tutorial-disabled: 'הדרכות מושבתות בשרת זה.' tutorial-already-running: "כבר יש לך הדרכה פעילה! סיים אותה לפני שתתחיל חדשה." + review-not-found: "Review could not be found!" leaderboards: pages: DAILY: "יומי" @@ -279,7 +295,7 @@ leaderboards: actionbar-percentage: "TOP {0}%" not-on-leaderboard: "לא נמצא בטבלת המובילים" tutorials: - stage: 'Stage' + stage: 'שלב' new-stage-unlocked: 'שלב חדש נפתח' tutorial-completed: 'ההדרכה הושלמה' beginner: @@ -388,5 +404,45 @@ tutorials: - 'בנייה מהנה! ג˜÷' stage-10-tasks: - 'קרא את כל הטיפים במגרש וסמן אותם כנקראו.' +#----------------------------------------------------- +#| Database +#----------------------------------------------------- +database: + city-project: + example-city: + name: 'עיר לדוגמה' + description: 'Some description' + country: + AT: + name: 'אוסטריה' + CH: + name: 'שוויץ' + LI: + name: 'ליכטנשטיין' + difficulty: + easy: + name: 'קל' + medium: + name: 'בינוני' + hard: + name: 'קשה' + status: + unclaimed: + name: 'Unclaimed' + unfinished: + name: 'לא גמור' + unreviewed: + name: 'Unreviewed' + completed: + name: 'הושלם' + toggle-criteria: + built_on_outlines: 'Built on outlines' + correct_height: 'Correct building height' + correct_facade_colour: 'Correct building colour' + correct_roof_colour: 'Correct roof colour' + correct_roof_shape: 'Correct roof shape' + correct_amount_windows_doors: 'Correct amount of windows and doors' + correct_window_type: 'Correct window types' + windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 1.0 +config-version: 1.1 diff --git a/src/main/resources/lang/ko_KR.yml b/src/main/resources/lang/ko_KR.yml index 5882e5f0..358209eb 100644 --- a/src/main/resources/lang/ko_KR.yml +++ b/src/main/resources/lang/ko_KR.yml @@ -446,4 +446,4 @@ database: windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 diff --git a/src/main/resources/lang/pt_PT.yml b/src/main/resources/lang/pt_PT.yml index f02ae958..6d6f0566 100644 --- a/src/main/resources/lang/pt_PT.yml +++ b/src/main/resources/lang/pt_PT.yml @@ -178,7 +178,7 @@ note: wont-be-able-continue-building: "Você não poderá continuar construindo neste terreno!" score-will-be-split: "A pontuação será dividida entre todos os membros quando revisada!" player-has-to-be-online: "O jogador tem que estar online!" - optional: "Optional" + optional: "Opcional" required: "Required" criteria-fulfilled: "Fulfilled" criteria-not-fulfilled: "Not fulfilled" @@ -260,8 +260,8 @@ message: cannot-undo-review: "Você não pode desfazer uma avaliação que você mesmo não avaliou!" cannot-send-feedback: "Você não pode enviar feedback para um lote que você mesmo não avaliou!" cannot-review-own-plot: "Você não pode revisar seu próprio terreno!" - cannot-modify-legacy-plot: "Legacy plots cannot be modified!" - cannot-load-legacy-plot: "Legacy plots cannot be loaded!" + cannot-modify-legacy-plot: "Terrenos legados não podem ser modificados!" + cannot-load-legacy-plot: "Terrenos legados não podem ser carregados!" player-has-no-permissions: "Você não tem permissão para fazer isso!" player-has-no-invitations: "Você não tem convites!" player-is-not-allowed: "Você não tem permissão para fazer isso!" @@ -446,4 +446,4 @@ database: windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 diff --git a/src/main/resources/lang/ru_RU.yml b/src/main/resources/lang/ru_RU.yml index 1ef1a8ce..a4ef2df7 100644 --- a/src/main/resources/lang/ru_RU.yml +++ b/src/main/resources/lang/ru_RU.yml @@ -17,12 +17,12 @@ lang: # ----------------------------------------------------- plot: plot-name: "Участок" - id: "ID" + id: "Айди" owner: "Владелец Участка" - members: "Участник собственности" + members: "Участники Участка" member: "Участник Участка" city: "Город" - country: "Country" + country: "Страна" difficulty: "Сложность" status: "Статус" score: "Оценка" @@ -35,28 +35,28 @@ plot: # | City Projects # ----------------------------------------------------- city-project: - cities: "Cities" + cities: "Города" open: "Свободных Участков" in-progress: "Участков в Процессе Постройки" completed: "Завершённых Участков" - plots-available: 'Plots Available' + plots-available: 'Доступные Участки' no-plots-available: "Доступных Участков Нет" - for-your-difficulty: "({0} for your difficulty)" + for-your-difficulty: "({0} для вашего уровня)" # ----------------------------------------------------- # | Countries # ----------------------------------------------------- country: - countries: "Countries" + countries: "Страны" # ----------------------------------------------------- # | Continents # ----------------------------------------------------- continent: - europe: "Europe" - asia: "Asia" - africa: "Africa" - oceania: "Oceania" - south-america: "South America" - north-america: "North America" + europe: "Европа" + asia: "Азия" + africa: "Африка" + oceania: "Океания" + south-america: "Южная Америка" + north-america: "Северная Америка" # ----------------------------------------------------- # | Difficulty # ----------------------------------------------------- @@ -69,7 +69,7 @@ difficulty: menu-title: close: "Закрыть" back: "Назад" - continue: 'Continue' + continue: 'Продолжить' next-page: "Следующая Страница" previous-page: "Предыдущая Страница" error: "Ошибка" @@ -87,30 +87,30 @@ menu-title: feedback: "Обратная связь | Отзыв #{0}" custom-heads: "Кастомные Головы" banner-maker: "Создатель Баннеров" - special-tools: "Special Blocks & Items" + special-tools: "Специальные блоки и предметы" review-point: "Балл" review-points: "Баллов" cancel: "Отменить" add-member-to-plot: "Добавить Участника к Участку" companion: "Компаньонка" - companion-select-continent: 'Select A Continent' - companion-select-country: 'Select A Country' - companion-select-city: 'Select A City' + companion-select-continent: 'Выбрать Континент' + companion-select-country: 'Выберите Страну' + companion-select-city: 'Выбор Города' player-plots: "{0} Участков" leave-plot: "Покинуть Участок" review-plots: "Оценить Участки" review-plot: "Оценить Участок #{0}" select-language: "Выберите Язык" - select-plot-type: 'Select Plot Type' + select-plot-type: 'Выбрать тип Участка' select-focus-mode: "Select Focus Mode" select-local-inspiration-mode: "Select Inspiration Mode" select-city-inspiration-mode: "Select City Inspiration Mode" - filter-by-country: "Filter By Country" - information: "Info" - tutorials: 'Tutorials' - tutorial-stages: 'Tutorial Stages' - tutorial-end: 'End Tutorial' - tutorial-beginner: 'Get Started' + filter-by-country: "Фильтровать по стране" + information: "Информация" + tutorials: 'Обучение' + tutorial-stages: 'Этапы обучения' + tutorial-end: 'Конец обучения' + tutorial-beginner: 'Начать' companion-random: 'Случайный выбор' # ----------------------------------------------------- # | Menu Descriptions @@ -129,21 +129,21 @@ menu-description: manage-members-desc: "Нажмите, чтобы открыть меню Участников Участка, где вы можете добавить или удалить других игроков с вашего участка" feedback-desc: "Нажмите, чтобы просмотреть оценку вашего участка" custom-heads-desc: "Нажмите, чтобы открыть меню голов и получить кастомные головы" - banner-maker-desc: "Click to create and save your own banners" + banner-maker-desc: "Нажмите, чтобы создать и сохранить свои баннеры" special-tools-desc: "Click here to access a variety of inaccessible blocks and items" add-member-to-plot-desc: "Пригласите своих друзей к вашему участку и начните строить вместе" review-points-desc: "Нажмите, чтобы выбрать" submit-review-desc: "Отправить выбранные баллы и отметить участок как оценённый" leave-plot-desc: "Нажмите, чтобы покинуть данный участок" select-language-desc: "Выберите свой язык" - select-plot-type-desc: 'Choose your plot type' + select-plot-type-desc: 'Выберите тип вашего Участка' select-focus-mode-desc: "Build your plot on a floating island in the void.%newline%%newline%- No Environment%newline%- No neighboring plots" select-local-inspiration-mode-desc: "Build on a floating island with surrounding environment as a reference.%newline%%newline%+ Environment%newline%- No neighboring plots" select-city-inspiration-mode-desc: "Build on a floating island with surrounding environment and other players plots that got scanned near the own plot.%newline%%newline%+ Environment%newline%+ Neighboring plots" - filter-desc: "Show All" + filter-desc: "Показать всё" information-desc: "A plot can receive a maximum of 20 points. If the plot receives less than 8 points or one category has 0 points, the plot is rejected and the builder gets the plot back to improve it. If the plot receives 0 points, it gets abandoned." tutorials-desc: 'Learn the basics of the BuildTheEarth project and enhance your building skills with tutorials on various topics.' - tutorial-end-desc: 'Your progress will be saved.' + tutorial-end-desc: 'Ваш прогресс будет сохранен.' tutorial-beginner-desc: 'Learn the basics how to build for the BuildTheEarth project.' companion-random-desc: 'Нажмите, чтобы выбрать случайным образом.' # ----------------------------------------------------- @@ -158,12 +158,12 @@ review: rejected: "Отклонено" feedback: "Отзыв" reviewer: "Оценщик" - player-language: "Player Language" - no-feedback: "No feedback" - accuracy-points: "Accuracy points" - block-palette-points: "Block palette points" + player-language: "Язык игрока" + no-feedback: "Нет ответа" + accuracy-points: "Баллы за точность" + block-palette-points: "Баллы за цветовую палитру" toggle-points: "Toggle points" - total-points: "Total points" + total-points: "Всего баллов" criteria: accuracy: "Точность Воссоздания" accuracy-desc: "Насколько точно исполнено здание?%newline%%newline%- Выглядит как в настоящей жизни%newline%- Правильные контуры%newline%- Правильная высота%newline%- Полностью завершен" @@ -173,30 +173,30 @@ review: # | Notes # ----------------------------------------------------- note: - tip: "Tip" - under-construction: 'Under Construction' + tip: "Совет" + under-construction: 'В процессе строительства' wont-be-able-continue-building: "Вы не сможете больше строить на этом участке!" score-will-be-split: "Общая Оценка будет разделена между всеми участниками после проверки!" player-has-to-be-online: "Игрок должен быть в сети!" - optional: "Optional" - required: "Required" + optional: "Необязательно" + required: "Требуется" criteria-fulfilled: "Fulfilled" criteria-not-fulfilled: "Not fulfilled" legacy: "LEGACY" action: - read: 'Read' - read-more: 'Read More' - mark-as-read: 'Mark as read' - start: 'Start' - continue: "Continue" - continue-tutorial: 'Continue Tutorial' - create-plot: 'Create Plot' + read: 'Читать' + read-more: 'Читать ещё' + mark-as-read: 'Отметить как прочитанное' + start: 'Начать' + continue: "Продолжить" + continue-tutorial: 'Продолжить обучение' + create-plot: 'Создать Участок' right-click: "Правая кнопка мыши" - left-click: "Left Click" - accept: 'Accept' - reject: 'Reject' - click-to-create-plot: 'Click to create new plot...' - click-to-proceed: "Click to proceed..." + left-click: "ЛКМ" + accept: 'Принять' + reject: 'Отклонить' + click-to-create-plot: 'Нажмите, чтобы создать новый участок...' + click-to-proceed: "Нажмите, чтобы продолжить..." click-to-remove-plot-member: "Нажмите, чтобы убрать участника с участка..." click-to-open-link: "Нажмите Здесь чтобы открыть {0} ссылку..." click-to-open-link-with-shortlink: "§6Нажмите Здесь §7чтобы открыть §a{0}§7 или воспользоваться этой ссылкой§a{1}" @@ -231,22 +231,22 @@ message: removed-plot-member: "§6{0}§a §aудалён из участка§6#{1}§a!" left-plot: "§aПокинул участок §6#{0}§a!" plot-will-get-abandoned-warning: "§c§lВНИМАНИЕ: §cЭтот участок будет автоматически сброшен!" - plot-will-be-rejected: "Plot will be rejected!" - plot-will-be-accepted: "Plot will be accepted" - plots-reviewed-singular: "{0} plot has been reviewed!" - plots-reviewed-plural: "{0} plots have been reviewed!" + plot-will-be-rejected: "Участок будет отклонён!" + plot-will-be-accepted: "Участок будет принят" + plots-reviewed-singular: "{0} участок был проверен!" + plots-reviewed-plural: "{0} участков было проверено!" saving-plot: "§aСохранение участка..." creating-plot: "§aСоздание нового участка..." created-new-plot: "§aСоздан новый участок§a для §6{0}§a!" - chat-enter-player: 'Please enter the name of the player in the chat.' - chat-enter-feedback: "Please enter a feedback for the player in the chat." + chat-enter-player: 'Пожалуйста, введите имя игрока в чате.' + chat-enter-feedback: "Пожалуйста, введите ответ для игрока в чат." chat-input-expires-after: "Chat input expires after {0} minutes." beginner-tutorial-required: 'Complete the tutorial to take part in the project.' beginner-tutorial-completed: 'Are you ready to build your own plot? Now it´s your turn!' player-invite-sent: 'An invitation has been sent to {0} to join your plot.' player-invite-to-sent: '{0} has invited you to help building on his plot.' - player-invite-accepted: 'Invitation to {0}´s plot has been accepted.' - player-invite-to-accepted: '{0} has accepted your invitation and has been added to your plot.' + player-invite-accepted: 'Приглашение на участок {0} было принято.' + player-invite-to-accepted: '{0} принял ваше приглашение и был добавлен на ваш участок.' player-invite-rejected: 'The invitation to {0}´s plot has been rejected.' error: plot-does-not-exist: "Этот участок не существует!" @@ -275,24 +275,24 @@ message: player-invite-to-rejected: '{0} has rejected your invitation.' player-needs-to-be-on-plot: "Вам нужно быть на участке чтобы использовать это!" player-needs-higher-score: "Вам нужна более высокая оценка чтобы строить на этом уровне сложности." - player-missing-tutorial: "Чтобы стать участником сюжета, игрок должен сначала пройти обучение!" + player-missing-tutorial: "Чтобы стать участником Участка, игрок должен сначала пройти обучение!" error-occurred: "Произошла ошибка! Пожалуйста, попробуйте снова!" no-plots-left: "У этого градостроительного проекта больше не осталось участков. Пожалуйста, выберите другой проект." please-wait: "Пожалуйста, подождите несколько секунд перед созданием нового участка!" all-slots-occupied: "Все ваши слоты заняты! Пожалуйста, завершите текущие участки, прежде чем создавать новый." chat-input-expired: "The chat input has expired." - tutorial-disabled: 'Tutorials are disabled on this server.' + tutorial-disabled: 'Обучение на этом сервере отключено.' tutorial-already-running: "You already have a tutorial running! Complete it before starting a new one." review-not-found: "Review could not be found!" leaderboards: pages: - DAILY: "Daily" - WEEKLY: "Weekly" + DAILY: "За день" + WEEKLY: "За неделю" MONTHLY: "Monthly" YEARLY: "Yearly" LIFETIME: "Lifetime" - actionbar-position: "Position #{0}" - actionbar-percentage: "Top {0}%" + actionbar-position: "Позиция #{0}" + actionbar-percentage: "Топ {0}%" not-on-leaderboard: "Not on leaderboard" tutorials: stage: 'Stage' @@ -300,18 +300,18 @@ tutorials: tutorial-completed: 'TUTORIAL COMPLETED' beginner: stage-1: - stage-1-title: 'Understanding the BuildTheEarth Project' + stage-1-title: 'Что такое проект BuildTheEarth' stage-1-messages: - - 'Hello {0}! Nice to meet you, my name is {1}. You´ve just stepped into the exciting world of the BuildTheEarth project!' - - 'Our mission is to recreate the entire planet Earth in Minecraft at a 1:1 scale. Yes, you heard right, at a 1:1 scale!' + - 'Привет, {0}! Рад тебя видеть, моё имя {1}. Ты зашёл в удивительный мир проекта BuildTheEarth!' + - 'Наша миссия - воссоздание всей планеты Земля в Minecraft в масштабе 1к1. Да, ты не ослышался, 1к1!' - 'However, we at Alps BTE are only responsible to recreate the beautiful alpine countries of Austria, Switzerland and Liechtenstein.' - - 'Are you ready to learn how to build for BTE? I will guide you through the basics to participate in the project. Let´s continue!' + - 'Готов научиться строить на BTE? Я расскажу тебе основы для участия в проекте. Продолжим!' stage-1-tasks: - 'Talk to {0} at the construction site.' stage-2: - stage-2-title: 'References' + stage-2-title: 'Референсы' stage-2-messages: - - 'Welcome on your little island. Here we will construct our first building for the Build The Earth project!' + - 'Добро пожаловать на твой небольшой остров. Здесь ты построишь своё первое здание в проекте BuildTheEarth!' - 'Before we begin building, we need to know how the real-life building looks like. For that we use tools like {0} and {1}.' - 'We use {2} to copy coordinates, so we can teleport to a specific point. In addition we can access {3} to have a closer look at the building.' - '{4}' @@ -320,7 +320,7 @@ tutorials: - 'Use the command {7} if you need the links later.' stage-2-tasks: stage-3: - stage-3-title: 'Teleporting' + stage-3-title: 'Телепортация' stage-3-messages: - 'The building outlines are generated by default, but since they are mostly not accurate, we have to correct them. To correct the outlines we firstly need to teleport to the edges of the building.' - 'Use the command {0} to teleport to the location in-game. {1} on one of the edges of the building to copy the coordinates.' @@ -336,16 +336,16 @@ tutorials: - 'In order to use WorldEdit, you need to get a wooden axe.' - 'Now that you have your wooden axe, you can {1} and {2} on blocks to make your selection.' stage-4-tasks: - - 'Use the command {0} to get your wooden axe.' + - 'Используй команду {0} , чтобы получить деревянный топор.' stage-5: - stage-5-title: 'Draw the Outlines' + stage-5-title: 'Сделайте контуры' stage-5-messages: - 'Now that we know about WorldEdit, we can draw the outlines of the building.' - 'To draw the outlines, we use the command {0}.' - '{1} to select the first point and {2} to select the second point.' - 'To continue connect the points using {0}. Try again!' stage-5-tasks: - - 'Connect the points by using {0}.' + - 'Соедините точки, используя {0}.' stage-6: stage-6-title: 'Building Heights' stage-6-messages: @@ -372,7 +372,7 @@ tutorials: stage-7-tasks: - 'Read all tips on the plot and mark them as read.' stage-8: - stage-8-title: 'Windows' + stage-8-title: 'Окна' stage-8-messages: - 'The building shell is done! Let´s continue with the windows and doors.' - 'Ohh... it looks like there are two windows missing. Can you help me place them? They look the same as on the right side.' @@ -392,7 +392,7 @@ tutorials: stage-9-tasks: - 'Read all tips on the plot and mark them as read.' stage-10: - stage-10-title: 'Detailing & Further Steps' + stage-10-title: 'Детализация и следующие шаги' stage-10-messages: - 'Detailing is one of the most important processes as it makes the building distinctive and unique.' - 'Add §6custom banners§f and §6custom heads§f to your builds. Use the command §6{0}§f to get a variety of custom heads.' @@ -400,10 +400,10 @@ tutorials: - 'Thank you for your participation. You are now ready to create your own buildings for the BuildTheEarth project!' - 'Click here to learn more about the project.' - 'To apply as builder, create and submit one or more plots on our server. You can find more information about the application process on our website or {1}.' - - 'If you want to explore the current progress of the map, check out the Terra server!' - - 'Happy building! ☺' + - 'Если вы хотите изучить текущий прогресс карты, проверьте Terra сервер!' + - 'Приятного строительства! ☺' stage-10-tasks: - - 'Read all tips on the plot and mark them as read.' + - 'Прочитайте все советы на Участке и пометьте их как прочитанные.' # ----------------------------------------------------- # | Database # ----------------------------------------------------- @@ -411,39 +411,39 @@ database: city-project: example-city: name: 'Example City' - description: 'Some description' + description: 'Описание' country: AT: - name: 'Austria' + name: 'Австрия' CH: - name: 'Switzerland' + name: 'Швейцария' LI: - name: 'Liechtenstein' + name: 'Лихтенштейн' difficulty: easy: - name: 'Easy' + name: 'Лёгкий' medium: - name: 'Medium' + name: 'Средний' hard: - name: 'Hard' + name: 'Сложный' status: unclaimed: - name: 'Unclaimed' + name: 'Свободно' unfinished: - name: 'Unfinished' + name: 'Не завершено' unreviewed: - name: 'Unreviewed' + name: 'Не проверено' completed: - name: 'Completed' + name: 'Завершено' toggle-criteria: - built_on_outlines: 'Built on outlines' - correct_height: 'Correct building height' - correct_facade_colour: 'Correct building colour' - correct_roof_colour: 'Correct roof colour' - correct_roof_shape: 'Correct roof shape' - correct_amount_windows_doors: 'Correct amount of windows and doors' - correct_window_type: 'Correct window types' - windows_blacked_out: 'All windows blacked out' + built_on_outlines: 'Построено на контуре' + correct_height: 'Правильная высота здания' + correct_facade_colour: 'Правильный цвет здания' + correct_roof_colour: 'Правильный цвет крыши' + correct_roof_shape: 'Правильная форма крыши' + correct_amount_windows_doors: 'Правильное количество окон и дверей' + correct_window_type: 'Правильные типы окон' + windows_blacked_out: 'Все окна затемнены' # NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 diff --git a/src/main/resources/lang/zh_CN.yml b/src/main/resources/lang/zh_CN.yml index fd96714c..cd8bf351 100644 --- a/src/main/resources/lang/zh_CN.yml +++ b/src/main/resources/lang/zh_CN.yml @@ -446,4 +446,4 @@ database: windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 diff --git a/src/main/resources/lang/zh_TW.yml b/src/main/resources/lang/zh_TW.yml index a0e4feb4..1a147704 100644 --- a/src/main/resources/lang/zh_TW.yml +++ b/src/main/resources/lang/zh_TW.yml @@ -127,13 +127,13 @@ menu-description: abandon-desc: "點擊以重設你的建地,並將其交付他人" undo-submit-desc: "點擊以撤回你的提交" manage-members-desc: "點擊以開啟建地成員選單你可以在那裡添加和移除在你建地上的其他玩家" - feedback-desc: "點擊以查看你建地的審核評語" + feedback-desc: "點擊以查看你的建地審核評語" custom-heads-desc: "點擊開啟頭顱選單以取得一個定製頭顱" - banner-maker-desc: "點擊以創造並儲存你自己的旗幟" + banner-maker-desc: "點擊以創建並儲存你自己的旗幟" special-tools-desc: "點擊此處以存取各種無法存取的方塊和物品" add-member-to-plot-desc: "邀請你的朋友到你的建地並開始共同建設" review-points-desc: "點擊以選取" - submit-review-desc: "提交選定的點並將建地標記為已審核" + submit-review-desc: "提交選取點並標記建地供審核" leave-plot-desc: "點擊以離開此建地" select-language-desc: "選擇你的語言" select-plot-type-desc: '挑選你的建地類型' @@ -141,7 +141,7 @@ menu-description: select-local-inspiration-mode-desc: "在有周邊環境能作參考的空島建設。%newline%%newline%+ 周邊環境%newline%- 沒有鄰近建地" select-city-inspiration-mode-desc: "在有周邊環境的空島建設,並投影出附近其他玩家的建地。%newline%%newline%+ 周邊環境%newline%+ 鄰近建地" filter-desc: "顯示全部" - information-desc: "一個建地最高可以獲得20積分。如果建地得分小於8分或任一類別獲得0分,該建地將被否決,建造者要取回建地並改進。如果建地獲得0分,它將被廢棄。" + information-desc: "一個建地最高可以獲得20積分。如果建地得分小於8分或任一類別獲得0分,該建地將被駁回,建造者要取回建地並改進。如果建地獲得0分,它將被廢棄。" tutorials-desc: '透過各種主題的教學來學習BuildTheEarth計畫的基礎知識並提升你的建築技巧。' tutorial-end-desc: '你的進度將被儲存。' tutorial-beginner-desc: '學習在BuildTheEarth計畫建築的基礎知識。' @@ -154,10 +154,10 @@ review: manage-plot: "管理建地" manage-and-review-plots: "管理與審核建地" accepted: "已同意" - abandoned: "已廢棄" rejected: "已否決" - feedback: "評語" - reviewer: "審核人" + abandoned: "已廢棄" + feedback: "回饋" + reviewer: "審核員" player-language: "玩家語言" no-feedback: "No feedback" accuracy-points: "Accuracy points" @@ -168,7 +168,7 @@ review: accuracy: "準確性" accuracy-desc: "建築的精確度如何?%newline%%newline%- 看起來像在真實世界%newline%- 正確的輪廓%newline%- 正確的高度%newline%- 完成了" block-palette: "方塊用色" - block-palette-desc: "使用了多少個不同的方塊,它們的創意如何?%newline%%newline%- 方塊顏色/紋理的選擇%newline%- 隨機方塊" + block-palette-desc: "使用了多少個不同的方塊,它們的創意如何?%newline%%newline%- 方塊顏色/材質的選擇%newline%- 隨機方塊" # ----------------------------------------------------- # | Notes # ----------------------------------------------------- @@ -176,7 +176,7 @@ note: tip: "提示" under-construction: '建設中' wont-be-able-continue-building: "你將無法繼續在此建地上進行建設!" - score-will-be-split: "審核時積分將分配給全部的成員!" + score-will-be-split: "審核時積分將分配給所有成員!" player-has-to-be-online: "玩家必須上線!" optional: "Optional" required: "Required" @@ -227,7 +227,7 @@ message: unfinished-plots: "§a你有§6{0}§a處尚未完成的建地!" enabled-build-permissions: "§a啟用審核人於建地§6#{0}§a的建築權限!" disabled-build-permissions: "§a禁用審核人於建地§6#{0}§a的建築權限!" - updated-plot-feedback: "§a建地§6#{0}§a的評語已更新!" + updated-plot-feedback: "§a建地 §6#{0}§a 的回饋已更新!" removed-plot-member: "§a將§6{0}§a從建地§6#{1}§a中移除!" left-plot: "§a離開建地§6#{0}§a!" plot-will-get-abandoned-warning: "§c§l警告:§c此建地將自動被廢棄!" @@ -245,17 +245,17 @@ message: beginner-tutorial-completed: '你準備好建設你自己的建地了嗎?現在該你上場了!' player-invite-sent: '已向{0}發送加入你建地的邀請。' player-invite-to-sent: '{0}邀請你到他的建地協助建設。' - player-invite-accepted: '已同意來自{0}建地的邀請。' - player-invite-to-accepted: '{0}同意了你的邀請並加入了你的建地。' - player-invite-rejected: '已否決來自{0}建地的邀請。' + player-invite-accepted: '已接受來自 {0} 建地的邀請。' + player-invite-to-accepted: '{0} 接受了你的邀請並加入了你的建地。' + player-invite-rejected: '已拒絕來自 {0} 建地的邀請。' error: plot-does-not-exist: "此建地不存在!" plot-either-unclaimed-or-unreviewed: "此建地無人認領或尚未審核!" - plot-has-not-yet-reviewed: "此建地尚未審核!" + plot-has-not-yet-reviewed: "此建地尚未審核!!" can-only-abandon-unfinished-plots: "你只能廢棄尚未完成的建地!" can-only-submit-unfinished-plots: "你只能提交尚未完成的建地!" can-only-undo-submissions-unreviewed-plots: "你只能撤回尚未審核的建地!" - can-only-manage-members-unfinished-plots: "你只能管理尚未完成的建地的成員!" + can-only-manage-members-unfinished-plots: "你只能管理尚未完成建地的成員!" cannot-teleport-outside-plot: "你無法傳送到建地外!" cannot-undo-review: "你無法撤回未經你本人審核過的審核!" cannot-send-feedback: "你無法給未經你本人審核過建地的發送評語!" @@ -265,14 +265,14 @@ message: player-has-no-permissions: "你沒有權限使用!" player-has-no-invitations: "你沒有受到邀請!" player-is-not-allowed: "你不被允許使用!" - player-is-plot-owner: "此玩家已經是建地的所有人!" + player-is-plot-owner: "此玩家已經是建地擁有者!" player-is-plot-member: "此玩家已經是此建地的成員!" player-is-not-online: "此玩家不在線上!" player-not-found: "無法找到該玩家!" player-already-invited: '{0}已被邀請加入建地了。' player-invite-expired: '來自{0}的邀請過期了。' player-invite-to-expired: '你發送給{0}的邀請過期了。' - player-invite-to-rejected: '{0}否決了你的邀請。' + player-invite-to-rejected: '{0} 拒絕了你的邀請。' player-needs-to-be-on-plot: "你需要在一個建地上才能使用它!" player-needs-higher-score: "你需要更高的積分來才能在這個難度下建設。" player-missing-tutorial: "玩家必须先完成教程,才能加入剧情!" @@ -287,11 +287,11 @@ message: leaderboards: pages: DAILY: "每日" - WEEKLY: "每周" + WEEKLY: "每週" MONTHLY: "每月" YEARLY: "每年" LIFETIME: "生涯" - actionbar-position: "排名#{0}" + actionbar-position: "排行 #{0}" actionbar-percentage: "前{0}%" not-on-leaderboard: "不在排行榜上" tutorials: @@ -328,7 +328,7 @@ tutorials: - '繼續傳送到其他標記點。以此類推!' - '切換Google地圖中的§6衛星§f視圖,建築物將以3D呈現。%newline%%newline%點擊地圖左下角的§6圖層§f。如果3D建築物沒有出現,則啟用「更多」中的§6地球檢視畫面§6。' stage-3-tasks: - - '使用{1}來傳送到建築物的全部{0}個邊緣。' + - '使用{1} 來傳送到所有的{0} 個建築物邊緣。' stage-4: stage-4-title: 'WorldEdit' stage-4-messages: @@ -345,7 +345,7 @@ tutorials: - '{1}以選取第一個點,{2}以選取第二個點。' - '使用{0}繼續連接其他點。以此類推!' stage-5-tasks: - - '使用{0}連接全部的點。' + - '使用 {0} 連接所有點。' stage-6: stage-6-title: '建築物高度' stage-6-messages: @@ -370,7 +370,7 @@ tutorials: - '使用WorldEdit指令§6{1}§f或手動填充屋頂。或使用指令§6{2}§f來切換選取區以因應更大更複雜的屋頂。' - '時刻檢查門窗的§6高度§f,使其與立面§6匹配§f。' stage-7-tasks: - - '閱讀建地上全部的提示並將其標記為已讀。' + - '閱讀建地上的所有提示並將其標記為已讀。' stage-8: stage-8-title: '窗戶' stage-8-messages: @@ -379,7 +379,7 @@ tutorials: - '別忘了§6暗化§f§6門窗§f讓你無法看穿他們。我們不建造內飾!' - '為BTE建造窗戶的方法有很多種,例如使用§6旗幟§f、§6地板門§f或§6地毯§f。' - '使用與右邊窗戶相同的方塊來製作。以此類推!' - - '感謝你的幫助!現在我們可以繼續塗裝了。' + - '感謝你的幫助!現在我們可以繼續上色了。' stage-8-tasks: - '放置缺失的窗戶細節。' stage-9: @@ -388,22 +388,22 @@ tutorials: - '塗裝是建築過程中不可或缺的一部分。使用合適的方塊和顏色使建築物看起來逼真非常重要。' - '使用§6Google街景服務§f或§6圖片§f來挑選合適的方塊,因為航照影像有時不是很準確。' - '使用WorldEdit指令§6{0}§f將你要的圖樣直接替換到外殼上。' - - '嘗試為牆壁和屋頂使用§6混合方塊§f和§6漸層§f,使建築物看起來更加真實與出眾。' + - '嘗試為牆壁和屋頂使用§6混合方塊§f和§6漸層§f,使建築物看起來更真實和出眾。' stage-9-tasks: - - '閱讀建地上全部的提示並將其標記為已讀。' + - '閱讀建地上的所有提示並將其標記為已讀。' stage-10: stage-10-title: '裝飾&後續步驟' stage-10-messages: - '裝飾是最重要的過程之一,它將使建築物與眾不同。' - '添加§6定製旗幟§f和§6定製頭顱§f到你的建築上。使用指令§6{0}§f來取得各種定製頭顱。' - '§6裝飾§f你建築物的方法有很多。時刻留意立面和屋頂的細節,例如§6煙囪§f、§6窗戶§f和§6排水槽§f。' - - '感謝你的參與。你現在已經準備好為BuildTheEarth計畫創造你自己的建築物了!' + - '感謝你的參與。你現在已經準備好為BuildTheEarth計畫創建你自己的建築物了!' - '點擊此處更深入了解此計畫。' - - '要申請成為建築師,請在我們的伺服器上建立並提交一或多個建地。你可以在我們的網站或{1}上找到更多關於申請過程的資訊。' - - '如果你想要探索地圖目前的進度,請查看Terra伺服器!' + - '要申請成為建築師,請在我們的伺服器上創建並提交一或多個建地。你可以在我們的網站或 {1} 上找到更多關於申請過程的資訊。' + - '如果你想要探索地圖目前的進度,請查看大地伺服器!' - '建築愉快!☺' stage-10-tasks: - - '閱讀建地上全部的提示並將其標記為已讀。' + - '閱讀建地上的所有提示並將其標記為已讀。' # ----------------------------------------------------- # | Database # ----------------------------------------------------- @@ -446,4 +446,4 @@ database: windows_blacked_out: 'All windows blacked out' # NOTE: Do not change -config-version: 2.5 \ No newline at end of file +config-version: 2.5 From 7b1edcad183bd11fa525cc65bc34b3ac4afb2430 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Wed, 14 Jan 2026 14:26:25 +0100 Subject: [PATCH 173/175] feat(tutorial): use /tutorials/schematics folder for tut schems --- .../alpsbte/plotsystem/core/system/plot/TutorialPlot.java | 3 +-- .../plotsystem/core/system/plot/utils/PlotUtils.java | 6 +++--- .../java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java | 3 +-- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java index 17e3b3da..1baf8492 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/TutorialPlot.java @@ -20,7 +20,6 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; -import java.nio.file.Paths; import java.time.LocalDate; import java.util.List; import java.util.Objects; @@ -149,7 +148,7 @@ public double getVersion() { public byte[] getInitialSchematicBytes() { File schematic; String fileName = getTutorialID() + "-" + currentSchematicId + ".schem"; - schematic = Paths.get(PlotUtils.getDefaultSchematicPath(), "tutorials", fileName).toFile(); + schematic = PlotUtils.getTutorialSchematicPath().resolve(fileName).toFile(); try { if (!schematic.exists()) FileUtils.copyInputStreamToFile(Objects.requireNonNull(PlotSystem.getPlugin() .getResource("tutorial/schematics/" + fileName + ".gz")), schematic); diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java index 9588b148..f76b001d 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/plot/utils/PlotUtils.java @@ -59,10 +59,10 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; import java.io.IOException; import java.math.RoundingMode; import java.net.URISyntaxException; +import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.time.LocalDate; @@ -230,8 +230,8 @@ public static boolean isPlotWorld(@NotNull World world) { return outputStream.toByteArray(); } - public static @NotNull String getDefaultSchematicPath() { - return Paths.get(PlotSystem.getPlugin().getDataFolder().getAbsolutePath(), "schematics") + File.separator; + public static @NotNull Path getTutorialSchematicPath() { + return Paths.get(PlotSystem.getPlugin().getDataFolder().getAbsolutePath(), "tutorial", "schematics"); } public static boolean savePlotAsSchematic(@NotNull Plot plot) throws IOException, WorldEditException { diff --git a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java index bd606f35..45dbd18e 100644 --- a/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java +++ b/src/main/java/com/alpsbte/plotsystem/utils/io/ConfigUtil.java @@ -50,8 +50,7 @@ public TutorialConfigurationUtil(ConfigFile[] configs) throws ConfigNotImplement public void updateConfigFile(@NotNull ConfigFile file) { int tutorialId = file.getInt(TutorialUtils.Path.TUTORIAL_ID); - File directory = Paths.get(PlotUtils.getDefaultSchematicPath(), "tutorials").toFile(); - File[] files = directory.listFiles(); + File[] files = PlotUtils.getTutorialSchematicPath().toFile().listFiles(); if (files == null) return; // Delete schematic files of the updated tutorial config after config has been updated From 69705116d707bd76129fa332dfe0bd5de9f123e7 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Wed, 14 Jan 2026 14:47:05 +0100 Subject: [PATCH 174/175] fix(tutorial): merge if statements --- .../core/system/tutorial/AbstractPlotTutorial.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java index 4548764e..874900f4 100644 --- a/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java +++ b/src/main/java/com/alpsbte/plotsystem/core/system/tutorial/AbstractPlotTutorial.java @@ -141,10 +141,8 @@ public void saveTutorial(int stageId) { Bukkit.getScheduler().runTaskAsynchronously(PlotSystem.getPlugin(), () -> { if (stageId >= stages.size()) { if (!tutorialPlot.isComplete()) tutorialPlot.setComplete(); - } else if (stageId > tutorialPlot.getStageID()) { - if (!tutorialPlot.setStageID(stageId)) { - PlotSystem.getPlugin().getComponentLogger().error("Could not save tutorial progress for tutorial plot #{}!", tutorialPlot.getId()); - } + } else if (stageId > tutorialPlot.getStageID() && !tutorialPlot.setStageID(stageId)) { + PlotSystem.getPlugin().getComponentLogger().error("Could not save tutorial progress for tutorial plot #{}!", tutorialPlot.getId()); } }); } From e0c769796978a984e607e9ef9ca9c2842690a2b1 Mon Sep 17 00:00:00 2001 From: Zoriot Date: Thu, 15 Jan 2026 22:05:44 +0100 Subject: [PATCH 175/175] fix(readme): update Plot System logo image source --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index bc48c5b8..4f508905 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,7 @@

- Plot System Logo + Plot System Logo