Updates to new database system

This commit is contained in:
ceze88 2023-07-01 10:41:18 +02:00
parent 95a4110ae4
commit d41670d212
11 changed files with 182 additions and 323 deletions

View File

@ -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();
}
/**

View File

@ -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<String, Object> serialize() {
Map<String, Object> 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<String, Object> 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";
}
}

View File

@ -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;

View File

@ -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.")

View File

@ -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<List<BoostData>> callback) {
List<BoostData> 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<Farm> 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<Map<Integer, Farm>> callback) {
this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()) {
Map<Integer, Farm> 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();
}
});
}
}

View File

@ -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," +

View File

@ -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<String, Object> 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<String, Object> serialize() {
Map<String, Object> 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<String, Object> 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<ItemStack> 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() {

View File

@ -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);

View File

@ -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);

View File

@ -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<LivingEntity> entitiesAroundFarm = this.entityCache.get(farm.getUniqueId());
Collection<LivingEntity> entitiesAroundFarm = this.entityCache.get(farm.getFarmUUID());
if (entitiesAroundFarm == null) {
continue;

View File

@ -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<Farm> farms) {
plugin.getDatabaseConnector().connectDSL(dslContext -> {
List<Query> 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<Query> 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();
});
}
}