diff --git a/EpicHoppers-API/pom.xml b/EpicHoppers-API/pom.xml index 2ad216f..deb0feb 100644 --- a/EpicHoppers-API/pom.xml +++ b/EpicHoppers-API/pom.xml @@ -7,10 +7,11 @@ com.craftaro EpicHoppers-Parent - 5.0.0-SNAPSHOT + 5.0.0-SNAPSHOT-b5 ../pom.xml EpicHoppers-API + 1.0.0-SNAPSHOT diff --git a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/EpicHoppersApi.java b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/EpicHoppersApi.java index f99a3ab..e133db7 100644 --- a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/EpicHoppersApi.java +++ b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/EpicHoppersApi.java @@ -1,8 +1,8 @@ package com.craftaro.epichoppers; +import com.craftaro.core.database.DataManager; import com.craftaro.epichoppers.boost.BoostManager; import com.craftaro.epichoppers.containers.ContainerManager; -import com.craftaro.epichoppers.database.DataManager; import com.craftaro.epichoppers.hopper.teleport.TeleportHandler; import com.craftaro.epichoppers.player.PlayerDataManager; import com.craftaro.epichoppers.hopper.levels.LevelManager; @@ -16,20 +16,16 @@ public class EpicHoppersApi { private final ContainerManager containerManager; private final TeleportHandler teleportHandler; private final PlayerDataManager playerDataManager; - private final DataManager dataManager; - private EpicHoppersApi(LevelManager levelManager, BoostManager boostManager, ContainerManager containerManager, TeleportHandler teleportHandler, - PlayerDataManager playerDataManager, - DataManager dataManager) { + PlayerDataManager playerDataManager) { this.levelManager = levelManager; this.boostManager = boostManager; this.containerManager = containerManager; this.teleportHandler = teleportHandler; this.playerDataManager = playerDataManager; - this.dataManager = dataManager; } public LevelManager getLevelManager() { @@ -52,22 +48,14 @@ public PlayerDataManager getPlayerDataManager() { return this.playerDataManager; } - /** - * TODO: The DataManager probably shouldn't be exposed to the API. - */ - @ApiStatus.Internal - public DataManager getDataManager() { - return this.dataManager; - } - public static EpicHoppersApi getApi() { return instance; } - static void initApi(LevelManager levelManager, BoostManager boostManager, ContainerManager containerManager, TeleportHandler teleportHandler, PlayerDataManager playerDataManager, DataManager dataManager) { + static void initApi(LevelManager levelManager, BoostManager boostManager, ContainerManager containerManager, TeleportHandler teleportHandler, PlayerDataManager playerDataManager) { if (instance != null) { throw new IllegalStateException(EpicHoppersApi.class.getSimpleName() + " already initialized"); } - instance = new EpicHoppersApi(levelManager, boostManager, containerManager, teleportHandler, playerDataManager, dataManager); + instance = new EpicHoppersApi(levelManager, boostManager, containerManager, teleportHandler, playerDataManager); } } diff --git a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/boost/BoostData.java b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/boost/BoostData.java index 7011c45..f472a6a 100644 --- a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/boost/BoostData.java +++ b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/boost/BoostData.java @@ -3,52 +3,23 @@ import java.util.Objects; import java.util.UUID; -public class BoostData { - private final int multiplier; - private final long endTime; - private final UUID player; - - public BoostData(int multiplier, long endTime, UUID player) { - this.multiplier = multiplier; - this.endTime = endTime; - this.player = player; - } - - public int getMultiplier() { - return this.multiplier; - } - - public UUID getPlayer() { - return this.player; - } - - public long getEndTime() { - return this.endTime; - } - - @Override - public int hashCode() { - int result = 31 * this.multiplier; - - result = 31 * result + (this.player == null ? 0 : this.player.hashCode()); - result = 31 * result + (int) (this.endTime ^ (this.endTime >>> 32)); - - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof BoostData)) { - return false; - } - - BoostData other = (BoostData) obj; - return this.multiplier == other.multiplier && - this.endTime == other.endTime && - Objects.equals(this.player, other.player); - } - +public interface BoostData { + + /** + * Gets the multiplier of the boost + * @return The multiplier + */ + int getMultiplier(); + + /** + * Gets the player's uuid who has the boost + * @return The player's uuid + */ + public UUID getPlayer(); + + /** + * Gets the end time of the boost + * @return The end time + */ + public long getEndTime(); } diff --git a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/database/DataManager.java b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/database/DataManager.java deleted file mode 100644 index c6a0552..0000000 --- a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/database/DataManager.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.craftaro.epichoppers.database; - -import com.craftaro.epichoppers.boost.BoostData; -import com.craftaro.epichoppers.hopper.Hopper; -import com.craftaro.epichoppers.hopper.ItemType; -import com.craftaro.epichoppers.hopper.LinkType; -import org.bukkit.Location; -import org.bukkit.inventory.ItemStack; - -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; - -public interface DataManager { - void createBoost(BoostData boostData); - - void getBoosts(Consumer> callback); - - void deleteBoost(BoostData boostData); - - void createLink(Hopper hopper, Location location, LinkType type); - - void updateItems(Hopper hopper, ItemType type, List items); - - void deleteLink(Hopper hopper, Location location); - - void deleteLinks(Hopper hopper); - - void createHoppers(List hoppers); - - void createHopper(Hopper hopper); - - void updateHopper(Hopper hopper); - - void deleteHopper(Hopper hopper); - - void getHoppers(Consumer> callback); -} diff --git a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/hopper/Hopper.java b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/hopper/Hopper.java index 5142a23..5835cf5 100644 --- a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/hopper/Hopper.java +++ b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/hopper/Hopper.java @@ -1,410 +1,57 @@ package com.craftaro.epichoppers.hopper; -import com.craftaro.core.SongodaPlugin; -import com.craftaro.core.compatibility.CompatibleParticleHandler; -import com.craftaro.core.compatibility.ServerVersion; -import com.craftaro.core.hooks.EconomyManager; -import com.craftaro.core.third_party.com.cryptomorin.xseries.XSound; -import com.craftaro.epichoppers.EpicHoppersApi; -import com.craftaro.epichoppers.api.events.HopperAccessEvent; -import com.craftaro.epichoppers.database.DataManager; +import com.craftaro.core.database.Data; import com.craftaro.epichoppers.hopper.levels.Level; -import com.craftaro.epichoppers.hopper.levels.LevelManager; -import com.craftaro.epichoppers.player.PlayerData; -import com.craftaro.epichoppers.player.PlayerDataManager; -import com.craftaro.epichoppers.utils.CostType; -import com.craftaro.epichoppers.utils.Methods; import com.craftaro.epichoppers.hopper.teleport.TeleportTrigger; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.InventoryHolder; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.UUID; -/** - * FIXME: Needs heavy refactoring to only have one responsibility. - */ -public class Hopper { - // Id for database use. - private int id; +public interface Hopper extends Data { - private final Location location; - private Level level = getLevelManager().getLowestLevel(); - private UUID lastPlayerOpened = null; - private UUID placedBy = null; - private final List linkedBlocks = new ArrayList<>(); - private Filter filter = new Filter(); - private TeleportTrigger teleportTrigger = TeleportTrigger.DISABLED; - private int transferTick = 0; + Location getLocation(); - private int syncId = -1; + Block getBlock(); - private Player activePlayer; + Level getLevel(); - private final Map moduleCache = new HashMap<>(); + void setLevel(Level level); - public Hopper(Location location) { - this.location = location; - } + @Nullable UUID getLastPlayerOpened(); - @ApiStatus.Internal - public boolean prepareForOpeningOverviewGui(Player player) { - if (this.lastPlayerOpened != null && - this.lastPlayerOpened != player.getUniqueId() && - Bukkit.getPlayer(this.lastPlayerOpened) != null) { - Bukkit.getPlayer(this.lastPlayerOpened).closeInventory(); - } + @Nullable UUID getPlacedBy(); - HopperAccessEvent accessEvent = new HopperAccessEvent(player, this); - Bukkit.getPluginManager().callEvent(accessEvent); - if (accessEvent.isCancelled()) { - return false; - } + void setPlacedBy(UUID placedBy); - if (this.placedBy == null) { - this.placedBy = player.getUniqueId(); - } + void setLastPlayerOpened(UUID lastPlayerOpened); - if (!player.hasPermission("epichoppers.overview")) { - return false; - } + TeleportTrigger getTeleportTrigger(); - setActivePlayer(player); - return true; - } + void setTeleportTrigger(TeleportTrigger teleportTrigger); - @ApiStatus.Internal - public void forceClose() { - if (this.activePlayer != null) { - this.activePlayer.closeInventory(); - } - } + List getLinkedBlocks(); - public void dropItems() { - Inventory inventory = ((InventoryHolder) this.location.getBlock().getState()).getInventory(); - World world = this.location.getWorld(); + void addLinkedBlock(Location location, LinkType type); - for (ItemStack itemStack : inventory.getContents()) { - if (itemStack == null || itemStack.getType() == Material.AIR) { - continue; - } + void removeLinkedBlock(Location location); - world.dropItemNaturally(this.location, itemStack); - } - } + void clearLinkedBlocks(); - public void upgrade(Player player, CostType type) { - if (!getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) { - return; - } + Filter getFilter(); - Level level = getLevelManager().getLevel(this.level.getLevel() + 1); - int cost = type == CostType.ECONOMY ? level.getCostEconomy() : level.getCostExperience(); + void setActivePlayer(Player activePlayer); - if (type == CostType.ECONOMY) { - if (!EconomyManager.isEnabled()) { - player.sendMessage("Economy not enabled."); - return; - } - if (!EconomyManager.hasBalance(player, cost)) { - getPlugin().getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player); - return; - } - EconomyManager.withdrawBalance(player, cost); - upgradeFinal(level, player); - } else if (type == CostType.EXPERIENCE) { - if (player.getLevel() >= cost || player.getGameMode() == GameMode.CREATIVE) { - if (player.getGameMode() != GameMode.CREATIVE) { - player.setLevel(player.getLevel() - cost); - } - upgradeFinal(level, player); - } else { - getPlugin().getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player); - } - } - } + void timeout(Player player); - private void upgradeFinal(Level level, Player player) { - this.level = level; - getDataManager().updateHopper(this); - syncName(); - if (getLevelManager().getHighestLevel() != level) { - getPlugin().getLocale().getMessage("event.upgrade.success") - .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); - } else { - getPlugin().getLocale().getMessage("event.upgrade.maxed") - .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); - } - Location loc = this.location.clone().add(.5, .5, .5); + void addDataToModuleCache(String s, Object value); - if (!getUpgradeParticleType().trim().isEmpty()) { - CompatibleParticleHandler.spawnParticles( - CompatibleParticleHandler.ParticleType.getParticle(getUpgradeParticleType()), - loc, 100, .5, .5, .5); - } + boolean isDataCachedInModuleCache(String cacheStr); - if (getLevelManager().getHighestLevel() != level) { - XSound.ENTITY_PLAYER_LEVELUP.play(player, .6f, 15); - } else { - XSound.ENTITY_PLAYER_LEVELUP.play(player, 2, 25); - XSound.BLOCK_NOTE_BLOCK_CHIME.play(player, 2, 25); - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> XSound.BLOCK_NOTE_BLOCK_CHIME.play(player, 1.2f, 35), 5); - Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> XSound.BLOCK_NOTE_BLOCK_CHIME.play(player, 1.8f, 35), 10); - } - } + Object getDataFromModuleCache(String cacheStr); - private void syncName() { - org.bukkit.block.Hopper hopper = (org.bukkit.block.Hopper) this.location.getBlock().getState(); - if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_10)) { - hopper.setCustomName(Methods.formatName(this.level.getLevel())); - } - hopper.update(true); - } - - public void timeout(Player player) { - this.syncId = Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> { - PlayerData playerData = getPlayerDataManager().getPlayerData(player); - if (playerData.getSyncType() != null && playerData.getLastHopper() == this) { - getPlugin().getLocale().getMessage("event.hopper.synctimeout").sendPrefixedMessage(player); - playerData.setSyncType(null); - } - }, getLinkTimeoutFromPluginConfig() * this.level.getLinkAmount()); - } - - public void link(Block toLink, boolean filtered, Player player) { - if (this.location.getWorld().equals(toLink.getLocation().getWorld()) - && !player.hasPermission("EpicHoppers.Override") - && !player.hasPermission("EpicHoppers.Admin") - && this.location.distance(toLink.getLocation()) > this.level.getRange()) { - getPlugin().getLocale().getMessage("event.hopper.syncoutofrange").sendPrefixedMessage(player); - return; - } - - if (this.linkedBlocks.contains(toLink.getLocation())) { - getPlugin().getLocale().getMessage("event.hopper.already").sendPrefixedMessage(player); - return; - } - - if (!filtered) { - this.linkedBlocks.add(toLink.getLocation()); - getDataManager().createLink(this, toLink.getLocation(), LinkType.REGULAR); - } else { - this.filter.setEndPoint(toLink.getLocation()); - getDataManager().createLink(this, toLink.getLocation(), LinkType.REJECT); - getPlugin().getLocale().getMessage("event.hopper.syncsuccess").sendPrefixedMessage(player); - getPlayerDataManager().getPlayerData(player).setSyncType(null); - return; - } - this.lastPlayerOpened = player.getUniqueId(); - - if (this.level.getLinkAmount() > 1) { - if (this.linkedBlocks.size() >= this.level.getLinkAmount()) { - getPlugin().getLocale().getMessage("event.hopper.syncdone").sendPrefixedMessage(player); - cancelSync(player); - return; - } - getPlugin().getLocale().getMessage("event.hopper.syncsuccessmore") - .processPlaceholder("amount", this.level.getLinkAmount() - this.linkedBlocks.size()) - .sendPrefixedMessage(player); - return; - } - getPlugin().getLocale().getMessage("event.hopper.syncsuccess").sendPrefixedMessage(player); - cancelSync(player); - } - - /** - * Ticks a hopper to determine when it can transfer items next - * - * @param maxTick The maximum amount the hopper can be ticked before next transferring items - * @param allowLooping If true, the hopper is allowed to transfer items if the tick is also valid - * @return true if the hopper should transfer an item, otherwise false - */ - public boolean tryTick(int maxTick, boolean allowLooping) { - this.transferTick++; - if (this.transferTick >= maxTick) { - if (allowLooping) { - this.transferTick = 0; - return true; - } else { - this.transferTick = maxTick; - } - } - return false; - } - - public Location getLocation() { - return this.location.clone(); - } - - public Block getBlock() { - return this.location.getBlock(); - } - - public World getWorld() { - return this.location.getWorld(); - } - - public int getX() { - return this.location.getBlockX(); - } - - public int getY() { - return this.location.getBlockY(); - } - - public int getZ() { - return this.location.getBlockZ(); - } - - public Level getLevel() { - return this.level; - } - - public void setLevel(Level level) { - this.level = level; - } - - public UUID getPlacedBy() { - return this.placedBy; - } - - public void setPlacedBy(UUID placedBy) { - this.placedBy = placedBy; - } - - public UUID getLastPlayerOpened() { - return this.lastPlayerOpened; - } - - public void setLastPlayerOpened(UUID uuid) { - this.lastPlayerOpened = uuid; - } - - public TeleportTrigger getTeleportTrigger() { - return this.teleportTrigger; - } - - public void setTeleportTrigger(TeleportTrigger teleportTrigger) { - this.teleportTrigger = teleportTrigger; - } - - public List getLinkedBlocks() { - return new ArrayList<>(this.linkedBlocks); - } - - public void addLinkedBlock(Location location, LinkType type) { - if (type == LinkType.REGULAR) { - this.linkedBlocks.add(location); - } else { - this.filter.setEndPoint(location); - } - } - - public void removeLinkedBlock(Location location) { - this.linkedBlocks.remove(location); - } - - public void clearLinkedBlocks() { - this.linkedBlocks.clear(); - } - - public Filter getFilter() { - return this.filter; - } - - public void setFilter(Filter filter) { - this.filter = filter; - } - - public Object getDataFromModuleCache(String key) { - return this.moduleCache.getOrDefault(key, null); - } - - public void addDataToModuleCache(String key, Object data) { - this.moduleCache.put(key, data); - } - - public boolean isDataCachedInModuleCache(String key) { - return this.moduleCache.containsKey(key); - } - - public void removeDataFromModuleCache(String key) { - this.moduleCache.remove(key); - } - - public void clearModuleCache() { - this.moduleCache.clear(); - } - - public void cancelSync(Player player) { - Bukkit.getScheduler().cancelTask(this.syncId); - getPlayerDataManager().getPlayerData(player).setSyncType(null); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public Player getActivePlayer() { - return this.activePlayer; - } - - public void setActivePlayer(Player activePlayer) { - this.activePlayer = activePlayer; - } - - private LevelManager getLevelManager() { - return EpicHoppersApi.getApi().getLevelManager(); - } - - private PlayerDataManager getPlayerDataManager() { - return EpicHoppersApi.getApi().getPlayerDataManager(); - } - - private DataManager getDataManager() { - return EpicHoppersApi.getApi().getDataManager(); - } - - /** - * @deprecated The class needs refactoring to not even need the plugin. - * This is just a temporary workaround to get a Minecraft 1.20-beta build ready - */ - @Deprecated - private long getLinkTimeoutFromPluginConfig() { - return getPlugin().getConfig().getLong("Main.Timeout When Syncing Hoppers"); - } - - /** - * @deprecated The class needs refactoring to not even need the plugin. - * This is just a temporary workaround to get a Minecraft 1.20-beta build ready - */ - @Deprecated - private String getUpgradeParticleType() { - return getPlugin().getConfig().getString("Main.Upgrade Particle Type"); - } - - /** - * @deprecated The class needs refactoring to not even need the plugin. - * This is just a temporary workaround to get a Minecraft 1.20-beta build ready - */ - @Deprecated - private SongodaPlugin getPlugin() { - return (SongodaPlugin) Bukkit.getPluginManager().getPlugin("EpicHoppers"); - } + void clearModuleCache(); } diff --git a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/player/PlayerData.java b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/player/PlayerData.java index be8ba12..9574acf 100644 --- a/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/player/PlayerData.java +++ b/EpicHoppers-API/src/main/java/com/craftaro/epichoppers/player/PlayerData.java @@ -1,5 +1,6 @@ package com.craftaro.epichoppers.player; + import com.craftaro.epichoppers.hopper.Hopper; public class PlayerData { diff --git a/EpicHoppers-Plugin/pom.xml b/EpicHoppers-Plugin/pom.xml index b23070d..c9d03f0 100644 --- a/EpicHoppers-Plugin/pom.xml +++ b/EpicHoppers-Plugin/pom.xml @@ -7,7 +7,7 @@ com.craftaro EpicHoppers-Parent - 5.0.0-SNAPSHOT + 5.0.0-SNAPSHOT-b5 ../pom.xml EpicHoppers-Plugin @@ -56,6 +56,7 @@ false **/nms/v*/** + **/third_party/** @@ -89,7 +90,7 @@ com.craftaro EpicHoppers-API - 5.0.0-SNAPSHOT + 1.0.0-SNAPSHOT compile @@ -136,9 +137,9 @@ - com.songoda - UltimateStacker - 2.1.6 + com.craftaro + UltimateStacker-API + 1.0.0-SNAPSHOT provided diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/EpicHoppers.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/EpicHoppers.java index acea70a..cbf4e6d 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/EpicHoppers.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/EpicHoppers.java @@ -4,17 +4,14 @@ import com.craftaro.core.SongodaPlugin; import com.craftaro.core.commands.CommandManager; import com.craftaro.core.configuration.Config; -import com.craftaro.core.database.DataManagerAbstract; -import com.craftaro.core.database.DataMigrationManager; import com.craftaro.core.database.DatabaseConnector; -import com.craftaro.core.database.MySQLConnector; -import com.craftaro.core.database.SQLiteConnector; import com.craftaro.core.gui.GuiManager; import com.craftaro.core.hooks.EconomyManager; import com.craftaro.core.hooks.ProtectionManager; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.third_party.de.tr7zw.nbtapi.NBTItem; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.boost.BoostDataImpl; import com.craftaro.epichoppers.boost.BoostManager; import com.craftaro.epichoppers.boost.BoostManagerImpl; import com.craftaro.epichoppers.commands.CommandBoost; @@ -23,9 +20,8 @@ import com.craftaro.epichoppers.commands.CommandSettings; import com.craftaro.epichoppers.containers.ContainerManager; import com.craftaro.epichoppers.containers.ContainerManagerImpl; -import com.craftaro.epichoppers.database.DataManager; -import com.craftaro.epichoppers.database.DataManagerImpl; import com.craftaro.epichoppers.database.migrations._1_InitialMigration; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.HopperManager; import com.craftaro.epichoppers.hopper.levels.Level; import com.craftaro.epichoppers.hopper.levels.LevelManager; @@ -76,8 +72,6 @@ public class EpicHoppers extends SongodaPlugin { private TeleportHandler teleportHandler; private DatabaseConnector databaseConnector; - private DataManager dataManager; - @Override public void onPluginLoad() { } @@ -120,33 +114,8 @@ public void onPluginEnable() { this.containerManager = new ContainerManagerImpl(); this.boostManager = new BoostManagerImpl(); - // Database stuff, go! - 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 DataManagerImpl(this.databaseConnector, this); - DataMigrationManager dataMigrationManager = new DataMigrationManager(this.databaseConnector, (DataManagerAbstract) this.dataManager, new _1_InitialMigration(this)); - dataMigrationManager.runMigrations(); - EpicHoppersApi.initApi(this.levelManager, this.boostManager, this.containerManager, this.teleportHandler, this.playerDataManager, this.dataManager); + initDatabase(Collections.singletonList(new _1_InitialMigration(this))); this.loadLevelManager(); @@ -162,6 +131,8 @@ public void onPluginEnable() { pluginManager.registerEvents(new InteractListeners(this), this); pluginManager.registerEvents(new InventoryListeners(), this); + EpicHoppersApi.initApi(this.levelManager, this.boostManager, this.containerManager, this.teleportHandler, this.playerDataManager); + // Start auto save int saveInterval = Settings.AUTOSAVE.getInt() * 60 * 20; Bukkit.getScheduler().runTaskTimerAsynchronously(this, this::saveModules, saveInterval, saveInterval); @@ -182,10 +153,9 @@ public void onPluginEnable() { @Override public void onDataLoad() { // Load data from DB - this.dataManager.getHoppers((hoppers) -> { - this.hopperManager.addHoppers(hoppers.values()); - this.dataManager.getBoosts((boosts) -> this.boostManager.addBoosts(boosts)); - + this.dataManager.getAsyncPool().execute(() -> { + this.hopperManager.addHoppers(this.dataManager.loadBatch(HopperImpl.class, "placed_hoppers")); + this.boostManager.loadBoosts(this.dataManager.loadBatch(BoostDataImpl.class, "boosted_players")); this.hopperManager.setReady(); }); } @@ -302,10 +272,6 @@ public GuiManager getGuiManager() { return this.guiManager; } - public DataManager getDataManager() { - return this.dataManager; - } - public DatabaseConnector getDatabaseConnector() { return this.databaseConnector; } diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostDataImpl.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostDataImpl.java new file mode 100644 index 0000000..8c2f202 --- /dev/null +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostDataImpl.java @@ -0,0 +1,92 @@ +package com.craftaro.epichoppers.boost; + +import com.craftaro.core.database.Data; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +public class BoostDataImpl implements BoostData, Data { + private final int multiplier; + private final long endTime; + private final UUID player; + + public BoostDataImpl() { + this.multiplier = 0; + this.endTime = 0; + this.player = null; + } + + public BoostDataImpl(Map map) { + this.multiplier = (int) map.get("multiplier"); + this.endTime = (long) map.get("end_time"); + this.player = UUID.fromString((String) map.get("player")); + } + + public BoostDataImpl(int multiplier, long endTime, UUID player) { + this.multiplier = multiplier; + this.endTime = endTime; + this.player = player; + } + + public int getMultiplier() { + return this.multiplier; + } + + public UUID getPlayer() { + return this.player; + } + + public long getEndTime() { + return this.endTime; + } + + @Override + public int hashCode() { + int result = 31 * this.multiplier; + + result = 31 * result + (this.player == null ? 0 : this.player.hashCode()); + result = 31 * result + (int) (this.endTime ^ (this.endTime >>> 32)); + + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof BoostDataImpl)) { + return false; + } + + BoostDataImpl other = (BoostDataImpl) obj; + return this.multiplier == other.multiplier && + this.endTime == other.endTime && + Objects.equals(this.player, other.player); + } + + @Override + public UUID getUniqueId() { + return player; + } + + @Override + public Map serialize() { + Map map = new java.util.HashMap<>(); + map.put("player", player.toString()); + map.put("multiplier", multiplier); + map.put("end_time", endTime); + return map; + } + + @Override + public Data deserialize(Map map) { + return new BoostDataImpl(map); + } + + @Override + public String getTableName() { + return "player_boosts"; + } +} diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostManagerImpl.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostManagerImpl.java index 1823592..f39e565 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostManagerImpl.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/boost/BoostManagerImpl.java @@ -1,5 +1,8 @@ package com.craftaro.epichoppers.boost; +import com.craftaro.core.database.Data; + +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -24,6 +27,10 @@ public void addBoosts(List boosts) { this.registeredBoosts.addAll(boosts); } + public void loadBoosts(Collection boosts) { + this.registeredBoosts.addAll(boosts); + } + @Override public Set getBoosts() { return Collections.unmodifiableSet(this.registeredBoosts); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/commands/CommandBoost.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/commands/CommandBoost.java index e8ebdd5..829d784 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/commands/CommandBoost.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/commands/CommandBoost.java @@ -3,7 +3,7 @@ import com.craftaro.core.commands.AbstractCommand; import com.craftaro.core.utils.NumberUtils; import com.craftaro.core.utils.TimeUtils; -import com.craftaro.epichoppers.boost.BoostData; +import com.craftaro.epichoppers.boost.BoostDataImpl; import com.craftaro.epichoppers.EpicHoppers; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -49,7 +49,7 @@ protected ReturnType runCommand(CommandSender sender, String... args) { return ReturnType.FAILURE; } - BoostData boostData = new BoostData(Integer.parseInt(args[1]), duration == 0L ? Long.MAX_VALUE : System.currentTimeMillis() + duration, player.getUniqueId()); + BoostDataImpl boostData = new BoostDataImpl(Integer.parseInt(args[1]), duration == 0L ? Long.MAX_VALUE : System.currentTimeMillis() + duration, player.getUniqueId()); this.plugin.getBoostManager().addBoostToPlayer(boostData); this.plugin.getLocale().newMessage("&7Successfully boosted &6" + Bukkit.getPlayer(args[0]).getName() + "'s &7hopper transfer rates by &6" + args[1] + "x" + (duration == 0L ? "" : (" for " + TimeUtils.makeReadable(duration))) + "&7.").sendPrefixedMessage(sender); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/DataManagerImpl.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/DataManagerImpl.java index aac9c34..53d222b 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/DataManagerImpl.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/DataManagerImpl.java @@ -1,11 +1,11 @@ package com.craftaro.epichoppers.database; -import com.craftaro.core.database.DataManagerAbstract; import com.craftaro.core.database.DatabaseConnector; import com.craftaro.epichoppers.boost.BoostData; +import com.craftaro.epichoppers.boost.BoostDataImpl; import com.craftaro.epichoppers.EpicHoppers; import com.craftaro.epichoppers.hopper.Filter; -import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.HopperBuilder; import com.craftaro.epichoppers.hopper.ItemType; import com.craftaro.epichoppers.hopper.LinkType; @@ -33,401 +33,346 @@ import java.util.UUID; import java.util.function.Consumer; -public class DataManagerImpl extends DataManagerAbstract implements DataManager { - public DataManagerImpl(DatabaseConnector databaseConnector, Plugin plugin) { - super(databaseConnector, plugin); - } - - @Override - 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 (?, ?, ?)"; - 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(); - } - }); - } - - @Override - 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(); - } - }); - } - - @Override - 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(); - } - }); - } - - @Override - public void createLink(Hopper hopper, Location location, LinkType type) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)"; - PreparedStatement statement = connection.prepareStatement(createLink); - statement.setInt(1, hopper.getId()); - - statement.setString(2, type.name()); - - statement.setString(3, location.getWorld().getName()); - statement.setInt(4, location.getBlockX()); - statement.setInt(5, location.getBlockY()); - statement.setInt(6, location.getBlockZ()); - statement.executeUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void updateItems(Hopper hopper, ItemType type, List items) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String clearItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE hopper_id = ? AND item_type = ?"; - try (PreparedStatement statement = connection.prepareStatement(clearItems)) { - statement.setInt(1, hopper.getId()); - statement.setString(2, type.name()); - statement.executeUpdate(); - } - - String createItem = "INSERT INTO " + this.getTablePrefix() + "items (hopper_id, item_type, item) VALUES (?, ?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createItem)) { - for (ItemStack item : items) { - statement.setInt(1, hopper.getId()); - statement.setString(2, type.name()); - - try (ByteArrayOutputStream stream = new ByteArrayOutputStream(); BukkitObjectOutputStream bukkitStream = new BukkitObjectOutputStream(stream)) { - bukkitStream.writeObject(item); - statement.setString(3, Base64.getEncoder().encodeToString(stream.toByteArray())); - } catch (IOException e) { - e.printStackTrace(); - continue; - } - statement.addBatch(); - } - statement.executeBatch(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void deleteLink(Hopper hopper, Location location) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String deleteLink = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ? AND world = ? AND x = ? AND y = ? AND z = ?"; - PreparedStatement statement = connection.prepareStatement(deleteLink); - statement.setInt(1, hopper.getId()); - statement.setString(2, location.getWorld().getName()); - statement.setInt(3, location.getBlockX()); - statement.setInt(4, location.getBlockY()); - statement.setInt(5, location.getBlockZ()); - statement.executeUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void deleteLinks(Hopper hopper) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String deleteHopperLinks = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ?"; - PreparedStatement statement = connection.prepareStatement(deleteHopperLinks); - statement.setInt(1, hopper.getId()); - statement.executeUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void createHoppers(List hoppers) { - for (Hopper hopper : hoppers) { - createHopper(hopper); - } - } - - @Override - public void createHopper(Hopper hopper) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String createHopper = "INSERT INTO " + this.getTablePrefix() + "placed_hoppers (level, placed_by, last_opened_by, teleport_trigger, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createHopper)) { - statement.setInt(1, hopper.getLevel().getLevel()); - - statement.setString(2, - hopper.getPlacedBy() == null ? null : hopper.getPlacedBy().toString()); - - statement.setString(3, - hopper.getLastPlayerOpened() == null ? null : hopper.getLastPlayerOpened().toString()); - - statement.setString(4, hopper.getTeleportTrigger().name()); - - statement.setString(5, hopper.getWorld().getName()); - statement.setInt(6, hopper.getX()); - statement.setInt(7, hopper.getY()); - statement.setInt(8, hopper.getZ()); - statement.executeUpdate(); - } - - int hopperId = this.lastInsertedId(connection, "placed_hoppers"); - hopper.setId(hopperId); - - Map items = new HashMap<>(); - Filter filter = hopper.getFilter(); - - for (ItemStack item : filter.getWhiteList()) { - items.put(item, ItemType.WHITELIST); - } - - for (ItemStack item : filter.getBlackList()) { - items.put(item, ItemType.BLACKLIST); - } - - for (ItemStack item : filter.getVoidList()) { - items.put(item, ItemType.VOID); - } - - for (ItemStack item : filter.getAutoSellWhiteList()) { - items.put(item, ItemType.AUTO_SELL_WHITELIST); - } - - for (ItemStack item : filter.getAutoSellBlackList()) { - items.put(item, ItemType.AUTO_SELL_BLACKLIST); - } - - String createItem = "INSERT INTO " + this.getTablePrefix() + "items (hopper_id, item_type, item) VALUES (?, ?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createItem)) { - for (Map.Entry entry : items.entrySet()) { - statement.setInt(1, hopper.getId()); - statement.setString(2, entry.getValue().name()); - - try (ByteArrayOutputStream stream = new ByteArrayOutputStream(); BukkitObjectOutputStream bukkitStream = new BukkitObjectOutputStream(stream)) { - bukkitStream.writeObject(entry.getKey()); - statement.setString(3, Base64.getEncoder().encodeToString(stream.toByteArray())); - } catch (IOException e) { - e.printStackTrace(); - continue; - } - statement.addBatch(); - } - statement.executeBatch(); - } - - Map links = new HashMap<>(); - - for (Location location : hopper.getLinkedBlocks()) { - links.put(location, LinkType.REGULAR); - } - - if (filter.getEndPoint() != null) { - links.put(filter.getEndPoint(), LinkType.REJECT); - } - - String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)"; - try (PreparedStatement statement = connection.prepareStatement(createLink)) { - for (Map.Entry entry : links.entrySet()) { - statement.setInt(1, hopper.getId()); - - statement.setString(2, entry.getValue().name()); - - Location location = entry.getKey(); - statement.setString(3, location.getWorld().getName()); - statement.setInt(4, location.getBlockX()); - statement.setInt(5, location.getBlockY()); - statement.setInt(6, location.getBlockZ()); - statement.addBatch(); - } - statement.executeBatch(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void updateHopper(Hopper hopper) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String updateHopper = "UPDATE " + this.getTablePrefix() + "placed_hoppers SET level = ?, placed_by = ?, last_opened_by = ?, teleport_trigger = ? WHERE id = ?"; - PreparedStatement statement = connection.prepareStatement(updateHopper); - statement.setInt(1, hopper.getLevel().getLevel()); - statement.setString(2, hopper.getPlacedBy().toString()); - statement.setString(3, hopper.getLastPlayerOpened().toString()); - statement.setString(4, hopper.getTeleportTrigger().name()); - statement.setInt(5, hopper.getId()); - statement.executeUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void deleteHopper(Hopper hopper) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - String deleteHopper = "DELETE FROM " + this.getTablePrefix() + "placed_hoppers WHERE id = ?"; - try (PreparedStatement statement = connection.prepareStatement(deleteHopper)) { - statement.setInt(1, hopper.getId()); - statement.executeUpdate(); - } - - String deleteHopperLinks = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ?"; - try (PreparedStatement statement = connection.prepareStatement(deleteHopperLinks)) { - statement.setInt(1, hopper.getId()); - statement.executeUpdate(); - } - - String deleteItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE hopper_id = ?"; - try (PreparedStatement statement = connection.prepareStatement(deleteItems)) { - statement.setInt(1, hopper.getId()); - statement.executeUpdate(); - } - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } - - @Override - public void getHoppers(Consumer> callback) { - this.runAsync(() -> { - try (Connection connection = this.databaseConnector.getConnection()) { - Map hoppers = new HashMap<>(); - - try (Statement statement = connection.createStatement()) { - String selectHoppers = "SELECT * FROM " + this.getTablePrefix() + "placed_hoppers"; - ResultSet result = statement.executeQuery(selectHoppers); - 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")); - - String lastOpenedByStr = result.getString("last_opened_by"); - UUID lastOpenedBy = lastOpenedByStr == null ? null : UUID.fromString(result.getString("last_opened_by")); - - TeleportTrigger teleportTrigger = TeleportTrigger.valueOf(result.getString("teleport_trigger")); - - int x = result.getInt("x"); - int y = result.getInt("y"); - int z = result.getInt("z"); - Location location = new Location(world, x, y, z); - - Hopper hopper = new HopperBuilder(location) - .setId(id) - .setLevel(((EpicHoppers) this.plugin).getLevelManager().getLevel(level)) - .setPlacedBy(placedBy) - .setLastPlayerOpened(lastOpenedBy) - .setTeleportTrigger(teleportTrigger) - .build(); - - hoppers.put(id, hopper); - } - } - - try (Statement statement = connection.createStatement()) { - String selectLinks = "SELECT * FROM " + this.getTablePrefix() + "links"; - ResultSet result = statement.executeQuery(selectLinks); - while (result.next()) { - World world = Bukkit.getWorld(result.getString("world")); - - if (world == null) { - continue; - } - - int id = result.getInt("hopper_id"); - LinkType type = LinkType.valueOf(result.getString("link_type")); - - int x = result.getInt("x"); - int y = result.getInt("y"); - int z = result.getInt("z"); - Location location = new Location(world, x, y, z); - - Hopper hopper = hoppers.get(id); - if (hopper == null) { - break; - } - - hopper.addLinkedBlock(location, type); - } - } - - try (Statement statement = connection.createStatement()) { - String selectItems = "SELECT * FROM " + this.getTablePrefix() + "items"; - ResultSet result = statement.executeQuery(selectItems); - while (result.next()) { - int id = result.getInt("hopper_id"); - ItemType type = ItemType.valueOf(result.getString("item_type")); - - ItemStack item = null; - try (BukkitObjectInputStream stream = new BukkitObjectInputStream( - new ByteArrayInputStream(Base64.getDecoder().decode(result.getString("item"))))) { - item = (ItemStack) stream.readObject(); - } catch (IOException | ClassNotFoundException e) { - e.printStackTrace(); - } - - Hopper hopper = hoppers.get(id); - if (hopper == null) { - break; - } - - if (item != null) { - hopper.getFilter().addItem(item, type); - } - } - } - this.sync(() -> callback.accept(hoppers)); - } catch (Exception ex) { - ex.printStackTrace(); - } - }); - } +public class DataManagerImpl { +// public DataManagerImpl(DatabaseConnector databaseConnector, Plugin plugin) { +// super(databaseConnector, plugin); +// } +// +// @Override +// public void createBoost(BoostDataImpl boostData) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String createBoostedPlayer = "INSERT INTO " + this.getTablePrefix() + "boosted_players (player, multiplier, end_time) VALUES (?, ?, ?)"; +// 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(); +// } +// }); +// } +// +// @Override +// 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 BoostDataImpl(multiplier, endTime, player)); +// } +// +// this.sync(() -> callback.accept(boosts)); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } +// +// @Override +// public void deleteBoost(BoostDataImpl 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(); +// } +// }); +// } +// +// @Override +// public void deleteLink(HopperImpl hopper, Location location) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String deleteLink = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ? AND world = ? AND x = ? AND y = ? AND z = ?"; +// PreparedStatement statement = connection.prepareStatement(deleteLink); +// statement.setInt(1, hopper.getId()); +// statement.setString(2, location.getWorld().getName()); +// statement.setInt(3, location.getBlockX()); +// statement.setInt(4, location.getBlockY()); +// statement.setInt(5, location.getBlockZ()); +// statement.executeUpdate(); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } +// +// @Override +// public void deleteLinks(HopperImpl hopper) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String deleteHopperLinks = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ?"; +// PreparedStatement statement = connection.prepareStatement(deleteHopperLinks); +// statement.setInt(1, hopper.getId()); +// statement.executeUpdate(); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } +// +// @Override +// public void createHoppers(List hoppers) { +// for (HopperImpl hopper : hoppers) { +// createHopper(hopper); +// } +// } +// +// @Override +// public void createHopper(HopperImpl hopper) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String createHopper = "INSERT INTO " + this.getTablePrefix() + "placed_hoppers (level, placed_by, last_opened_by, teleport_trigger, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; +// try (PreparedStatement statement = connection.prepareStatement(createHopper)) { +// statement.setInt(1, hopper.getLevel().getLevel()); +// +// statement.setString(2, +// hopper.getPlacedBy() == null ? null : hopper.getPlacedBy().toString()); +// +// statement.setString(3, +// hopper.getLastPlayerOpened() == null ? null : hopper.getLastPlayerOpened().toString()); +// +// statement.setString(4, hopper.getTeleportTrigger().name()); +// +// statement.setString(5, hopper.getWorld().getName()); +// statement.setInt(6, hopper.getX()); +// statement.setInt(7, hopper.getY()); +// statement.setInt(8, hopper.getZ()); +// statement.executeUpdate(); +// } +// +// int hopperId = this.lastInsertedId(connection, "placed_hoppers"); +// hopper.setId(hopperId); +// +// Map items = new HashMap<>(); +// Filter filter = hopper.getFilter(); +// +// for (ItemStack item : filter.getWhiteList()) { +// items.put(item, ItemType.WHITELIST); +// } +// +// for (ItemStack item : filter.getBlackList()) { +// items.put(item, ItemType.BLACKLIST); +// } +// +// for (ItemStack item : filter.getVoidList()) { +// items.put(item, ItemType.VOID); +// } +// +// for (ItemStack item : filter.getAutoSellWhiteList()) { +// items.put(item, ItemType.AUTO_SELL_WHITELIST); +// } +// +// for (ItemStack item : filter.getAutoSellBlackList()) { +// items.put(item, ItemType.AUTO_SELL_BLACKLIST); +// } +// +// String createItem = "INSERT INTO " + this.getTablePrefix() + "items (hopper_id, item_type, item) VALUES (?, ?, ?)"; +// try (PreparedStatement statement = connection.prepareStatement(createItem)) { +// for (Map.Entry entry : items.entrySet()) { +// statement.setInt(1, hopper.getId()); +// statement.setString(2, entry.getValue().name()); +// +// try (ByteArrayOutputStream stream = new ByteArrayOutputStream(); BukkitObjectOutputStream bukkitStream = new BukkitObjectOutputStream(stream)) { +// bukkitStream.writeObject(entry.getKey()); +// statement.setString(3, Base64.getEncoder().encodeToString(stream.toByteArray())); +// } catch (IOException e) { +// e.printStackTrace(); +// continue; +// } +// statement.addBatch(); +// } +// statement.executeBatch(); +// } +// +// Map links = new HashMap<>(); +// +// for (Location location : hopper.getLinkedBlocks()) { +// links.put(location, LinkType.REGULAR); +// } +// +// if (filter.getEndPoint() != null) { +// links.put(filter.getEndPoint(), LinkType.REJECT); +// } +// +// String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)"; +// try (PreparedStatement statement = connection.prepareStatement(createLink)) { +// for (Map.Entry entry : links.entrySet()) { +// statement.setInt(1, hopper.getId()); +// +// statement.setString(2, entry.getValue().name()); +// +// Location location = entry.getKey(); +// statement.setString(3, location.getWorld().getName()); +// statement.setInt(4, location.getBlockX()); +// statement.setInt(5, location.getBlockY()); +// statement.setInt(6, location.getBlockZ()); +// statement.addBatch(); +// } +// statement.executeBatch(); +// } +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } +// +// @Override +// public void updateHopper(HopperImpl hopper) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String updateHopper = "UPDATE " + this.getTablePrefix() + "placed_hoppers SET level = ?, placed_by = ?, last_opened_by = ?, teleport_trigger = ? WHERE id = ?"; +// PreparedStatement statement = connection.prepareStatement(updateHopper); +// statement.setInt(1, hopper.getLevel().getLevel()); +// statement.setString(2, hopper.getPlacedBy().toString()); +// statement.setString(3, hopper.getLastPlayerOpened().toString()); +// statement.setString(4, hopper.getTeleportTrigger().name()); +// statement.setInt(5, hopper.getId()); +// statement.executeUpdate(); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } +// +// @Override +// public void deleteHopper(HopperImpl hopper) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String deleteHopper = "DELETE FROM " + this.getTablePrefix() + "placed_hoppers WHERE id = ?"; +// try (PreparedStatement statement = connection.prepareStatement(deleteHopper)) { +// statement.setInt(1, hopper.getId()); +// statement.executeUpdate(); +// } +// +// String deleteHopperLinks = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ?"; +// try (PreparedStatement statement = connection.prepareStatement(deleteHopperLinks)) { +// statement.setInt(1, hopper.getId()); +// statement.executeUpdate(); +// } +// +// String deleteItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE hopper_id = ?"; +// try (PreparedStatement statement = connection.prepareStatement(deleteItems)) { +// statement.setInt(1, hopper.getId()); +// statement.executeUpdate(); +// } +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } +// +// @Override +// public void getHoppers(Consumer> callback) { +// this.runAsync(() -> { +// try (Connection connection = this.databaseConnector.getConnection()) { +// Map hoppers = new HashMap<>(); +// +// try (Statement statement = connection.createStatement()) { +// String selectHoppers = "SELECT * FROM " + this.getTablePrefix() + "placed_hoppers"; +// ResultSet result = statement.executeQuery(selectHoppers); +// 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")); +// +// String lastOpenedByStr = result.getString("last_opened_by"); +// UUID lastOpenedBy = lastOpenedByStr == null ? null : UUID.fromString(result.getString("last_opened_by")); +// +// TeleportTrigger teleportTrigger = TeleportTrigger.valueOf(result.getString("teleport_trigger")); +// +// int x = result.getInt("x"); +// int y = result.getInt("y"); +// int z = result.getInt("z"); +// Location location = new Location(world, x, y, z); +// +// HopperImpl hopper = new HopperBuilder(location) +// .setId(id) +// .setLevel(((EpicHoppers) this.plugin).getLevelManager().getLevel(level)) +// .setPlacedBy(placedBy) +// .setLastPlayerOpened(lastOpenedBy) +// .setTeleportTrigger(teleportTrigger) +// .build(); +// +// hoppers.put(id, hopper); +// } +// } +// +// try (Statement statement = connection.createStatement()) { +// String selectLinks = "SELECT * FROM " + this.getTablePrefix() + "links"; +// ResultSet result = statement.executeQuery(selectLinks); +// while (result.next()) { +// World world = Bukkit.getWorld(result.getString("world")); +// +// if (world == null) { +// continue; +// } +// +// int id = result.getInt("hopper_id"); +// LinkType type = LinkType.valueOf(result.getString("link_type")); +// +// int x = result.getInt("x"); +// int y = result.getInt("y"); +// int z = result.getInt("z"); +// Location location = new Location(world, x, y, z); +// +// HopperImpl hopper = hoppers.get(id); +// if (hopper == null) { +// break; +// } +// +// hopper.addLinkedBlock(location, type); +// } +// } +// +// try (Statement statement = connection.createStatement()) { +// String selectItems = "SELECT * FROM " + this.getTablePrefix() + "items"; +// ResultSet result = statement.executeQuery(selectItems); +// while (result.next()) { +// int id = result.getInt("hopper_id"); +// ItemType type = ItemType.valueOf(result.getString("item_type")); +// +// ItemStack item = null; +// try (BukkitObjectInputStream stream = new BukkitObjectInputStream( +// new ByteArrayInputStream(Base64.getDecoder().decode(result.getString("item"))))) { +// item = (ItemStack) stream.readObject(); +// } catch (IOException | ClassNotFoundException e) { +// e.printStackTrace(); +// } +// +// HopperImpl hopper = hoppers.get(id); +// if (hopper == null) { +// break; +// } +// +// if (item != null) { +// hopper.getFilter().addItem(item, type); +// } +// } +// } +// this.sync(() -> callback.accept(hoppers)); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } +// }); +// } } diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/migrations/_1_InitialMigration.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/migrations/_1_InitialMigration.java index ff747eb..62ac46e 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/migrations/_1_InitialMigration.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/database/migrations/_1_InitialMigration.java @@ -1,6 +1,7 @@ package com.craftaro.epichoppers.database.migrations; import com.craftaro.core.database.DataMigration; +import com.craftaro.core.database.DatabaseConnector; import com.craftaro.core.database.MySQLConnector; import com.craftaro.epichoppers.EpicHoppers; @@ -17,13 +18,12 @@ public _1_InitialMigration(EpicHoppers plugin) { } @Override - public void migrate(Connection connection, String tablePrefix) throws SQLException { - String autoIncrement = this.plugin.getDatabaseConnector() instanceof MySQLConnector ? " AUTO_INCREMENT" : ""; + public void migrate(DatabaseConnector databaseConnector, String tablePrefix) throws SQLException { // Create hoppers table - try (Statement statement = connection.createStatement()) { + try (Statement statement = databaseConnector.getConnection().createStatement()) { statement.execute("CREATE TABLE " + tablePrefix + "placed_hoppers (" + - "id INTEGER PRIMARY KEY" + autoIncrement + ", " + + "id INTEGER PRIMARY KEY AUTO_INCREMENT" + ", " + "level INTEGER NOT NULL, " + "placed_by VARCHAR(36), " + "last_opened_by VARCHAR(36), " + @@ -36,7 +36,7 @@ public void migrate(Connection connection, String tablePrefix) throws SQLExcepti } // Create hopper links - try (Statement statement = connection.createStatement()) { + try (Statement statement = databaseConnector.getConnection().createStatement()) { statement.execute("CREATE TABLE " + tablePrefix + "links (" + "hopper_id INTEGER NOT NULL, " + "link_type TEXT NOT NULL," + @@ -49,7 +49,7 @@ public void migrate(Connection connection, String tablePrefix) throws SQLExcepti // Create items // Items are base64. - try (Statement statement = connection.createStatement()) { + try (Statement statement = databaseConnector.getConnection().createStatement()) { statement.execute("CREATE TABLE " + tablePrefix + "items (" + "hopper_id INTEGER NOT NULL, " + "item_type BIT NOT NULL," + @@ -58,7 +58,7 @@ public void migrate(Connection connection, String tablePrefix) throws SQLExcepti } // 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/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIAutoSellFilter.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIAutoSellFilter.java index 9d39d9e..1d74217 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIAutoSellFilter.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIAutoSellFilter.java @@ -5,11 +5,12 @@ import com.craftaro.core.gui.GuiUtils; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; -import com.craftaro.epichoppers.EpicHoppersApi; import com.craftaro.epichoppers.hopper.Filter; import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.ItemType; import com.craftaro.epichoppers.settings.Settings; +import com.craftaro.epichoppers.utils.DataHelper; import com.craftaro.epichoppers.utils.Methods; import org.bukkit.Bukkit; import org.bukkit.inventory.ItemStack; @@ -21,14 +22,14 @@ public class GUIAutoSellFilter extends CustomizableGui { private static final List OPEN_INVENTORIES = new ArrayList<>(); - private final Hopper hopper; + private final HopperImpl hopper; private final int[] whiteListSlots = {9, 10, 11, 18, 19, 20, 27, 28, 29, 36, 37, 38}; private final int[] blackListSlots = {12, 13, 14, 21, 22, 23, 30, 31, 32, 39, 40, 41}; public GUIAutoSellFilter(SongodaPlugin plugin, Hopper hopper) { super(plugin, "autosell"); - this.hopper = hopper; + this.hopper = (HopperImpl) hopper; setRows(6); setTitle(TextUtils.formatText(Methods.formatName(hopper.getLevel().getLevel()) + " &8-&f AutoSell Filter")); @@ -62,7 +63,7 @@ public GUIAutoSellFilter(SongodaPlugin plugin, Hopper hopper) { setButton("back", 8, GuiUtils.createButtonItem(XMaterial.ARROW.parseItem(), plugin.getLocale().getMessage("general.nametag.back").getMessage()), (event) -> { - if (hopper.prepareForOpeningOverviewGui(event.player)) { + if (this.hopper.prepareForOpeningOverviewGui(event.player)) { this.guiManager.showGUI(event.player, new GUIOverview(plugin, hopper, event.player)); } compile(); @@ -180,11 +181,11 @@ private void compile() { filter.setAutoSellWhiteList(whiteListItems); filter.setAutoSellBlackList(blackListItems); - EpicHoppersApi.getApi().getDataManager().updateItems(this.hopper, ItemType.AUTO_SELL_WHITELIST, whiteListItems); - EpicHoppersApi.getApi().getDataManager().updateItems(this.hopper, ItemType.AUTO_SELL_BLACKLIST, blackListItems); + DataHelper.updateItems(this.hopper, ItemType.AUTO_SELL_WHITELIST, whiteListItems); + DataHelper.updateItems(this.hopper, ItemType.AUTO_SELL_BLACKLIST, blackListItems); } - public static void compileOpenAutoSellFilter(Hopper hopper) { + public static void compileOpenAutoSellFilter(HopperImpl hopper) { for (GUIAutoSellFilter autoSellFilter : OPEN_INVENTORIES) { if (autoSellFilter.hopper == hopper) { autoSellFilter.compile(); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUICrafting.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUICrafting.java index ccfe49f..02faf16 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUICrafting.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUICrafting.java @@ -5,10 +5,11 @@ import com.craftaro.core.gui.GuiUtils; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.levels.modules.ModuleAutoCrafting; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.Methods; -import com.craftaro.epichoppers.hopper.Hopper; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -38,7 +39,7 @@ public GUICrafting(ModuleAutoCrafting module, SongodaPlugin plugin, Hopper hoppe setButton("back", 8, GuiUtils.createButtonItem(XMaterial.ARROW.parseItem(), plugin.getLocale().getMessage("general.nametag.back").getMessage()), (event) -> { - if (hopper.prepareForOpeningOverviewGui(event.player)) { + if (((HopperImpl)hopper).prepareForOpeningOverviewGui(event.player)) { this.guiManager.showGUI(event.player, new GUIOverview(plugin, hopper, event.player)); } setItem(module, hopper, player); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIFilter.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIFilter.java index e9e8cd8..72037eb 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIFilter.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIFilter.java @@ -6,12 +6,14 @@ import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; import com.craftaro.epichoppers.EpicHoppersApi; +import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.hopper.ItemType; import com.craftaro.epichoppers.player.SyncType; import com.craftaro.epichoppers.settings.Settings; +import com.craftaro.epichoppers.utils.DataHelper; import com.craftaro.epichoppers.utils.Methods; import com.craftaro.epichoppers.hopper.Filter; -import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; @@ -26,12 +28,12 @@ public class GUIFilter extends CustomizableGui { private static final List OPEN_INVENTORIES = new ArrayList<>(); private final SongodaPlugin plugin; - private final Hopper hopper; + private final HopperImpl hopper; public GUIFilter(SongodaPlugin plugin, Hopper hopper, Player player) { super(plugin, "filter"); this.plugin = plugin; - this.hopper = hopper; + this.hopper = (HopperImpl) hopper; setRows(6); setTitle(TextUtils.formatText(Methods.formatName(hopper.getLevel().getLevel()) + " &8-&f Filter")); @@ -68,7 +70,7 @@ public GUIFilter(SongodaPlugin plugin, Hopper hopper, Player player) { setButton("back", 8, GuiUtils.createButtonItem(XMaterial.ARROW.parseItem(), plugin.getLocale().getMessage("general.nametag.back").getMessage()), (event) -> { - if (hopper.prepareForOpeningOverviewGui(event.player)) { + if (this.hopper.prepareForOpeningOverviewGui(event.player)) { this.guiManager.showGUI(event.player, new GUIOverview(plugin, hopper, event.player)); } compile(); @@ -235,12 +237,12 @@ private void compile() { filter.setWhiteList(owhite); filter.setBlackList(oblack); filter.setVoidList(ovoid); - EpicHoppersApi.getApi().getDataManager().updateItems(this.hopper, ItemType.WHITELIST, owhite); - EpicHoppersApi.getApi().getDataManager().updateItems(this.hopper, ItemType.BLACKLIST, oblack); - EpicHoppersApi.getApi().getDataManager().updateItems(this.hopper, ItemType.VOID, ovoid); + DataHelper.updateItems(this.hopper, ItemType.WHITELIST, owhite); + DataHelper.updateItems(this.hopper, ItemType.BLACKLIST, oblack); + DataHelper.updateItems(this.hopper, ItemType.VOID, ovoid); } - public static void compileOpenGuiFilter(Hopper hopper) { + public static void compileOpenGuiFilter(HopperImpl hopper) { for (GUIFilter guiFilter : OPEN_INVENTORIES) { if (guiFilter.hopper == hopper) { guiFilter.compile(); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIOverview.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIOverview.java index 3abce86..ecd542f 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIOverview.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUIOverview.java @@ -8,15 +8,19 @@ import com.craftaro.core.utils.NumberUtils; import com.craftaro.core.utils.TextUtils; import com.craftaro.core.utils.TimeUtils; +import com.craftaro.epichoppers.EpicHoppers; import com.craftaro.epichoppers.EpicHoppersApi; import com.craftaro.epichoppers.boost.BoostData; +import com.craftaro.epichoppers.boost.BoostDataImpl; import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.levels.Level; import com.craftaro.epichoppers.hopper.levels.modules.Module; import com.craftaro.epichoppers.hopper.teleport.TeleportTrigger; import com.craftaro.epichoppers.player.SyncType; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.CostType; +import com.craftaro.epichoppers.utils.DataHelper; import com.craftaro.epichoppers.utils.Methods; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -33,7 +37,7 @@ public class GUIOverview extends CustomizableGui { private final SongodaPlugin plugin; - private final Hopper hopper; + private final HopperImpl hopper; private final Player player; private int task; @@ -41,7 +45,7 @@ public class GUIOverview extends CustomizableGui { public GUIOverview(SongodaPlugin plugin, Hopper hopper, Player player) { super(plugin, "overview"); this.plugin = plugin; - this.hopper = hopper; + this.hopper = (HopperImpl) hopper; this.player = player; setRows(3); @@ -189,7 +193,7 @@ private void constructGUI() { return; } this.hopper.clearLinkedBlocks(); - EpicHoppersApi.getApi().getDataManager().deleteLinks(this.hopper); + DataHelper.deleteLinks(this.hopper); if (event.clickType == ClickType.RIGHT) { this.plugin.getLocale().getMessage("event.hopper.desync").sendPrefixedMessage(this.player); constructGUI(); @@ -224,7 +228,7 @@ private void constructGUI() { } else if (this.hopper.getTeleportTrigger() == TeleportTrigger.WALK_ON) { this.hopper.setTeleportTrigger(TeleportTrigger.DISABLED); } - EpicHoppersApi.getApi().getDataManager().updateHopper(this.hopper); + EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().save(this.hopper); constructGUI(); } }); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUISmeltable.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUISmeltable.java index 21cefd5..46bf021 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUISmeltable.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/gui/GUISmeltable.java @@ -6,10 +6,11 @@ import com.craftaro.core.gui.GuiUtils; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.levels.modules.ModuleAutoSmelter; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.Methods; -import com.craftaro.epichoppers.hopper.Hopper; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -19,7 +20,7 @@ public class GUISmeltable extends CustomizableGui { private final SongodaPlugin plugin; - private final Hopper hopper; + private final HopperImpl hopper; private final int maxPages; private final ModuleAutoSmelter moduleAutoSmelter; @@ -31,7 +32,7 @@ public class GUISmeltable extends CustomizableGui { public GUISmeltable(ModuleAutoSmelter moduleAutoSmelter, SongodaPlugin plugin, Hopper hopper) { super(plugin, "smeltable"); this.plugin = plugin; - this.hopper = hopper; + this.hopper = (HopperImpl) hopper; this.moduleAutoSmelter = moduleAutoSmelter; int smeltables = BURNABLES.size(); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperBuilder.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperBuilder.java index d269fcb..5c26d85 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperBuilder.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperBuilder.java @@ -9,10 +9,10 @@ import java.util.UUID; public class HopperBuilder { - private final Hopper hopper; + private final HopperImpl hopper; public HopperBuilder(Location location) { - this.hopper = new Hopper(location); + this.hopper = new HopperImpl(location); } public HopperBuilder(Block block) { @@ -65,7 +65,7 @@ public HopperBuilder setTeleportTrigger(TeleportTrigger teleportTrigger) { return this; } - public Hopper build() { + public HopperImpl build() { return this.hopper; } } diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperImpl.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperImpl.java new file mode 100644 index 0000000..ee3e526 --- /dev/null +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperImpl.java @@ -0,0 +1,474 @@ +package com.craftaro.epichoppers.hopper; + +import com.craftaro.core.SongodaPlugin; +import com.craftaro.core.compatibility.CompatibleParticleHandler; +import com.craftaro.core.compatibility.ServerVersion; +import com.craftaro.core.database.Data; +import com.craftaro.core.database.DataManager; +import com.craftaro.core.database.SerializedLocation; +import com.craftaro.core.hooks.EconomyManager; +import com.craftaro.core.third_party.com.cryptomorin.xseries.XSound; +import com.craftaro.core.third_party.org.jooq.impl.DSL; +import com.craftaro.epichoppers.EpicHoppers; +import com.craftaro.epichoppers.EpicHoppersApi; +import com.craftaro.epichoppers.api.events.HopperAccessEvent; +import com.craftaro.epichoppers.hopper.levels.Level; +import com.craftaro.epichoppers.hopper.levels.LevelManager; +import com.craftaro.epichoppers.player.PlayerData; +import com.craftaro.epichoppers.player.PlayerDataManager; +import com.craftaro.epichoppers.utils.CostType; +import com.craftaro.epichoppers.utils.DataHelper; +import com.craftaro.epichoppers.utils.Methods; +import com.craftaro.epichoppers.hopper.teleport.TeleportTrigger; +import com.songoda.skyblock.core.utils.ItemUtils; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.InventoryHolder; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.ApiStatus; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * FIXME: Needs heavy refactoring to only have one responsibility. + */ +public class HopperImpl implements Hopper { + // Id for database use. + private int id; + + private final Location location; + private Level level = getLevelManager().getLowestLevel(); + private UUID lastPlayerOpened = null; + private UUID placedBy = null; + private final List linkedBlocks = new ArrayList<>(); + private Filter filter = new Filter(); + private TeleportTrigger teleportTrigger = TeleportTrigger.DISABLED; + private int transferTick = 0; + + private int syncId = -1; + + private Player activePlayer; + + private final Map moduleCache = new HashMap<>(); + + /** + * Default constructor for database use. + */ + public HopperImpl() { + this.location = null; + } + + public HopperImpl(Location location) { + this.location = location; + } + + /** + * Constructor for database use. + */ + public HopperImpl(Map map) { + this.id = (int) map.get("id"); + this.location = SerializedLocation.of(map); + this.level = getLevelManager().getLevel((int) map.get("level")); + this.lastPlayerOpened = map.get("lastPlayerOpened") == null ? null : UUID.fromString((String) map.get("lastPlayerOpened")); + + DataManager dataManager = EpicHoppers.getPlugin(EpicHoppers.class).getDataManager(); + dataManager.getDatabaseConnector().connectDSL(dslContext -> { + + //Load links + dslContext.select().from(DSL.table(dataManager.getTablePrefix() + "links")).where(DSL.field("hopper_id").eq(id)).fetch().forEach(record -> { + this.linkedBlocks.add(new Location(Bukkit.getWorld(record.get("world", String.class)), + record.get("x", Double.class), + record.get("y", Double.class), + record.get("z", Double.class))); + }); + + + //Load filtered items + dslContext.select().from(DSL.table(dataManager.getTablePrefix() + "items")).where(DSL.field("hopper_id").eq(id)).fetch().forEach(record -> { + ItemStack itemStack = ItemUtils.itemStackArrayFromBase64(record.get("item", String.class))[0]; + ItemType type = ItemType.valueOf(record.get("item_type", String.class)); + filter.addItem(itemStack, type); + + }); + }); + } + + @ApiStatus.Internal + public boolean prepareForOpeningOverviewGui(Player player) { + if (this.lastPlayerOpened != null && + this.lastPlayerOpened != player.getUniqueId() && + Bukkit.getPlayer(this.lastPlayerOpened) != null) { + Bukkit.getPlayer(this.lastPlayerOpened).closeInventory(); + } + + HopperAccessEvent accessEvent = new HopperAccessEvent(player, this); + Bukkit.getPluginManager().callEvent(accessEvent); + if (accessEvent.isCancelled()) { + return false; + } + + if (this.placedBy == null) { + this.placedBy = player.getUniqueId(); + } + + if (!player.hasPermission("epichoppers.overview")) { + return false; + } + + setActivePlayer(player); + return true; + } + + @ApiStatus.Internal + public void forceClose() { + if (this.activePlayer != null) { + this.activePlayer.closeInventory(); + } + } + + public void dropItems() { + Inventory inventory = ((InventoryHolder) this.location.getBlock().getState()).getInventory(); + World world = this.location.getWorld(); + + for (ItemStack itemStack : inventory.getContents()) { + if (itemStack == null || itemStack.getType() == Material.AIR) { + continue; + } + + world.dropItemNaturally(this.location, itemStack); + } + } + + public void upgrade(Player player, CostType type) { + if (!getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) { + return; + } + + Level level = getLevelManager().getLevel(this.level.getLevel() + 1); + int cost = type == CostType.ECONOMY ? level.getCostEconomy() : level.getCostExperience(); + + if (type == CostType.ECONOMY) { + if (!EconomyManager.isEnabled()) { + player.sendMessage("Economy not enabled."); + return; + } + if (!EconomyManager.hasBalance(player, cost)) { + getPlugin().getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player); + return; + } + EconomyManager.withdrawBalance(player, cost); + upgradeFinal(level, player); + } else if (type == CostType.EXPERIENCE) { + if (player.getLevel() >= cost || player.getGameMode() == GameMode.CREATIVE) { + if (player.getGameMode() != GameMode.CREATIVE) { + player.setLevel(player.getLevel() - cost); + } + upgradeFinal(level, player); + } else { + getPlugin().getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player); + } + } + } + + private void upgradeFinal(Level level, Player player) { + this.level = level; + EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().save(this); + //TODO save items/links + syncName(); + if (getLevelManager().getHighestLevel() != level) { + getPlugin().getLocale().getMessage("event.upgrade.success") + .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); + } else { + getPlugin().getLocale().getMessage("event.upgrade.maxed") + .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); + } + Location loc = this.location.clone().add(.5, .5, .5); + + if (!getUpgradeParticleType().trim().isEmpty()) { + CompatibleParticleHandler.spawnParticles( + CompatibleParticleHandler.ParticleType.getParticle(getUpgradeParticleType()), + loc, 100, .5, .5, .5); + } + + if (getLevelManager().getHighestLevel() != level) { + XSound.ENTITY_PLAYER_LEVELUP.play(player, .6f, 15); + } else { + XSound.ENTITY_PLAYER_LEVELUP.play(player, 2, 25); + XSound.BLOCK_NOTE_BLOCK_CHIME.play(player, 2, 25); + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> XSound.BLOCK_NOTE_BLOCK_CHIME.play(player, 1.2f, 35), 5); + Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> XSound.BLOCK_NOTE_BLOCK_CHIME.play(player, 1.8f, 35), 10); + } + } + + private void syncName() { + org.bukkit.block.Hopper hopper = (org.bukkit.block.Hopper) this.location.getBlock().getState(); + if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_10)) { + hopper.setCustomName(Methods.formatName(this.level.getLevel())); + } + hopper.update(true); + } + + public void timeout(Player player) { + this.syncId = Bukkit.getScheduler().scheduleSyncDelayedTask(getPlugin(), () -> { + PlayerData playerData = getPlayerDataManager().getPlayerData(player); + if (playerData.getSyncType() != null && playerData.getLastHopper() == this) { + getPlugin().getLocale().getMessage("event.hopper.synctimeout").sendPrefixedMessage(player); + playerData.setSyncType(null); + } + }, getLinkTimeoutFromPluginConfig() * this.level.getLinkAmount()); + } + + public void link(Block toLink, boolean filtered, Player player) { + if (this.location.getWorld().equals(toLink.getLocation().getWorld()) + && !player.hasPermission("EpicHoppers.Override") + && !player.hasPermission("EpicHoppers.Admin") + && this.location.distance(toLink.getLocation()) > this.level.getRange()) { + getPlugin().getLocale().getMessage("event.hopper.syncoutofrange").sendPrefixedMessage(player); + return; + } + + if (this.linkedBlocks.contains(toLink.getLocation())) { + getPlugin().getLocale().getMessage("event.hopper.already").sendPrefixedMessage(player); + return; + } + + if (!filtered) { + this.linkedBlocks.add(toLink.getLocation()); + DataHelper.createLink(this, toLink.getLocation(), LinkType.REGULAR); + } else { + this.filter.setEndPoint(toLink.getLocation()); + DataHelper.createLink(this, toLink.getLocation(), LinkType.REJECT); + getPlugin().getLocale().getMessage("event.hopper.syncsuccess").sendPrefixedMessage(player); + getPlayerDataManager().getPlayerData(player).setSyncType(null); + return; + } + this.lastPlayerOpened = player.getUniqueId(); + + if (this.level.getLinkAmount() > 1) { + if (this.linkedBlocks.size() >= this.level.getLinkAmount()) { + getPlugin().getLocale().getMessage("event.hopper.syncdone").sendPrefixedMessage(player); + cancelSync(player); + return; + } + getPlugin().getLocale().getMessage("event.hopper.syncsuccessmore") + .processPlaceholder("amount", this.level.getLinkAmount() - this.linkedBlocks.size()) + .sendPrefixedMessage(player); + return; + } + getPlugin().getLocale().getMessage("event.hopper.syncsuccess").sendPrefixedMessage(player); + cancelSync(player); + } + + /** + * Ticks a hopper to determine when it can transfer items next + * + * @param maxTick The maximum amount the hopper can be ticked before next transferring items + * @param allowLooping If true, the hopper is allowed to transfer items if the tick is also valid + * @return true if the hopper should transfer an item, otherwise false + */ + public boolean tryTick(int maxTick, boolean allowLooping) { + this.transferTick++; + if (this.transferTick >= maxTick) { + if (allowLooping) { + this.transferTick = 0; + return true; + } else { + this.transferTick = maxTick; + } + } + return false; + } + + public Location getLocation() { + return this.location.clone(); + } + + public Block getBlock() { + return this.location.getBlock(); + } + + public World getWorld() { + return this.location.getWorld(); + } + + public int getX() { + return this.location.getBlockX(); + } + + public int getY() { + return this.location.getBlockY(); + } + + public int getZ() { + return this.location.getBlockZ(); + } + + public Level getLevel() { + return this.level; + } + + public void setLevel(Level level) { + this.level = level; + } + + public UUID getPlacedBy() { + return this.placedBy; + } + + public void setPlacedBy(UUID placedBy) { + this.placedBy = placedBy; + } + + public UUID getLastPlayerOpened() { + return this.lastPlayerOpened; + } + + public void setLastPlayerOpened(UUID uuid) { + this.lastPlayerOpened = uuid; + } + + public TeleportTrigger getTeleportTrigger() { + return this.teleportTrigger; + } + + public void setTeleportTrigger(TeleportTrigger teleportTrigger) { + this.teleportTrigger = teleportTrigger; + } + + public List getLinkedBlocks() { + return new ArrayList<>(this.linkedBlocks); + } + + public void addLinkedBlock(Location location, LinkType type) { + if (type == LinkType.REGULAR) { + this.linkedBlocks.add(location); + } else { + this.filter.setEndPoint(location); + } + } + + public void removeLinkedBlock(Location location) { + this.linkedBlocks.remove(location); + } + + public void clearLinkedBlocks() { + this.linkedBlocks.clear(); + } + + public Filter getFilter() { + return this.filter; + } + + public void setFilter(Filter filter) { + this.filter = filter; + } + + public Object getDataFromModuleCache(String key) { + return this.moduleCache.getOrDefault(key, null); + } + + public void addDataToModuleCache(String key, Object data) { + this.moduleCache.put(key, data); + } + + public boolean isDataCachedInModuleCache(String key) { + return this.moduleCache.containsKey(key); + } + + public void removeDataFromModuleCache(String key) { + this.moduleCache.remove(key); + } + + public void clearModuleCache() { + this.moduleCache.clear(); + } + + public void cancelSync(Player player) { + Bukkit.getScheduler().cancelTask(this.syncId); + getPlayerDataManager().getPlayerData(player).setSyncType(null); + } + + @Override + public int getId() { + return this.id; + } + + @Override + public Map serialize() { + Map map = new HashMap<>(); + map.put("id", this.id); + map.put("level", this.level.getLevel()); + map.put("placed_by", this.placedBy.toString()); + map.put("last_opened_by", this.lastPlayerOpened.toString()); + map.put("teleport_trigger", this.teleportTrigger.name()); + map.putAll(SerializedLocation.of(this.location)); + return map; + } + + @Override + public Data deserialize(Map map) { + return new HopperImpl(map); + } + + @Override + public String getTableName() { + return "placed_hoppers"; + } + + public void setId(int id) { + this.id = id; + } + + public Player getActivePlayer() { + return this.activePlayer; + } + + public void setActivePlayer(Player activePlayer) { + this.activePlayer = activePlayer; + } + + private LevelManager getLevelManager() { + return EpicHoppersApi.getApi().getLevelManager(); + } + + private PlayerDataManager getPlayerDataManager() { + return EpicHoppersApi.getApi().getPlayerDataManager(); + } + + /** + * @deprecated The class needs refactoring to not even need the plugin. + * This is just a temporary workaround to get a Minecraft 1.20-beta build ready + */ + @Deprecated + private long getLinkTimeoutFromPluginConfig() { + return getPlugin().getConfig().getLong("Main.Timeout When Syncing Hoppers"); + } + + /** + * @deprecated The class needs refactoring to not even need the plugin. + * This is just a temporary workaround to get a Minecraft 1.20-beta build ready + */ + @Deprecated + private String getUpgradeParticleType() { + return getPlugin().getConfig().getString("Main.Upgrade Particle Type"); + } + + /** + * @deprecated The class needs refactoring to not even need the plugin. + * This is just a temporary workaround to get a Minecraft 1.20-beta build ready + */ + @Deprecated + private SongodaPlugin getPlugin() { + return (SongodaPlugin) Bukkit.getPluginManager().getPlugin("EpicHoppers"); + } +} diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperManager.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperManager.java index c383e1c..1be47d9 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperManager.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/HopperManager.java @@ -13,7 +13,7 @@ import java.util.Map; public class HopperManager { - private final Map registeredHoppers = new HashMap<>(); + private final Map registeredHoppers = new HashMap<>(); private final EpicHoppers plugin; protected boolean ready; @@ -37,18 +37,18 @@ public boolean isReady() { return this.ready; } - public Hopper addHopper(Hopper hopper) { + public HopperImpl addHopper(HopperImpl hopper) { this.registeredHoppers.put(roundLocation(hopper.getLocation()), hopper); return hopper; } @Deprecated - public void addHopper(Location location, Hopper hopper) { + public void addHopper(Location location, HopperImpl hopper) { this.registeredHoppers.put(roundLocation(location), hopper); } - public void addHoppers(Collection hoppers) { - for (Hopper hopper : hoppers) { + public void addHoppers(Collection hoppers) { + for (HopperImpl hopper : hoppers) { this.registeredHoppers.put(hopper.getLocation(), hopper); } } @@ -59,10 +59,10 @@ public void addHoppers(Collection hoppers) { * @param location The location of the hopper to remove * @return The removed hopper, or null if none was removed */ - public Hopper removeHopper(Location location) { - Hopper removed = this.registeredHoppers.remove(location); + public HopperImpl removeHopper(Location location) { + HopperImpl removed = this.registeredHoppers.remove(location); - for (Hopper hopper : this.registeredHoppers.values()) { + for (HopperImpl hopper : this.registeredHoppers.values()) { hopper.removeLinkedBlock(location); } @@ -75,19 +75,19 @@ public Hopper removeHopper(Location location) { return removed; } - public Hopper getHopper(Location location) { + public HopperImpl getHopper(Location location) { if (!this.registeredHoppers.containsKey(location = roundLocation(location))) { if (!this.ready) { throw new IllegalStateException("Hoppers are still being loaded"); } - Hopper hopper = addHopper(new Hopper(location)); - this.plugin.getDataManager().createHopper(hopper); + HopperImpl hopper = addHopper(new HopperImpl(location)); + this.plugin.getDataManager().delete(hopper); } return this.registeredHoppers.get(location); } - public Hopper getHopper(Block block) { + public HopperImpl getHopper(Block block) { return getHopper(block.getLocation()); } @@ -98,16 +98,16 @@ public boolean isHopper(Location location) { return this.registeredHoppers.containsKey(roundLocation(location)); } - public Map getHoppers() { + public Map getHoppers() { return Collections.unmodifiableMap(this.registeredHoppers); } - public Hopper getHopperFromPlayer(Player player) { + public HopperImpl getHopperFromPlayer(Player player) { if (!this.ready) { throw new IllegalStateException("Hoppers are still being loaded"); } - for (Hopper hopper : this.registeredHoppers.values()) { + for (HopperImpl hopper : this.registeredHoppers.values()) { if (hopper.getLastPlayerOpened() == player.getUniqueId()) { return hopper; } diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoCrafting.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoCrafting.java index f72d6cf..eeb028f 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoCrafting.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoCrafting.java @@ -4,10 +4,11 @@ import com.craftaro.core.gui.GuiManager; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.Methods; import com.craftaro.epichoppers.gui.GUICrafting; -import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.utils.StorageContainerCache; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -122,7 +123,7 @@ public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { for (int i = 0; i < items.length; i++) { if (!slotsToAlter.containsKey(i)) { // and yeet into space! - hopper.getWorld().dropItemNaturally(hopper.getLocation(), items[i]); + hopper.getLocation().getWorld().dropItemNaturally(hopper.getLocation(), items[i]); items[i] = null; freeSlotAfterRemovingIngredients = true; diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSell.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSell.java index ddb70aa..2a733f4 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSell.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSell.java @@ -6,11 +6,12 @@ import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.NumberUtils; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.Methods; import com.craftaro.epichoppers.gui.GUIAutoSellFilter; import com.craftaro.epichoppers.hopper.Filter; -import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.utils.StorageContainerCache; import me.gypopo.economyshopgui.api.EconomyShopGUIHook; import org.bukkit.Bukkit; diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSmelter.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSmelter.java index 436086f..a00a2bc 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSmelter.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleAutoSmelter.java @@ -5,9 +5,10 @@ import com.craftaro.core.gui.GuiManager; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.gui.GUISmeltable; -import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.utils.StorageContainerCache; import org.bukkit.Material; import org.bukkit.entity.Player; diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleBlockBreak.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleBlockBreak.java index 7e79251..04c9d7d 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleBlockBreak.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleBlockBreak.java @@ -4,9 +4,10 @@ import com.craftaro.core.compatibility.ServerVersion; import com.craftaro.core.gui.GuiManager; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.EpicHoppersApi; -import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.utils.StorageContainerCache; import org.bukkit.Location; import org.bukkit.Material; diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleMobHopper.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleMobHopper.java index d331f9b..10dca8e 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleMobHopper.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleMobHopper.java @@ -4,6 +4,7 @@ import com.craftaro.core.gui.GuiManager; import com.craftaro.core.utils.TextUtils; import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.utils.StorageContainerCache; import org.bukkit.Location; import org.bukkit.Material; @@ -49,7 +50,7 @@ public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { return; } - hopper.getWorld().getNearbyEntities(hopper.getLocation(), 5, 5, 5).stream() + hopper.getLocation().getWorld().getNearbyEntities(hopper.getLocation(), 5, 5, 5).stream() .filter(entity -> entity instanceof LivingEntity && !(entity instanceof Player) && !(entity instanceof ArmorStand)).limit(1).forEach(entity -> { Location location = hopper.getLocation().add(.5, 1, .5); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleSuction.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleSuction.java index cb370f2..cebdbde 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleSuction.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/levels/modules/ModuleSuction.java @@ -7,11 +7,12 @@ import com.craftaro.core.locale.Locale; import com.craftaro.core.third_party.com.cryptomorin.xseries.XMaterial; import com.craftaro.core.utils.TextUtils; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.Methods; -import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.utils.StorageContainerCache; -import com.songoda.ultimatestacker.UltimateStacker; +import com.craftaro.ultimatestacker.api.UltimateStackerApi; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.EntityType; @@ -157,7 +158,7 @@ public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { private int getActualItemAmount(Item item) { if (ULTIMATE_STACKER) { - return UltimateStacker.getActualItemAmount(item); + return UltimateStackerApi.getStackedItemManager().getActualItemAmount(item); } else if (WILD_STACKER) { return WildStackerAPI.getItemAmount(item); } else { @@ -168,7 +169,7 @@ private int getActualItemAmount(Item item) { private void updateAmount(Item item, int amount) { if (ULTIMATE_STACKER) { - UltimateStacker.updateItemAmount(item, item.getItemStack(), amount); + UltimateStackerApi.getStackedItemManager().updateStack(item, amount); } else if (WILD_STACKER) { WildStackerAPI.getStackedItem(item).setStackAmount(amount, true); } else { diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/teleport/TeleportHandlerImpl.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/teleport/TeleportHandlerImpl.java index 4db04d5..3d1c18d 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/teleport/TeleportHandlerImpl.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/hopper/teleport/TeleportHandlerImpl.java @@ -4,6 +4,7 @@ import com.craftaro.core.third_party.com.cryptomorin.xseries.XSound; import com.craftaro.epichoppers.EpicHoppers; import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.Methods; import org.bukkit.Bukkit; @@ -64,7 +65,7 @@ private void teleportRunner() { continue; } - Hopper hopper = this.plugin.getHopperManager().getHopper(location); + HopperImpl hopper = this.plugin.getHopperManager().getHopper(location); if (hopper.getTeleportTrigger() != TeleportTrigger.WALK_ON) { continue; diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/BlockListeners.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/BlockListeners.java index 1eaabe7..ef5b625 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/BlockListeners.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/BlockListeners.java @@ -6,7 +6,7 @@ import com.craftaro.epichoppers.api.events.HopperPlaceEvent; import com.craftaro.epichoppers.gui.GUIAutoSellFilter; import com.craftaro.epichoppers.gui.GUIFilter; -import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.HopperBuilder; import com.craftaro.epichoppers.hopper.levels.Level; import com.craftaro.epichoppers.settings.Settings; @@ -68,7 +68,7 @@ public void onBlockPlace(BlockPlaceEvent e) { return; } - Hopper hopper = this.plugin.getHopperManager().addHopper( + HopperImpl hopper = this.plugin.getHopperManager().addHopper( new HopperBuilder(e.getBlock()) .setLevel(this.plugin.getLevelManager().getLevel(item)) .setPlacedBy(player) @@ -77,7 +77,7 @@ public void onBlockPlace(BlockPlaceEvent e) { HopperPlaceEvent hopperPlaceEvent = new HopperPlaceEvent(player, hopper); Bukkit.getPluginManager().callEvent(hopperPlaceEvent); - this.plugin.getDataManager().createHopper(hopper); + this.plugin.getDataManager().save(hopper); } private int maxHoppers(Player player) { @@ -130,7 +130,7 @@ public void onBlockBreak(BlockBreakEvent event) { return; } - Hopper hopper = this.plugin.getHopperManager().getHopper(block); + HopperImpl hopper = this.plugin.getHopperManager().getHopper(block); GUIFilter.compileOpenGuiFilter(hopper); GUIAutoSellFilter.compileOpenAutoSellFilter(hopper); @@ -175,7 +175,7 @@ public void onBlockBreak(BlockBreakEvent event) { .forEach(item -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), item)); this.plugin.getHopperManager().removeHopper(block.getLocation()); - this.plugin.getDataManager().deleteHopper(hopper); + this.plugin.getDataManager().delete(hopper); this.plugin.getPlayerDataManager().getPlayerData(player).setSyncType(null); } diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/HopperListeners.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/HopperListeners.java index 6d5b0fe..2f96081 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/HopperListeners.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/HopperListeners.java @@ -2,9 +2,9 @@ import com.craftaro.core.compatibility.ServerVersion; import com.craftaro.core.nms.NmsManager; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.EpicHoppers; -import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.hopper.levels.modules.Module; import com.craftaro.epichoppers.hopper.levels.modules.ModuleAutoCrafting; import com.craftaro.epichoppers.utils.HopperDirection; @@ -40,7 +40,7 @@ public void onHop(InventoryMoveItemEvent event) { return; } - // Hopper minecarts should be able to take care of themselves + // HopperImpl minecarts should be able to take care of themselves // Let EpicHoppers take over if the hopper is pointing down though if (destination.getHolder() instanceof HopperMinecart && source.getHolder() instanceof org.bukkit.block.Hopper @@ -56,7 +56,7 @@ public void onHop(InventoryMoveItemEvent event) { return; } - // Hopper going into minecarts + // HopperImpl going into minecarts if (destination.getHolder() instanceof Minecart && source.getHolder() instanceof org.bukkit.block.Hopper) { event.setCancelled(true); return; @@ -68,12 +68,12 @@ public void onHop(InventoryMoveItemEvent event) { return; } - // Calling HopperManager#getHopper() automatically creates a new Hopper and we don't need to iterate over default-valued hoppers + // Calling HopperManager#getHopper() automatically creates a new HopperImpl and we don't need to iterate over default-valued hoppers if (!this.plugin.getHopperManager().isHopper(destinationLocation)) { return; } - Hopper toHopper = this.plugin.getHopperManager().getHopper(destinationLocation); + HopperImpl toHopper = this.plugin.getHopperManager().getHopper(destinationLocation); // minecraft 1.8 doesn't have a method to get the hopper's location from the inventory, so we use the holder instead final ItemStack toMove = event.getItem(); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/InteractListeners.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/InteractListeners.java index 22da1e6..ce18c07 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/InteractListeners.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/listeners/InteractListeners.java @@ -2,10 +2,11 @@ import com.craftaro.core.hooks.ProtectionManager; import com.craftaro.core.hooks.WorldGuardHook; +import com.craftaro.epichoppers.hopper.Hopper; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.EpicHoppers; import com.craftaro.epichoppers.gui.GUIOverview; -import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.teleport.TeleportTrigger; import com.craftaro.epichoppers.player.PlayerData; import com.craftaro.epichoppers.player.SyncType; @@ -37,12 +38,12 @@ public void onPlayerToggleSneakEvent(PlayerToggleSneakEvent event) { Location location = player.getLocation().getBlock().getRelative(BlockFace.SELF).getLocation(); Location down = location.getBlock().getRelative(BlockFace.DOWN).getLocation(); if (this.plugin.getHopperManager().isHopper(down)) { - Hopper hopper = this.plugin.getHopperManager().getHopper(down); + HopperImpl hopper = this.plugin.getHopperManager().getHopper(down); if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) { this.plugin.getTeleportHandler().tpEntity(player, hopper); } } else if (this.plugin.getHopperManager().isHopper(location)) { - Hopper hopper = this.plugin.getHopperManager().getHopper(location); + HopperImpl hopper = this.plugin.getHopperManager().getHopper(location); if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) { this.plugin.getTeleportHandler().tpEntity(player, hopper); } @@ -89,7 +90,7 @@ public void onBlockInteract(PlayerInteractEvent event) { return; } - Hopper hopper = this.plugin.getHopperManager().getHopper(event.getClickedBlock()); + HopperImpl hopper = this.plugin.getHopperManager().getHopper(event.getClickedBlock()); if (!player.getInventory().getItemInHand().getType().name().contains("PICKAXE")) { if (hopper.prepareForOpeningOverviewGui(player)) { this.plugin.getGuiManager().showGUI(player, new GUIOverview(this.plugin, hopper, player)); @@ -103,7 +104,7 @@ public void onBlockInteract(PlayerInteractEvent event) { if (event.getClickedBlock().getState() instanceof InventoryHolder || (event.getClickedBlock().getType() == Material.ENDER_CHEST && Settings.ENDERCHESTS.getBoolean())) { - Hopper hopper = playerData.getLastHopper(); + HopperImpl hopper = (HopperImpl) playerData.getLastHopper(); if (event.getClickedBlock().getLocation().equals(playerData.getLastHopper().getLocation())) { if (!hopper.getLinkedBlocks().isEmpty()) { this.plugin.getLocale().getMessage("event.hopper.syncfinish").sendPrefixedMessage(player); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/settings/Settings.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/settings/Settings.java index 6b33b9d..428ee50 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/settings/Settings.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/settings/Settings.java @@ -27,7 +27,7 @@ public class Settings { public static final ConfigSetting DISABLED_WORLDS = new ConfigSetting(CONFIG, "Main.Disabled Worlds", Arrays.asList("example1", "example2"), "Worlds where epic hoppers cannot be placed.", - "Any placed Epic Hopper will just be converted to a normal one."); + "Any placed Epic HopperImpl will just be converted to a normal one."); public static final ConfigSetting TELEPORT = new ConfigSetting(CONFIG, "Main.Allow Players To Teleport Through Hoppers", true, "Should players be able to teleport through hoppers?"); diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/tasks/HopTask.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/tasks/HopTask.java index c3699c2..5edd321 100644 --- a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/tasks/HopTask.java +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/tasks/HopTask.java @@ -1,7 +1,9 @@ package com.craftaro.epichoppers.tasks; import com.craftaro.epichoppers.boost.BoostData; +import com.craftaro.epichoppers.boost.BoostDataImpl; import com.craftaro.epichoppers.containers.CustomContainer; +import com.craftaro.epichoppers.hopper.HopperImpl; import com.craftaro.epichoppers.hopper.levels.modules.ModuleAutoCrafting; import com.craftaro.epichoppers.settings.Settings; import com.craftaro.epichoppers.utils.HopperDirection; @@ -45,7 +47,7 @@ public HopTask(EpicHoppers plugin) { @Override public void run() { - for (final com.craftaro.epichoppers.hopper.Hopper hopper : this.plugin.getHopperManager().getHoppers().values()) { + for (final HopperImpl hopper : this.plugin.getHopperManager().getHoppers().values()) { try { // Get this hopper's location. @@ -56,7 +58,7 @@ public void run() { continue; } - // Get Hopper Block. + // Get HopperImpl Block. Block block = location.getBlock(); // If block is not a hopper continue. @@ -173,7 +175,7 @@ private void debt(ItemStack item, int amountToMove, InventoryHolder currentHolde } } - private StorageContainerCache.Cache getFilterEndpoint(com.craftaro.epichoppers.hopper.Hopper hopper) { + private StorageContainerCache.Cache getFilterEndpoint(HopperImpl hopper) { // Get endpoint location. Location endPoint = hopper.getFilter().getEndPoint(); @@ -199,7 +201,7 @@ private StorageContainerCache.Cache getFilterEndpoint(com.craftaro.epichoppers.h return cache; } - private void pullItemsFromContainers(com.craftaro.epichoppers.hopper.Hopper toHopper, StorageContainerCache.Cache hopperCache, int maxToMove) { + private void pullItemsFromContainers(HopperImpl toHopper, StorageContainerCache.Cache hopperCache, int maxToMove) { // Grab items from the container above (includes storage/hopper minecarts, EpicFarming farm items and AdvancedChests chest) // If the container above is a hopper, ignore it if it's pointing down Block above = toHopper.getBlock().getRelative(BlockFace.UP); @@ -305,7 +307,7 @@ private void pullItemsFromContainers(com.craftaro.epichoppers.hopper.Hopper toHo } } - private void pushItemsIntoContainers(com.craftaro.epichoppers.hopper.Hopper hopper, StorageContainerCache.Cache hopperCache, int maxToMove, Collection blockedMaterials, HopperDirection hopperDirection) { + private void pushItemsIntoContainers(HopperImpl hopper, StorageContainerCache.Cache hopperCache, int maxToMove, Collection blockedMaterials, HopperDirection hopperDirection) { // Filter target, if any StorageContainerCache.Cache filterCache = getFilterEndpoint(hopper); @@ -395,7 +397,7 @@ private void pushItemsIntoContainers(com.craftaro.epichoppers.hopper.Hopper hopp } } - private boolean tryPushCustomContainer(com.craftaro.epichoppers.hopper.Hopper hopper, + private boolean tryPushCustomContainer(HopperImpl hopper, StorageContainerCache.Cache hopperCache, CustomContainer container, StorageContainerCache.Cache filterCache, @@ -442,7 +444,7 @@ private boolean tryPushCustomContainer(com.craftaro.epichoppers.hopper.Hopper ho return false; } - private boolean tryPush(com.craftaro.epichoppers.hopper.Hopper hopper, + private boolean tryPush(HopperImpl hopper, StorageContainerCache.Cache hopperCache, StorageContainerCache.Cache targetCache, StorageContainerCache.Cache filterCache, @@ -491,7 +493,7 @@ private boolean tryPush(com.craftaro.epichoppers.hopper.Hopper hopper, return false; } - private void processVoidFilter(com.craftaro.epichoppers.hopper.Hopper hopper, StorageContainerCache.Cache hopperCache, int maxToMove) { + private void processVoidFilter(HopperImpl hopper, StorageContainerCache.Cache hopperCache, int maxToMove) { // Loop over hopper inventory to process void filtering. if (!hopper.getFilter().getVoidList().isEmpty()) { ItemStack[] hopperContents = hopperCache.cachedInventory; diff --git a/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/utils/DataHelper.java b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/utils/DataHelper.java new file mode 100644 index 0000000..38d634b --- /dev/null +++ b/EpicHoppers-Plugin/src/main/java/com/craftaro/epichoppers/utils/DataHelper.java @@ -0,0 +1,101 @@ +package com.craftaro.epichoppers.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.craftaro.epichoppers.EpicHoppers; +import com.craftaro.epichoppers.hopper.Hopper; +import com.craftaro.epichoppers.hopper.HopperImpl; +import com.craftaro.epichoppers.hopper.ItemType; +import com.craftaro.epichoppers.hopper.LinkType; +import org.bukkit.Location; +import org.bukkit.inventory.ItemStack; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.util.Base64; +import java.util.List; + +public class DataHelper { + + public static void createLink(HopperImpl hopper, Location location, LinkType type) { + EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getDatabaseConnector().connectDSL(dslContext -> { + dslContext.insertInto(DSL.table(EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getTablePrefix() + "links")) + .columns( + DSL.field("hopper_id"), + DSL.field("link_type"), + DSL.field("world"), + DSL.field("x"), + DSL.field("y"), + DSL.field("z")) + .values( + hopper.getId(), + type.name(), + location.getWorld().getName(), + location.getBlockX(), + location.getBlockY(), + location.getBlockZ()) + .execute(); + }); + } + + public static void updateItems(HopperImpl hopper, ItemType type, List items) { +// try (Connection connection = this.databaseConnector.getConnection()) { +// String clearItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE hopper_id = ? AND item_type = ?"; +// try (PreparedStatement statement = connection.prepareStatement(clearItems)) { +// statement.setInt(1, hopper.getId()); +// statement.setString(2, type.name()); +// statement.executeUpdate(); +// } +// +// String createItem = "INSERT INTO " + this.getTablePrefix() + "items (hopper_id, item_type, item) VALUES (?, ?, ?)"; +// try (PreparedStatement statement = connection.prepareStatement(createItem)) { +// for (ItemStack item : items) { +// statement.setInt(1, hopper.getId()); +// statement.setString(2, type.name()); +// +// try (ByteArrayOutputStream stream = new ByteArrayOutputStream(); BukkitObjectOutputStream bukkitStream = new BukkitObjectOutputStream(stream)) { +// bukkitStream.writeObject(item); +// statement.setString(3, Base64.getEncoder().encodeToString(stream.toByteArray())); +// } catch (IOException e) { +// e.printStackTrace(); +// continue; +// } +// statement.addBatch(); +// } +// statement.executeBatch(); +// } +// } catch (Exception ex) { +// ex.printStackTrace(); +// } + + //Recreate with jooq + EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getDatabaseConnector().connectDSL(dslContext -> { + dslContext.deleteFrom(DSL.table(EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getTablePrefix() + "items")) + .where(DSL.field("hopper_id").eq(hopper.getId())) + .and(DSL.field("item_type").eq(type.name())) + .execute(); + + dslContext.batch( + items.stream().map(item -> dslContext.insertInto(DSL.table(EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getTablePrefix() + "items")) + .columns( + DSL.field("hopper_id"), + DSL.field("item_type"), + DSL.field("item")) + .values( + hopper.getId(), + type.name(), + Base64.getEncoder().encodeToString(ItemSerializer.serializeItem(item))) + ).toArray(Query[]::new) + ).execute(); + }); + } + + public static void deleteLinks(Hopper hopper) { + EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getDatabaseConnector().connectDSL(dslContext -> { + dslContext.deleteFrom(DSL.table(EpicHoppers.getPlugin(EpicHoppers.class).getDataManager().getTablePrefix() + "links")) + .where(DSL.field("hopper_id").eq(hopper.getId())) + .execute(); + }); + } +} diff --git a/pom.xml b/pom.xml index 7fbdce3..2d2e826 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.craftaro EpicHoppers-Parent pom - 5.0.0-SNAPSHOT + 5.0.0-SNAPSHOT-b5