From d41670d21259bf0022cc59eef104a7e65141b1a3 Mon Sep 17 00:00:00 2001 From: ceze88 Date: Sat, 1 Jul 2023 10:41:18 +0200 Subject: [PATCH] Updates to new database system --- .../com/songoda/epicfarming/EpicFarming.java | 64 +---- .../songoda/epicfarming/boost/BoostData.java | 23 +- .../epicfarming/boost/BoostManager.java | 2 +- .../epicfarming/commands/CommandBoost.java | 2 +- .../epicfarming/database/DataManager.java | 243 ------------------ .../migrations/_1_InitialMigration.java | 9 +- .../com/songoda/epicfarming/farming/Farm.java | 81 ++++-- .../epicfarming/listeners/BlockListeners.java | 8 +- .../listeners/EntityListeners.java | 2 +- .../songoda/epicfarming/tasks/FarmTask.java | 6 +- .../songoda/epicfarming/utils/DataHelper.java | 65 +++++ 11 files changed, 182 insertions(+), 323 deletions(-) delete mode 100644 src/main/java/com/songoda/epicfarming/database/DataManager.java create mode 100644 src/main/java/com/songoda/epicfarming/utils/DataHelper.java diff --git a/src/main/java/com/songoda/epicfarming/EpicFarming.java b/src/main/java/com/songoda/epicfarming/EpicFarming.java index 1061d83..8240251 100644 --- a/src/main/java/com/songoda/epicfarming/EpicFarming.java +++ b/src/main/java/com/songoda/epicfarming/EpicFarming.java @@ -5,7 +5,6 @@ import com.craftaro.core.SongodaPlugin; import com.craftaro.core.commands.CommandManager; import com.craftaro.core.compatibility.ServerVersion; import com.craftaro.core.configuration.Config; -import com.craftaro.core.database.DataMigrationManager; import com.craftaro.core.database.DatabaseConnector; import com.craftaro.core.database.MySQLConnector; import com.craftaro.core.database.SQLiteConnector; @@ -22,7 +21,6 @@ import com.songoda.epicfarming.commands.CommandBoost; import com.songoda.epicfarming.commands.CommandGiveFarmItem; import com.songoda.epicfarming.commands.CommandReload; import com.songoda.epicfarming.commands.CommandSettings; -import com.songoda.epicfarming.database.DataManager; import com.songoda.epicfarming.database.migrations._1_InitialMigration; import com.songoda.epicfarming.farming.Farm; import com.songoda.epicfarming.farming.FarmManager; @@ -46,6 +44,7 @@ import com.songoda.epicfarming.storage.types.StorageYaml; import com.songoda.epicfarming.tasks.FarmTask; import com.songoda.epicfarming.tasks.GrowthTask; import com.songoda.epicfarming.tasks.HopperTask; +import com.songoda.epicfarming.utils.DataHelper; import com.songoda.epicfarming.utils.EntityUtils; import com.songoda.epicfarming.utils.Methods; import com.songoda.skyblock.SkyBlock; @@ -61,6 +60,7 @@ import org.bukkit.plugin.PluginManager; import java.io.File; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.UUID; @@ -79,9 +79,6 @@ public class EpicFarming extends SongodaPlugin { private EntityUtils entityUtils; - private DatabaseConnector databaseConnector; - private DataManager dataManager; - @Override public void onPluginLoad() { } @@ -94,7 +91,7 @@ public class EpicFarming extends SongodaPlugin { saveToFile(); for (Farm farm : this.farmManager.getFarms().values()) { if (farm.needsToBeSaved()) { - this.dataManager.updateItems(farm); + DataHelper.updateItems(farm); } } } @@ -133,30 +130,7 @@ public class EpicFarming extends SongodaPlugin { ); // Database stuff. - try { - if (Settings.MYSQL_ENABLED.getBoolean()) { - String hostname = Settings.MYSQL_HOSTNAME.getString(); - int port = Settings.MYSQL_PORT.getInt(); - String database = Settings.MYSQL_DATABASE.getString(); - String username = Settings.MYSQL_USERNAME.getString(); - String password = Settings.MYSQL_PASSWORD.getString(); - boolean useSSL = Settings.MYSQL_USE_SSL.getBoolean(); - int poolSize = Settings.MYSQL_POOL_SIZE.getInt(); - - this.databaseConnector = new MySQLConnector(this, hostname, port, database, username, password, useSSL, poolSize); - this.getLogger().info("Data handler connected using MySQL."); - } else { - this.databaseConnector = new SQLiteConnector(this); - this.getLogger().info("Data handler connected using SQLite."); - } - } catch (Exception ex) { - this.getLogger().severe("Fatal error trying to connect to database. Please make sure all your connection settings are correct and try again. Plugin has been disabled."); - this.emergencyStop(); - } - - this.dataManager = new DataManager(this.databaseConnector, this); - DataMigrationManager dataMigrationManager = new DataMigrationManager(this.databaseConnector, this.dataManager, new _1_InitialMigration()); - dataMigrationManager.runMigrations(); + initDatabase(Collections.singletonList(new _1_InitialMigration())); this.loadLevelManager(); @@ -200,7 +174,7 @@ public class EpicFarming extends SongodaPlugin { for (Farm farm : this.farmManager.getFarms().values()) { if (farm.needsToBeSaved()) { - this.dataManager.updateItemsAsync(farm); + DataHelper.updateItemsAsync(farm); } } }, 6000, 6000); @@ -248,13 +222,12 @@ public class EpicFarming extends SongodaPlugin { farmType = FarmType.valueOf(farmTypeStr); } - Farm farm = new Farm(location, this.levelManager.getLevel(row.get("level").asInt()), placedBy); - farm.setFarmType(farmType); + Farm farm = new Farm(location, this.levelManager.getLevel(row.get("level").asInt()), placedBy, farmType); farm.setItems(items); farms.add(farm); } - this.dataManager.createFarms(farms); + DataHelper.createFarms(farms); } // Adding in Boosts @@ -264,7 +237,7 @@ public class EpicFarming extends SongodaPlugin { continue; } - this.dataManager.createBoost(new BoostData( + this.dataManager.save(new BoostData( row.get("amount").asInt(), Long.parseLong(row.getKey()), UUID.fromString(row.get("uuid").asString()))); @@ -273,17 +246,12 @@ public class EpicFarming extends SongodaPlugin { dataFile.delete(); } - final boolean finalConverted = converted; - this.dataManager.runAsync(() -> { - if (finalConverted) { - Bukkit.getConsoleSender().sendMessage("[" + getDescription().getName() + "] " + ChatColor.GREEN + "Conversion complete :)"); - } + if (converted) { + Bukkit.getConsoleSender().sendMessage("[" + getDescription().getName() + "] " + ChatColor.GREEN + "Conversion complete :)"); - this.dataManager.getFarms((farms) -> { - this.farmManager.addFarms(farms.values()); - this.dataManager.getBoosts((boosts) -> this.boostManager.addBoosts(boosts)); - }); - }); + this.farmManager.addFarms(this.dataManager.loadBatch(Farm.class, "active_farms")); + this.boostManager.addBoosts(this.dataManager.loadBatch(BoostData.class, "boosts")); + } }); } @@ -426,11 +394,7 @@ public class EpicFarming extends SongodaPlugin { } public DatabaseConnector getDatabaseConnector() { - return this.databaseConnector; - } - - public DataManager getDataManager() { - return this.dataManager; + return this.dataManager.getDatabaseConnector(); } /** diff --git a/src/main/java/com/songoda/epicfarming/boost/BoostData.java b/src/main/java/com/songoda/epicfarming/boost/BoostData.java index 89034ba..3eb124c 100644 --- a/src/main/java/com/songoda/epicfarming/boost/BoostData.java +++ b/src/main/java/com/songoda/epicfarming/boost/BoostData.java @@ -1,9 +1,12 @@ package com.songoda.epicfarming.boost; +import com.craftaro.core.database.Data; + +import java.util.Map; import java.util.Objects; import java.util.UUID; -public class BoostData { +public class BoostData implements Data { private final int multiplier; private final long endTime; private final UUID player; @@ -50,4 +53,22 @@ public class BoostData { && Objects.equals(this.player, other.player); } + @Override + public Map serialize() { + Map map = new java.util.HashMap<>(); + map.put("player", this.player.toString()); + map.put("multiplier", this.multiplier); + map.put("end_time", this.endTime); + return map; + } + + @Override + public Data deserialize(Map map) { + return new BoostData((int) map.get("multiplier"), (long) map.get("end_time"), UUID.fromString((String) map.get("player"))); + } + + @Override + public String getTableName() { + return "boosted_players"; + } } diff --git a/src/main/java/com/songoda/epicfarming/boost/BoostManager.java b/src/main/java/com/songoda/epicfarming/boost/BoostManager.java index c4ccbee..641dfc5 100644 --- a/src/main/java/com/songoda/epicfarming/boost/BoostManager.java +++ b/src/main/java/com/songoda/epicfarming/boost/BoostManager.java @@ -35,7 +35,7 @@ public class BoostManager { for (BoostData boostData : this.registeredBoosts) { if (boostData.getPlayer().toString().equals(player.toString())) { if (System.currentTimeMillis() >= boostData.getEndTime()) { - EpicFarming.getPlugin(EpicFarming.class).getDataManager().deleteBoost(boostData); + EpicFarming.getPlugin(EpicFarming.class).getDataManager().delete(boostData); removeBoostFromPlayer(boostData); } return boostData; diff --git a/src/main/java/com/songoda/epicfarming/commands/CommandBoost.java b/src/main/java/com/songoda/epicfarming/commands/CommandBoost.java index c983aa1..61ad0db 100644 --- a/src/main/java/com/songoda/epicfarming/commands/CommandBoost.java +++ b/src/main/java/com/songoda/epicfarming/commands/CommandBoost.java @@ -48,7 +48,7 @@ public class CommandBoost extends AbstractCommand { } BoostData boostData = new BoostData(Integer.parseInt(args[1]), duration == 0L ? Long.MAX_VALUE : System.currentTimeMillis() + duration, player.getUniqueId()); - this.plugin.getDataManager().createBoost(boostData); + this.plugin.getDataManager().save(boostData); this.plugin.getBoostManager().addBoostToPlayer(boostData); this.plugin.getLocale().newMessage("&7Successfully boosted &6" + Bukkit.getPlayer(args[0]).getName() + "'s &7farms by &6" + args[1] + "x" + (duration == 0L ? "" : (" for " + TimeUtils.makeReadable(duration))) + "&7.") diff --git a/src/main/java/com/songoda/epicfarming/database/DataManager.java b/src/main/java/com/songoda/epicfarming/database/DataManager.java deleted file mode 100644 index 80b6f5b..0000000 --- a/src/main/java/com/songoda/epicfarming/database/DataManager.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.songoda.epicfarming.database; - -import com.craftaro.core.database.DataManagerAbstract; -import com.craftaro.core.database.DatabaseConnector; -import com.craftaro.core.utils.ItemSerializer; -import com.songoda.epicfarming.EpicFarming; -import com.songoda.epicfarming.boost.BoostData; -import com.songoda.epicfarming.farming.Farm; -import com.songoda.epicfarming.farming.FarmType; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.Plugin; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Consumer; - -public class DataManager extends DataManagerAbstract { - public DataManager(DatabaseConnector connector, Plugin plugin) { - super(connector, plugin); - } - - public void createBoost(BoostData boostData) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String createBoostedPlayer = "INSERT INTO " + this.getTablePrefix() + "boosted_players (player, multiplier, end_time) VALUES (?, ?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createBoostedPlayer)) { - statement.setString(1, boostData.getPlayer().toString()); - statement.setInt(2, boostData.getMultiplier()); - statement.setLong(3, boostData.getEndTime()); - statement.executeUpdate(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - public void getBoosts(Consumer> callback) { - List boosts = new ArrayList<>(); - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - Statement statement = connection.createStatement(); - String selectBoostedPlayers = "SELECT * FROM " + this.getTablePrefix() + "boosted_players"; - ResultSet result = statement.executeQuery(selectBoostedPlayers); - while (result.next()) { - UUID player = UUID.fromString(result.getString("player")); - int multiplier = result.getInt("multiplier"); - long endTime = result.getLong("end_time"); - boosts.add(new BoostData(multiplier, endTime, player)); - } - - this.sync(() -> callback.accept(boosts)); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - public void deleteBoost(BoostData boostData) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String deleteBoost = "DELETE FROM " + this.getTablePrefix() + "boosted_players WHERE end_time = ?"; - PreparedStatement statement = connection.prepareStatement(deleteBoost); - statement.setLong(1, boostData.getEndTime()); - statement.executeUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - public void createFarm(Farm farm) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String createFarm = "INSERT INTO " + this.getTablePrefix() + "active_farms (farm_type, level, placed_by, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createFarm)) { - statement.setString(1, farm.getFarmType().name()); - statement.setInt(2, farm.getLevel().getLevel()); - statement.setString(3, farm.getPlacedBy().toString()); - statement.setString(4, farm.getLocation().getWorld().getName()); - statement.setInt(5, farm.getLocation().getBlockX()); - statement.setInt(6, farm.getLocation().getBlockY()); - statement.setInt(7, farm.getLocation().getBlockZ()); - - statement.executeUpdate(); - } - - int farmId = this.lastInsertedId(connection, "active_farms"); - farm.setId(farmId); - - String createItem = "INSERT INTO " + this.getTablePrefix() + "items (farm_id, item) VALUES (?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createItem)) { - for (ItemStack item : farm.getItems().toArray(new ItemStack[0])) { - statement.setInt(1, farm.getId()); - statement.setBytes(2, ItemSerializer.serializeItem(item)); - statement.addBatch(); - } - statement.executeBatch(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - public void createFarms(List farms) { - for (Farm farm : farms) { - createFarm(farm); - } - } - - public void updateFarm(Farm farm) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String updateFarm = "UPDATE " + this.getTablePrefix() + "active_farms SET level = ?, farm_type = ? WHERE id = ?"; - PreparedStatement statement = connection.prepareStatement(updateFarm); - statement.setInt(1, farm.getLevel().getLevel()); - statement.setString(2, farm.getFarmType().name()); - statement.setInt(3, farm.getId()); - statement.executeUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - public void deleteFarm(Farm farm) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String deleteFarm = "DELETE FROM " + this.getTablePrefix() + "active_farms WHERE id = ?"; - try (PreparedStatement statement = connection.prepareStatement(deleteFarm)) { - statement.setInt(1, farm.getId()); - statement.executeUpdate(); - } - - String deleteItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE farm_id = ?"; - try (PreparedStatement statement = connection.prepareStatement(deleteItems)) { - statement.setInt(1, farm.getId()); - statement.executeUpdate(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - public void updateItemsAsync(Farm farm) { - this.runAsync(() -> updateItems(farm)); - } - - public void updateItems(Farm farm) { - try (Connection connection = this.databaseConnector.getConnection()) { - String deleteItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE farm_id = ?"; - try (PreparedStatement statement = connection.prepareStatement(deleteItems)) { - statement.setInt(1, farm.getId()); - statement.executeUpdate(); - } - - String createItem = "INSERT INTO " + this.getTablePrefix() + "items (farm_id, item) VALUES (?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createItem)) { - for (ItemStack item : farm.getItems().toArray(new ItemStack[0])) { - statement.setInt(1, farm.getId()); - statement.setBytes(2, ItemSerializer.serializeItem(item)); - - statement.addBatch(); - } - statement.executeBatch(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - farm.setNeedsToBeSaved(false); - } - - public void getFarms(Consumer> callback) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - Map farms = new HashMap<>(); - try (Statement statement = connection.createStatement()) { - String selectFarms = "SELECT * FROM " + this.getTablePrefix() + "active_farms"; - ResultSet result = statement.executeQuery(selectFarms); - while (result.next()) { - World world = Bukkit.getWorld(result.getString("world")); - - if (world == null) { - continue; - } - - int id = result.getInt("id"); - int level = result.getInt("level"); - - String placedByStr = result.getString("placed_by"); - UUID placedBy = placedByStr == null ? null : UUID.fromString(result.getString("placed_by")); - - FarmType farmType = FarmType.valueOf(result.getString("farm_type")); - - int x = result.getInt("x"); - int y = result.getInt("y"); - int z = result.getInt("z"); - Location location = new Location(world, x, y, z); - - Farm farm = new Farm(location, EpicFarming.getInstance().getLevelManager().getLevel(level), placedBy); - farm.setId(id); - farm.setFarmType(farmType); - - farms.put(id, farm); - } - } - - try (Statement statement = connection.createStatement()) { - String selectItems = "SELECT * FROM " + this.getTablePrefix() + "items"; - ResultSet result = statement.executeQuery(selectItems); - while (result.next()) { - int id = result.getInt("farm_id"); - ItemStack item = ItemSerializer.deserializeItem(result.getBytes("item")); - - Farm farm = farms.get(id); - if (farm == null) { - break; - } - - if (item != null) { - farm.addItem(item); - } - } - } - this.sync(() -> callback.accept(farms)); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } -} diff --git a/src/main/java/com/songoda/epicfarming/database/migrations/_1_InitialMigration.java b/src/main/java/com/songoda/epicfarming/database/migrations/_1_InitialMigration.java index a35c198..c8bc316 100644 --- a/src/main/java/com/songoda/epicfarming/database/migrations/_1_InitialMigration.java +++ b/src/main/java/com/songoda/epicfarming/database/migrations/_1_InitialMigration.java @@ -1,6 +1,7 @@ package com.songoda.epicfarming.database.migrations; import com.craftaro.core.database.DataMigration; +import com.craftaro.core.database.DatabaseConnector; import com.craftaro.core.database.MySQLConnector; import com.songoda.epicfarming.EpicFarming; @@ -14,11 +15,11 @@ public class _1_InitialMigration extends DataMigration { } @Override - public void migrate(Connection connection, String tablePrefix) throws SQLException { + public void migrate(DatabaseConnector databaseConnector, String tablePrefix) throws SQLException { String autoIncrement = EpicFarming.getPlugin(EpicFarming.class).getDatabaseConnector() instanceof MySQLConnector ? " AUTO_INCREMENT" : ""; // Create farms table. - try (Statement statement = connection.createStatement()) { + try (Statement statement = databaseConnector.getConnection().createStatement()) { statement.execute("CREATE TABLE " + tablePrefix + "active_farms (" + "id INTEGER PRIMARY KEY" + autoIncrement + ", " + "farm_type TEXT NOT NULL, " + @@ -34,7 +35,7 @@ public class _1_InitialMigration extends DataMigration { // Create items. // Items are stored as Base64. Dunno if this is the most efficient way to // store them, though. - try (Statement statement = connection.createStatement()) { + try (Statement statement = databaseConnector.getConnection().createStatement()) { statement.execute("CREATE TABLE " + tablePrefix + "items (" + "farm_id INTEGER NOT NULL, " + "item VARBINARY(999) NOT NULL" + @@ -42,7 +43,7 @@ public class _1_InitialMigration extends DataMigration { } // Create player boosts - try (Statement statement = connection.createStatement()) { + try (Statement statement = databaseConnector.getConnection().createStatement()) { statement.execute("CREATE TABLE " + tablePrefix + "boosted_players (" + "player VARCHAR(36) NOT NULL, " + "multiplier INTEGER NOT NULL," + diff --git a/src/main/java/com/songoda/epicfarming/farming/Farm.java b/src/main/java/com/songoda/epicfarming/farming/Farm.java index e62d3ce..e71ce27 100644 --- a/src/main/java/com/songoda/epicfarming/farming/Farm.java +++ b/src/main/java/com/songoda/epicfarming/farming/Farm.java @@ -2,6 +2,8 @@ package com.songoda.epicfarming.farming; import com.craftaro.core.compatibility.CompatibleMaterial; import com.craftaro.core.compatibility.CompatibleParticleHandler; +import com.craftaro.core.database.Data; +import com.craftaro.core.database.SerializedLocation; import com.craftaro.core.hooks.EconomyManager; import com.craftaro.core.hooks.ProtectionManager; import com.craftaro.core.third_party.com.cryptomorin.xseries.XBlock; @@ -28,13 +30,13 @@ import java.util.Map; import java.util.Random; import java.util.UUID; -public class Farm { +public class Farm implements Data { // This is the unique identifier for this farm. // It is reset on every plugin load. private final UUID uniqueId = UUID.randomUUID(); // Id for database usage. - private int id; + private final int id; private boolean needsToBeSaved = false; @@ -52,10 +54,35 @@ public class Farm { private final Map moduleCache = new HashMap<>(); - public Farm(Location location, Level level, UUID placedBy) { + /** + * This is the constructor for a new farm. + * It is used when a player places a new farm. + * + * @param location The location of the farm. + * @param level The level of the farm. + * @param placedBy The player who placed the farm. + * @param farmType The type of farm. + */ + public Farm(Location location, Level level, UUID placedBy, FarmType farmType) { + this(EpicFarming.getPlugin(EpicFarming.class).getDataManager().getNextId("active_farms"), location, level, placedBy, farmType); + } + + /** + * This is the constructor for a new farm. + * It is used when we load a farm from the database. + * + * @param id The id of the farm. + * @param location The location of the farm. + * @param level The level of the farm. + * @param placedBy The player who placed the farm. + * @param farmType The type of farm. + */ + public Farm(int id, Location location, Level level, UUID placedBy, FarmType farmType) { + this.id = id; this.location = location; this.level = level; this.placedBy = placedBy; + this.farmType = farmType; } public void view(Player player, boolean force) { @@ -123,7 +150,7 @@ public class Farm { private void upgradeFinal(Level level, Player player) { EpicFarming instance = EpicFarming.getInstance(); this.level = level; - instance.getDataManager().updateFarm(this); + instance.getDataManager().save(this); if (instance.getLevelManager().getHighestLevel() != level) { instance.getLocale().getMessage("event.upgrade.success") .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); @@ -181,10 +208,42 @@ public class Farm { return false; } - public UUID getUniqueId() { + //Don't use getUniqueId here as it conflicts with the Data interface. + public UUID getFarmUUID() { return this.uniqueId; } + @Override + public int getId() { + return this.id; + } + + @Override + public Map serialize() { + Map map = new HashMap<>(); + map.put("id", this.id); + map.put("farm_type", this.farmType.name()); + map.put("level", this.level.getLevel()); + map.put("placed_by", this.placedBy.toString()); + map.putAll(SerializedLocation.of(this.location)); + return map; + } + + @Override + public Data deserialize(Map map) { + int id = (int) map.get("id"); + FarmType farmType = FarmType.valueOf((String) map.get("farm_type")); + Level level = EpicFarming.getPlugin(EpicFarming.class).getLevelManager().getLevel((int) map.get("level")); + UUID placedBy = UUID.fromString((String) map.get("placed_by")); + Location location = SerializedLocation.of(map); + return new Farm(id, location, level, placedBy, farmType); + } + + @Override + public String getTableName() { + return "active_farms"; + } + public List getItems() { return Collections.unmodifiableList(this.items); } @@ -352,20 +411,12 @@ public class Farm { this.farmType = FarmType.CROPS; break; } - EpicFarming.getInstance().getDataManager().updateFarm(this); + EpicFarming.getInstance().getDataManager().save(this); } public void setFarmType(FarmType farmType) { this.farmType = farmType; - EpicFarming.getInstance().getDataManager().updateFarm(this); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; + EpicFarming.getInstance().getDataManager().save(this); } public boolean needsToBeSaved() { diff --git a/src/main/java/com/songoda/epicfarming/listeners/BlockListeners.java b/src/main/java/com/songoda/epicfarming/listeners/BlockListeners.java index 936d418..916cd7f 100644 --- a/src/main/java/com/songoda/epicfarming/listeners/BlockListeners.java +++ b/src/main/java/com/songoda/epicfarming/listeners/BlockListeners.java @@ -99,9 +99,9 @@ public class BlockListeners implements Listener { return; } - Farm farm = new Farm(location, this.plugin.getLevelManager().getLevel(level == 0 ? 1 : level), e.getPlayer().getUniqueId()); + Farm farm = new Farm(location, this.plugin.getLevelManager().getLevel(level == 0 ? 1 : level), e.getPlayer().getUniqueId(), FarmType.CROPS); //TODO check if the FarmType is correct this.plugin.getFarmManager().addFarm(location, farm); - this.plugin.getDataManager().createFarm(farm); + this.plugin.getDataManager().save(farm); farm.tillLand(); }, 1); @@ -118,7 +118,7 @@ public class BlockListeners implements Listener { return; } - this.plugin.getDataManager().deleteFarm(farm); + this.plugin.getDataManager().delete(farm); farm.forceMenuClose(); this.plugin.getFarmTask().getCrops(farm, false); @@ -150,7 +150,7 @@ public class BlockListeners implements Listener { } this.plugin.getFarmTask().getCrops(farm, false); - this.plugin.getDataManager().deleteFarm(farm); + this.plugin.getDataManager().delete(farm); farm.forceMenuClose(); event.setCancelled(true); diff --git a/src/main/java/com/songoda/epicfarming/listeners/EntityListeners.java b/src/main/java/com/songoda/epicfarming/listeners/EntityListeners.java index 7d4fa33..23d833a 100644 --- a/src/main/java/com/songoda/epicfarming/listeners/EntityListeners.java +++ b/src/main/java/com/songoda/epicfarming/listeners/EntityListeners.java @@ -121,7 +121,7 @@ public class EntityListeners implements Listener { event.blockList().remove(block); Farm farm = this.plugin.getFarmManager().removeFarm(block.getLocation()); - this.plugin.getDataManager().deleteFarm(farm); + this.plugin.getDataManager().delete(farm); farm.forceMenuClose(); this.plugin.getFarmTask().getCrops(farm, false); diff --git a/src/main/java/com/songoda/epicfarming/tasks/FarmTask.java b/src/main/java/com/songoda/epicfarming/tasks/FarmTask.java index b1754a3..4c5c6a0 100644 --- a/src/main/java/com/songoda/epicfarming/tasks/FarmTask.java +++ b/src/main/java/com/songoda/epicfarming/tasks/FarmTask.java @@ -99,13 +99,13 @@ public class FarmTask extends BukkitRunnable { double radius = farm.getLevel().getRadius() + .5; Bukkit.getScheduler().runTask(this.plugin, () -> { - this.entityCache.remove(farm.getUniqueId()); - this.entityCache.put(farm.getUniqueId(), this.plugin.getEntityUtils().getNearbyEntities(location, radius, false) + this.entityCache.remove(farm.getFarmUUID()); + this.entityCache.put(farm.getFarmUUID(), this.plugin.getEntityUtils().getNearbyEntities(location, radius, false) .stream().filter(e -> !(e instanceof Player) && e != null && !(e instanceof ArmorStand)) .collect(Collectors.toCollection(ArrayList::new))); }); - Collection entitiesAroundFarm = this.entityCache.get(farm.getUniqueId()); + Collection entitiesAroundFarm = this.entityCache.get(farm.getFarmUUID()); if (entitiesAroundFarm == null) { continue; diff --git a/src/main/java/com/songoda/epicfarming/utils/DataHelper.java b/src/main/java/com/songoda/epicfarming/utils/DataHelper.java new file mode 100644 index 0000000..8138b18 --- /dev/null +++ b/src/main/java/com/songoda/epicfarming/utils/DataHelper.java @@ -0,0 +1,65 @@ +package com.songoda.epicfarming.utils; + +import com.craftaro.core.third_party.org.jooq.Query; +import com.craftaro.core.third_party.org.jooq.impl.DSL; +import com.craftaro.core.utils.ItemSerializer; +import com.songoda.epicfarming.EpicFarming; +import com.songoda.epicfarming.farming.Farm; +import org.bukkit.inventory.ItemStack; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.ArrayList; +import java.util.List; + +public class DataHelper { + + private static final EpicFarming plugin = EpicFarming.getPlugin(EpicFarming.class); + + public static void createFarms(List farms) { + + plugin.getDatabaseConnector().connectDSL(dslContext -> { + List queries = new ArrayList<>(); + for (Farm farm : farms) { + queries.add(dslContext.insertInto(DSL.table(plugin.getDataManager().getTablePrefix() + "active_farms")) + .columns(DSL.field("farm_type"), + DSL.field("level"), + DSL.field("placed_by"), + DSL.field("world"), + DSL.field("x"), + DSL.field("y"), + DSL.field("z")) + .values(farm.getFarmType().name(), + farm.getLevel().getLevel(), + farm.getPlacedBy().toString(), + farm.getLocation().getWorld().getName(), + farm.getLocation().getBlockX(), + farm.getLocation().getBlockY(), + farm.getLocation().getBlockZ())); + } + dslContext.batch(queries).execute(); + }); + } + + public static void updateItemsAsync(Farm farm) { + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> updateItems(farm)); + } + + public static void updateItems(Farm farm) { + String tablePrefix = plugin.getDataManager().getTablePrefix(); + + plugin.getDatabaseConnector().connectDSL(dslContext -> { + dslContext.deleteFrom(DSL.table(tablePrefix + "items")) + .where(DSL.field("farm_id").eq(farm.getId())) + .execute(); + + List queries = new ArrayList<>(); + for (int i = 0; i < farm.getItems().size(); i++) { + queries.add(dslContext.insertInto(DSL.table(tablePrefix + "items")) + .columns(DSL.field("farm_id"), DSL.field("item")) + .values(farm.getId(), ItemSerializer.serializeItem(farm.getItems().get(i)))); + } + dslContext.batch(queries).execute(); + }); + } +}