Heavy code style changes and slight refactoring

This commit is contained in:
Christian Koop 2023-06-26 17:22:26 +02:00
parent 1fc846a241
commit 99cd257b86
No known key found for this signature in database
GPG Key ID: 89A8181384E010A3
56 changed files with 1198 additions and 1086 deletions

View File

@ -12,7 +12,6 @@ import com.songoda.core.database.SQLiteConnector;
import com.songoda.core.gui.GuiManager; import com.songoda.core.gui.GuiManager;
import com.songoda.core.hooks.EconomyManager; import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.hooks.ProtectionManager; import com.songoda.core.hooks.ProtectionManager;
import com.songoda.core.locale.Locale;
import com.songoda.core.third_party.de.tr7zw.nbtapi.NBTItem; import com.songoda.core.third_party.de.tr7zw.nbtapi.NBTItem;
import com.songoda.core.utils.TextUtils; import com.songoda.core.utils.TextUtils;
import com.songoda.epichoppers.boost.BoostManager; import com.songoda.epichoppers.boost.BoostManager;
@ -58,8 +57,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
public class EpicHoppers extends SongodaPlugin { public class EpicHoppers extends SongodaPlugin {
private static EpicHoppers INSTANCE;
private final GuiManager guiManager = new GuiManager(this); private final GuiManager guiManager = new GuiManager(this);
private final Config levelsConfig = new Config(this, "levels.yml"); private final Config levelsConfig = new Config(this, "levels.yml");
private HopperManager hopperManager; private HopperManager hopperManager;
@ -74,13 +71,8 @@ public class EpicHoppers extends SongodaPlugin {
private DatabaseConnector databaseConnector; private DatabaseConnector databaseConnector;
private DataManager dataManager; private DataManager dataManager;
public static EpicHoppers getInstance() {
return INSTANCE;
}
@Override @Override
public void onPluginLoad() { public void onPluginLoad() {
INSTANCE = this;
} }
@Override @Override
@ -117,9 +109,9 @@ public class EpicHoppers extends SongodaPlugin {
new CommandSettings(this) new CommandSettings(this)
); );
this.hopperManager = new HopperManager(); this.hopperManager = new HopperManager(this);
this.playerDataManager = new PlayerDataManager(); this.playerDataManager = new PlayerDataManager();
this.containerManager = new ContainerManager(this); this.containerManager = new ContainerManager();
this.boostManager = new BoostManager(); this.boostManager = new BoostManager();
// Database stuff, go! // Database stuff, go!
@ -145,8 +137,7 @@ public class EpicHoppers extends SongodaPlugin {
} }
this.dataManager = new DataManager(this.databaseConnector, this); this.dataManager = new DataManager(this.databaseConnector, this);
DataMigrationManager dataMigrationManager = new DataMigrationManager(this.databaseConnector, this.dataManager, DataMigrationManager dataMigrationManager = new DataMigrationManager(this.databaseConnector, this.dataManager, new _1_InitialMigration(this));
new _1_InitialMigration());
dataMigrationManager.runMigrations(); dataMigrationManager.runMigrations();
this.loadLevelManager(); this.loadLevelManager();
@ -155,7 +146,7 @@ public class EpicHoppers extends SongodaPlugin {
this.teleportHandler = new TeleportHandler(this); this.teleportHandler = new TeleportHandler(this);
// Register Listeners // Register Listeners
guiManager.init(); this.guiManager.init();
PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
pluginManager.registerEvents(new HopperListeners(this), this); pluginManager.registerEvents(new HopperListeners(this), this);
pluginManager.registerEvents(new EntityListeners(), this); pluginManager.registerEvents(new EntityListeners(), this);
@ -200,24 +191,25 @@ public class EpicHoppers extends SongodaPlugin {
@Override @Override
public List<Config> getExtraConfig() { public List<Config> getExtraConfig() {
return Collections.singletonList(levelsConfig); return Collections.singletonList(this.levelsConfig);
} }
private void loadLevelManager() { private void loadLevelManager() {
if (!new File(this.getDataFolder(), "levels.yml").exists()) if (!new File(this.getDataFolder(), "levels.yml").exists()) {
this.saveResource("levels.yml", false); this.saveResource("levels.yml", false);
levelsConfig.load(); }
this.levelsConfig.load();
// Load an instance of LevelManager // Load an instance of LevelManager
levelManager = new LevelManager(); this.levelManager = new LevelManager();
/* /*
* Register Levels into LevelManager from configuration. * Register Levels into LevelManager from configuration.
*/ */
levelManager.clear(); this.levelManager.clear();
for (String levelName : levelsConfig.getKeys(false)) { for (String levelName : this.levelsConfig.getKeys(false)) {
int level = Integer.parseInt(levelName.split("-")[1]); int level = Integer.parseInt(levelName.split("-")[1]);
ConfigurationSection levels = levelsConfig.getConfigurationSection(levelName); ConfigurationSection levels = this.levelsConfig.getConfigurationSection(levelName);
int radius = levels.getInt("Range"); int radius = levels.getInt("Range");
int amount = levels.getInt("Amount"); int amount = levels.getInt("Amount");
@ -245,13 +237,13 @@ public class EpicHoppers extends SongodaPlugin {
modules.add(new ModuleAutoSmelter(this, levels.getInt("AutoSmelting"))); modules.add(new ModuleAutoSmelter(this, levels.getInt("AutoSmelting")));
} }
} }
levelManager.addLevel(level, costExperience, costEconomy, radius, amount, filter, teleport, linkAmount, modules); this.levelManager.addLevel(level, costExperience, costEconomy, radius, amount, filter, teleport, linkAmount, modules);
} }
} }
private void saveModules() { private void saveModules() {
if (levelManager != null) { if (this.levelManager != null) {
for (Level level : levelManager.getLevels().values()) { for (Level level : this.levelManager.getLevels().values()) {
for (Module module : level.getRegisteredModules()) { for (Module module : level.getRegisteredModules()) {
module.saveDataToFile(); module.saveDataToFile();
} }
@ -274,48 +266,52 @@ public class EpicHoppers extends SongodaPlugin {
return nbtItem.getItem(); return nbtItem.getItem();
} }
@Override
public Locale getLocale() {
return locale;
}
public TeleportHandler getTeleportHandler() { public TeleportHandler getTeleportHandler() {
return teleportHandler; return this.teleportHandler;
} }
public BoostManager getBoostManager() { public BoostManager getBoostManager() {
return boostManager; return this.boostManager;
} }
public CommandManager getCommandManager() { public CommandManager getCommandManager() {
return commandManager; return this.commandManager;
} }
public LevelManager getLevelManager() { public LevelManager getLevelManager() {
return levelManager; return this.levelManager;
} }
public HopperManager getHopperManager() { public HopperManager getHopperManager() {
return hopperManager; return this.hopperManager;
} }
public PlayerDataManager getPlayerDataManager() { public PlayerDataManager getPlayerDataManager() {
return playerDataManager; return this.playerDataManager;
} }
public GuiManager getGuiManager() { public GuiManager getGuiManager() {
return guiManager; return this.guiManager;
} }
public DataManager getDataManager() { public DataManager getDataManager() {
return dataManager; return this.dataManager;
} }
public DatabaseConnector getDatabaseConnector() { public DatabaseConnector getDatabaseConnector() {
return databaseConnector; return this.databaseConnector;
} }
public ContainerManager getContainerManager() { public ContainerManager getContainerManager() {
return containerManager; return this.containerManager;
}
/**
* @deprecated Use {@link #getPlugin(Class)} instead
*/
@Deprecated
public static EpicHoppers getInstance() {
return EpicHoppers.getPlugin(EpicHoppers.class);
} }
} }

View File

@ -9,13 +9,22 @@ import org.bukkit.event.HandlerList;
* Called when a hopper is accessed by a player. * Called when a hopper is accessed by a player.
*/ */
public class HopperAccessEvent extends HopperEvent implements Cancellable { public class HopperAccessEvent extends HopperEvent implements Cancellable {
private static final HandlerList HANDLERS = new HandlerList(); private static final HandlerList HANDLERS = new HandlerList();
private boolean canceled = false; private boolean canceled = false;
public HopperAccessEvent(Player player, Hopper hopper) { public HopperAccessEvent(Player who, Hopper hopper) {
super(player, hopper); super(who, hopper);
}
@Override
public boolean isCancelled() {
return this.canceled;
}
@Override
public void setCancelled(boolean cancel) {
this.canceled = cancel;
} }
@Override @Override
@ -26,15 +35,4 @@ public class HopperAccessEvent extends HopperEvent implements Cancellable {
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return HANDLERS; return HANDLERS;
} }
@Override
public boolean isCancelled() {
return canceled;
}
@Override
public void setCancelled(boolean canceled) {
this.canceled = canceled;
}
} }

View File

@ -5,11 +5,10 @@ import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
public class HopperBreakEvent extends HopperEvent { public class HopperBreakEvent extends HopperEvent {
private static final HandlerList HANDLERS = new HandlerList(); private static final HandlerList HANDLERS = new HandlerList();
public HopperBreakEvent(Player player, Hopper hopper) { public HopperBreakEvent(Player who, Hopper hopper) {
super(player, hopper); super(who, hopper);
} }
@Override @Override
@ -20,5 +19,4 @@ public class HopperBreakEvent extends HopperEvent {
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return HANDLERS; return HANDLERS;
} }
} }

View File

@ -9,7 +9,6 @@ import org.bukkit.event.player.PlayerEvent;
* Represents an abstract {@link Event} given a {@link Player} and {@link Hopper} instance * Represents an abstract {@link Event} given a {@link Player} and {@link Hopper} instance
*/ */
public abstract class HopperEvent extends PlayerEvent { public abstract class HopperEvent extends PlayerEvent {
protected final Hopper hopper; protected final Hopper hopper;
public HopperEvent(Player who, Hopper hopper) { public HopperEvent(Player who, Hopper hopper) {
@ -23,7 +22,7 @@ public abstract class HopperEvent extends PlayerEvent {
* @return the broken spawner * @return the broken spawner
*/ */
public Hopper getHopper() { public Hopper getHopper() {
return hopper; return this.hopper;
} }
} }

View File

@ -5,11 +5,10 @@ import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
public class HopperPlaceEvent extends HopperEvent { public class HopperPlaceEvent extends HopperEvent {
private static final HandlerList HANDLERS = new HandlerList(); private static final HandlerList HANDLERS = new HandlerList();
public HopperPlaceEvent(Player player, Hopper hopper) { public HopperPlaceEvent(Player who, Hopper hopper) {
super(player, hopper); super(who, hopper);
} }
@Override @Override
@ -20,5 +19,4 @@ public class HopperPlaceEvent extends HopperEvent {
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return HANDLERS; return HANDLERS;
} }
} }

View File

@ -4,7 +4,6 @@ import java.util.Objects;
import java.util.UUID; import java.util.UUID;
public class BoostData { public class BoostData {
private final int multiplier; private final int multiplier;
private final long endTime; private final long endTime;
private final UUID player; private final UUID player;
@ -16,35 +15,40 @@ public class BoostData {
} }
public int getMultiplier() { public int getMultiplier() {
return multiplier; return this.multiplier;
} }
public UUID getPlayer() { public UUID getPlayer() {
return player; return this.player;
} }
public long getEndTime() { public long getEndTime() {
return endTime; return this.endTime;
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = 31 * multiplier; int result = 31 * this.multiplier;
result = 31 * result + (this.player == null ? 0 : player.hashCode()); result = 31 * result + (this.player == null ? 0 : this.player.hashCode());
result = 31 * result + (int) (endTime ^ (endTime >>> 32)); result = 31 * result + (int) (this.endTime ^ (this.endTime >>> 32));
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (this == obj) return true; if (this == obj) {
if (!(obj instanceof BoostData)) return false; return true;
}
if (!(obj instanceof BoostData)) {
return false;
}
BoostData other = (BoostData) obj; BoostData other = (BoostData) obj;
return multiplier == other.multiplier && endTime == other.endTime return this.multiplier == other.multiplier &&
&& Objects.equals(player, other.player); this.endTime == other.endTime &&
Objects.equals(this.player, other.player);
} }
} }

View File

@ -7,7 +7,6 @@ import java.util.Set;
import java.util.UUID; import java.util.UUID;
public class BoostManager { public class BoostManager {
private final Set<BoostData> registeredBoosts = new HashSet<>(); private final Set<BoostData> registeredBoosts = new HashSet<>();
public void addBoostToPlayer(BoostData data) { public void addBoostToPlayer(BoostData data) {
@ -19,16 +18,19 @@ public class BoostManager {
} }
public void addBoosts(List<BoostData> boosts) { public void addBoosts(List<BoostData> boosts) {
registeredBoosts.addAll(boosts); this.registeredBoosts.addAll(boosts);
} }
public Set<BoostData> getBoosts() { public Set<BoostData> getBoosts() {
return Collections.unmodifiableSet(registeredBoosts); return Collections.unmodifiableSet(this.registeredBoosts);
} }
public BoostData getBoost(UUID player) { public BoostData getBoost(UUID player) {
if (player == null) return null; if (player == null) {
for (BoostData boostData : registeredBoosts) { return null;
}
for (BoostData boostData : this.registeredBoosts) {
if (boostData.getPlayer().toString().equals(player.toString())) { if (boostData.getPlayer().toString().equals(player.toString())) {
if (System.currentTimeMillis() >= boostData.getEndTime()) { if (System.currentTimeMillis() >= boostData.getEndTime()) {
removeBoostFromPlayer(boostData); removeBoostFromPlayer(boostData);

View File

@ -1,19 +1,20 @@
package com.songoda.epichoppers.commands; package com.songoda.epichoppers.commands;
import com.songoda.core.commands.AbstractCommand; import com.songoda.core.commands.AbstractCommand;
import com.songoda.core.utils.NumberUtils;
import com.songoda.core.utils.TimeUtils;
import com.songoda.epichoppers.EpicHoppers; import com.songoda.epichoppers.EpicHoppers;
import com.songoda.epichoppers.boost.BoostData; import com.songoda.epichoppers.boost.BoostData;
import com.songoda.epichoppers.utils.Methods;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
public class CommandBoost extends AbstractCommand { public class CommandBoost extends AbstractCommand {
private final EpicHoppers plugin; private final EpicHoppers plugin;
public CommandBoost(EpicHoppers plugin) { public CommandBoost(EpicHoppers plugin) {
@ -24,11 +25,11 @@ public class CommandBoost extends AbstractCommand {
@Override @Override
protected ReturnType runCommand(CommandSender sender, String... args) { protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length < 2) { if (args.length < 2) {
plugin.getLocale().newMessage("&7Syntax error...").sendPrefixedMessage(sender); this.plugin.getLocale().newMessage("&7Syntax error...").sendPrefixedMessage(sender);
return ReturnType.SYNTAX_ERROR; return ReturnType.SYNTAX_ERROR;
} }
if (!Methods.isInt(args[1])) { if (!NumberUtils.isInt(args[1])) {
plugin.getLocale().newMessage("&6" + args[1] + " &7is not a number...").sendPrefixedMessage(sender); this.plugin.getLocale().newMessage("&6" + args[1] + " &7is not a number...").sendPrefixedMessage(sender);
return ReturnType.SYNTAX_ERROR; return ReturnType.SYNTAX_ERROR;
} }
@ -36,7 +37,7 @@ public class CommandBoost extends AbstractCommand {
if (args.length > 2) { if (args.length > 2) {
for (String line : args) { for (String line : args) {
long time = Methods.parseTime(line); long time = TimeUtils.parseTime(line);
duration += time; duration += time;
} }
@ -44,14 +45,14 @@ public class CommandBoost extends AbstractCommand {
Player player = Bukkit.getPlayer(args[0]); Player player = Bukkit.getPlayer(args[0]);
if (player == null) { if (player == null) {
plugin.getLocale().newMessage("&cThat player does not exist or is not online...").sendPrefixedMessage(sender); this.plugin.getLocale().newMessage("&cThat player does not exist or is not online...").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
BoostData boostData = new BoostData(Integer.parseInt(args[1]), duration == 0L ? Long.MAX_VALUE : System.currentTimeMillis() + duration, player.getUniqueId()); BoostData boostData = new BoostData(Integer.parseInt(args[1]), duration == 0L ? Long.MAX_VALUE : System.currentTimeMillis() + duration, player.getUniqueId());
plugin.getBoostManager().addBoostToPlayer(boostData); this.plugin.getBoostManager().addBoostToPlayer(boostData);
plugin.getLocale().newMessage("&7Successfully boosted &6" + Bukkit.getPlayer(args[0]).getName() this.plugin.getLocale().newMessage("&7Successfully boosted &6" + Bukkit.getPlayer(args[0]).getName()
+ "'s &7hopper transfer rates by &6" + args[1] + "x" + (duration == 0L ? "" : (" for " + Methods.makeReadable(duration))) + "&7.").sendPrefixedMessage(sender); + "'s &7hopper transfer rates by &6" + args[1] + "x" + (duration == 0L ? "" : (" for " + TimeUtils.makeReadable(duration))) + "&7.").sendPrefixedMessage(sender);
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }
@ -68,7 +69,8 @@ public class CommandBoost extends AbstractCommand {
} else if (args.length == 3) { } else if (args.length == 3) {
return Arrays.asList("1m", "1h", "1d"); return Arrays.asList("1m", "1h", "1d");
} }
return null;
return Collections.emptyList();
} }
@Override @Override

View File

@ -12,7 +12,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
public class CommandGive extends AbstractCommand { public class CommandGive extends AbstractCommand {
private final EpicHoppers plugin; private final EpicHoppers plugin;
public CommandGive(EpicHoppers plugin) { public CommandGive(EpicHoppers plugin) {
@ -26,29 +25,29 @@ public class CommandGive extends AbstractCommand {
return ReturnType.SYNTAX_ERROR; return ReturnType.SYNTAX_ERROR;
} }
if (Bukkit.getPlayerExact(args[0]) == null) { if (Bukkit.getPlayerExact(args[0]) == null) {
plugin.getLocale().newMessage("&cThat username does not exist, or the user is not online!").sendPrefixedMessage(sender); this.plugin.getLocale().newMessage("&cThat username does not exist, or the user is not online!").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
Level level = plugin.getLevelManager().getLowestLevel(); Level level = this.plugin.getLevelManager().getLowestLevel();
Player player; Player player;
if (Bukkit.getPlayer(args[0]) == null) { if (Bukkit.getPlayer(args[0]) == null) {
plugin.getLocale().newMessage("&cThat player does not exist or is currently offline.").sendPrefixedMessage(sender); this.plugin.getLocale().newMessage("&cThat player does not exist or is currently offline.").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} else { } else {
player = Bukkit.getPlayer(args[0]); player = Bukkit.getPlayer(args[0]);
} }
if (!plugin.getLevelManager().isLevel(Integer.parseInt(args[1]))) { if (!this.plugin.getLevelManager().isLevel(Integer.parseInt(args[1]))) {
plugin.getLocale().newMessage("&cNot a valid level... The current valid levels are: &4" + level.getLevel() + "-" + plugin.getLevelManager().getHighestLevel().getLevel() + "&c.") this.plugin.getLocale().newMessage("&cNot a valid level... The current valid levels are: &4" + level.getLevel() + "-" + this.plugin.getLevelManager().getHighestLevel().getLevel() + "&c.")
.sendPrefixedMessage(sender); .sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} else { } else {
level = plugin.getLevelManager().getLevel(Integer.parseInt(args[1])); level = this.plugin.getLevelManager().getLevel(Integer.parseInt(args[1]));
} }
player.getInventory().addItem(plugin.newHopperItem(level)); player.getInventory().addItem(this.plugin.newHopperItem(level));
plugin.getLocale().getMessage("command.give.success").processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); this.plugin.getLocale().getMessage("command.give.success").processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player);
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }

View File

@ -7,7 +7,6 @@ import org.bukkit.command.CommandSender;
import java.util.List; import java.util.List;
public class CommandReload extends AbstractCommand { public class CommandReload extends AbstractCommand {
private final EpicHoppers plugin; private final EpicHoppers plugin;
public CommandReload(EpicHoppers plugin) { public CommandReload(EpicHoppers plugin) {
@ -17,8 +16,8 @@ public class CommandReload extends AbstractCommand {
@Override @Override
protected ReturnType runCommand(CommandSender sender, String... args) { protected ReturnType runCommand(CommandSender sender, String... args) {
plugin.reloadConfig(); this.plugin.reloadConfig();
plugin.getLocale().getMessage("&7Configuration and Language files reloaded.").sendPrefixedMessage(sender); this.plugin.getLocale().getMessage("&7Configuration and Language files reloaded.").sendPrefixedMessage(sender);
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }

View File

@ -9,7 +9,6 @@ import org.bukkit.entity.Player;
import java.util.List; import java.util.List;
public class CommandSettings extends AbstractCommand { public class CommandSettings extends AbstractCommand {
private final EpicHoppers plugin; private final EpicHoppers plugin;
public CommandSettings(EpicHoppers plugin) { public CommandSettings(EpicHoppers plugin) {
@ -19,7 +18,7 @@ public class CommandSettings extends AbstractCommand {
@Override @Override
protected ReturnType runCommand(CommandSender sender, String... args) { protected ReturnType runCommand(CommandSender sender, String... args) {
plugin.getGuiManager().showGUI((Player) sender, new PluginConfigGui(plugin)); this.plugin.getGuiManager().showGUI((Player) sender, new PluginConfigGui(this.plugin));
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }

View File

@ -5,9 +5,7 @@ import com.songoda.skyblock.permission.BasicPermission;
import com.songoda.skyblock.permission.PermissionType; import com.songoda.skyblock.permission.PermissionType;
public class EpicHoppersPermission extends BasicPermission { public class EpicHoppersPermission extends BasicPermission {
public EpicHoppersPermission() { public EpicHoppersPermission() {
super("EpicHoppers", CompatibleMaterial.HOPPER, PermissionType.GENERIC); super("EpicHoppers", CompatibleMaterial.HOPPER, PermissionType.GENERIC);
} }
} }

View File

@ -1,6 +1,5 @@
package com.songoda.epichoppers.containers; package com.songoda.epichoppers.containers;
import com.songoda.epichoppers.EpicHoppers;
import com.songoda.epichoppers.containers.impl.AdvancedChestImplementation; import com.songoda.epichoppers.containers.impl.AdvancedChestImplementation;
import com.songoda.epichoppers.containers.impl.EpicFarmingImplementation; import com.songoda.epichoppers.containers.impl.EpicFarmingImplementation;
import com.songoda.epichoppers.containers.impl.FabledSkyBlockImplementation; import com.songoda.epichoppers.containers.impl.FabledSkyBlockImplementation;
@ -13,12 +12,9 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
public class ContainerManager { public class ContainerManager {
private final EpicHoppers plugin;
private final Set<IContainer> customContainers; private final Set<IContainer> customContainers;
public ContainerManager(EpicHoppers plugin) { public ContainerManager() {
this.plugin = plugin;
this.customContainers = new HashSet<>(); this.customContainers = new HashSet<>();
registerCustomContainerImplementation("AdvancedChests", new AdvancedChestImplementation()); registerCustomContainerImplementation("AdvancedChests", new AdvancedChestImplementation());
@ -27,13 +23,13 @@ public class ContainerManager {
} }
public Set<IContainer> getCustomContainerImplementations() { public Set<IContainer> getCustomContainerImplementations() {
return Collections.unmodifiableSet(customContainers); return Collections.unmodifiableSet(this.customContainers);
} }
public void registerCustomContainerImplementation(String requiredPlugin, IContainer container) { public void registerCustomContainerImplementation(String requiredPlugin, IContainer container) {
PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
if (requiredPlugin != null && pluginManager.isPluginEnabled(requiredPlugin)) { if (requiredPlugin != null && pluginManager.isPluginEnabled(requiredPlugin)) {
customContainers.add(container); this.customContainers.add(container);
} }
} }
@ -42,7 +38,7 @@ public class ContainerManager {
} }
public CustomContainer getCustomContainer(Block block) { public CustomContainer getCustomContainer(Block block) {
for (IContainer container : customContainers) { for (IContainer container : this.customContainers) {
CustomContainer customContainer = container.getCustomContainer(block); CustomContainer customContainer = container.getCustomContainer(block);
if (customContainer.isContainer()) { if (customContainer.isContainer()) {
return customContainer; return customContainer;

View File

@ -4,14 +4,17 @@ import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public abstract class CustomContainer { public abstract class CustomContainer {
private final Block block; private final Block block;
public CustomContainer(Block block) { public CustomContainer(Block block) {
this.block = block; this.block = block;
} }
public abstract boolean addToContainer(ItemStack itemToMove); public abstract boolean addToContainer(ItemStack itemToMove);
public abstract ItemStack[] getItems(); public abstract ItemStack[] getItems();
public abstract void removeFromContainer(ItemStack itemToMove, int amountToMove); public abstract void removeFromContainer(ItemStack itemToMove, int amountToMove);
public abstract boolean isContainer(); public abstract boolean isContainer();
} }

View File

@ -3,6 +3,5 @@ package com.songoda.epichoppers.containers;
import org.bukkit.block.Block; import org.bukkit.block.Block;
public interface IContainer { public interface IContainer {
CustomContainer getCustomContainer(Block block); CustomContainer getCustomContainer(Block block);
} }

View File

@ -8,13 +8,12 @@ import us.lynuxcraft.deadsilenceiv.advancedchests.AdvancedChestsAPI;
import us.lynuxcraft.deadsilenceiv.advancedchests.chest.AdvancedChest; import us.lynuxcraft.deadsilenceiv.advancedchests.chest.AdvancedChest;
public class AdvancedChestImplementation implements IContainer { public class AdvancedChestImplementation implements IContainer {
@Override @Override
public CustomContainer getCustomContainer(Block block) { public CustomContainer getCustomContainer(Block block) {
return new Container(block); return new Container(block);
} }
class Container extends CustomContainer { static class Container extends CustomContainer {
private final AdvancedChest advancedChest; private final AdvancedChest advancedChest;
public Container(Block block) { public Container(Block block) {
@ -24,23 +23,26 @@ public class AdvancedChestImplementation implements IContainer {
@Override @Override
public boolean addToContainer(ItemStack itemToMove) { public boolean addToContainer(ItemStack itemToMove) {
return AdvancedChestsAPI.addItemToChest(advancedChest, itemToMove); return AdvancedChestsAPI.addItemToChest(this.advancedChest, itemToMove);
} }
@Override @Override
public ItemStack[] getItems() { public ItemStack[] getItems() {
return advancedChest.getAllItems().toArray(new ItemStack[0]); return this.advancedChest.getAllItems().toArray(new ItemStack[0]);
} }
@Override @Override
public void removeFromContainer(ItemStack itemToMove, int amountToMove) { public void removeFromContainer(ItemStack itemToMove, int amountToMove) {
for (ItemStack item : advancedChest.getAllItems()) { for (ItemStack item : this.advancedChest.getAllItems()) {
if (item == null) return; if (item == null) {
return;
}
if (itemToMove.getType() == item.getType()) { if (itemToMove.getType() == item.getType()) {
item.setAmount(item.getAmount() - amountToMove); item.setAmount(item.getAmount() - amountToMove);
if (item.getAmount() <= 0) if (item.getAmount() <= 0)
advancedChest.getAllItems().remove(item); this.advancedChest.getAllItems().remove(item);
return; return;
} }
} }
@ -48,7 +50,7 @@ public class AdvancedChestImplementation implements IContainer {
@Override @Override
public boolean isContainer() { public boolean isContainer() {
return advancedChest != null; return this.advancedChest != null;
} }
} }
} }

View File

@ -9,13 +9,12 @@ import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class EpicFarmingImplementation implements IContainer { public class EpicFarmingImplementation implements IContainer {
@Override @Override
public CustomContainer getCustomContainer(Block block) { public CustomContainer getCustomContainer(Block block) {
return new Container(block); return new Container(block);
} }
class Container extends CustomContainer { static class Container extends CustomContainer {
private final Farm farm; private final Farm farm;
public Container(Block block) { public Container(Block block) {
@ -25,28 +24,28 @@ public class EpicFarmingImplementation implements IContainer {
@Override @Override
public boolean addToContainer(ItemStack itemToMove) { public boolean addToContainer(ItemStack itemToMove) {
if (!farm.willFit(itemToMove)) { if (!this.farm.willFit(itemToMove)) {
return false; return false;
} }
farm.addItem(itemToMove); this.farm.addItem(itemToMove);
return true; return true;
} }
@Override @Override
public ItemStack[] getItems() { public ItemStack[] getItems() {
return farm.getItems() return this.farm.getItems()
.stream().filter(i -> CompatibleMaterial.getMaterial(i) != CompatibleMaterial.BONE_MEAL) .stream().filter(item -> CompatibleMaterial.getMaterial(item) != CompatibleMaterial.BONE_MEAL)
.toArray(ItemStack[]::new); .toArray(ItemStack[]::new);
} }
@Override @Override
public void removeFromContainer(ItemStack itemToMove, int amountToMove) { public void removeFromContainer(ItemStack itemToMove, int amountToMove) {
farm.removeMaterial(itemToMove.getType(), amountToMove); this.farm.removeMaterial(itemToMove.getType(), amountToMove);
} }
@Override @Override
public boolean isContainer() { public boolean isContainer() {
return farm != null; return this.farm != null;
} }
} }
} }

View File

@ -10,13 +10,12 @@ import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class FabledSkyBlockImplementation implements IContainer { public class FabledSkyBlockImplementation implements IContainer {
@Override @Override
public CustomContainer getCustomContainer(Block block) { public CustomContainer getCustomContainer(Block block) {
return new Container(block); return new Container(block);
} }
class Container extends CustomContainer { static class Container extends CustomContainer {
private final Stackable stackable; private final Stackable stackable;
public Container(Block block) { public Container(Block block) {
@ -30,13 +29,13 @@ public class FabledSkyBlockImplementation implements IContainer {
@Override @Override
public boolean addToContainer(ItemStack itemToMove) { public boolean addToContainer(ItemStack itemToMove) {
if (CompatibleMaterial.getMaterial(itemToMove) != stackable.getMaterial()) { if (CompatibleMaterial.getMaterial(itemToMove) != this.stackable.getMaterial()) {
return false; return false;
} }
stackable.addOne(); this.stackable.addOne();
if (stackable.getMaxSize() > 0 && stackable.isMaxSize()) { if (this.stackable.getMaxSize() > 0 && this.stackable.isMaxSize()) {
stackable.setSize(stackable.getMaxSize()); this.stackable.setSize(this.stackable.getMaxSize());
return false; return false;
} }
@ -45,22 +44,21 @@ public class FabledSkyBlockImplementation implements IContainer {
@Override @Override
public ItemStack[] getItems() { public ItemStack[] getItems() {
ItemStack[] array = { new ItemStack(stackable.getMaterial().getMaterial(), stackable.getSize()) }; return new ItemStack[]{new ItemStack(this.stackable.getMaterial().getMaterial(), this.stackable.getSize())};
return array;
} }
@Override @Override
public void removeFromContainer(ItemStack itemToMove, int amountToMove) { public void removeFromContainer(ItemStack itemToMove, int amountToMove) {
if (CompatibleMaterial.getMaterial(itemToMove) != stackable.getMaterial()) { if (CompatibleMaterial.getMaterial(itemToMove) != this.stackable.getMaterial()) {
return; return;
} }
stackable.setSize(stackable.getSize() - amountToMove); this.stackable.setSize(this.stackable.getSize() - amountToMove);
} }
@Override @Override
public boolean isContainer() { public boolean isContainer() {
return stackable != null; return this.stackable != null;
} }
} }
} }

View File

@ -34,14 +34,13 @@ import java.util.UUID;
import java.util.function.Consumer; import java.util.function.Consumer;
public class DataManager extends DataManagerAbstract { public class DataManager extends DataManagerAbstract {
public DataManager(DatabaseConnector databaseConnector, Plugin plugin) { public DataManager(DatabaseConnector databaseConnector, Plugin plugin) {
super(databaseConnector, plugin); super(databaseConnector, plugin);
} }
public void createBoost(BoostData boostData) { public void createBoost(BoostData boostData) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String createBoostedPlayer = "INSERT INTO " + this.getTablePrefix() + "boosted_players (player, multiplier, end_time) VALUES (?, ?, ?)"; String createBoostedPlayer = "INSERT INTO " + this.getTablePrefix() + "boosted_players (player, multiplier, end_time) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(createBoostedPlayer); PreparedStatement statement = connection.prepareStatement(createBoostedPlayer);
statement.setString(1, boostData.getPlayer().toString()); statement.setString(1, boostData.getPlayer().toString());
@ -57,7 +56,7 @@ public class DataManager extends DataManagerAbstract {
public void getBoosts(Consumer<List<BoostData>> callback) { public void getBoosts(Consumer<List<BoostData>> callback) {
List<BoostData> boosts = new ArrayList<>(); List<BoostData> boosts = new ArrayList<>();
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
String selectBoostedPlayers = "SELECT * FROM " + this.getTablePrefix() + "boosted_players"; String selectBoostedPlayers = "SELECT * FROM " + this.getTablePrefix() + "boosted_players";
ResultSet result = statement.executeQuery(selectBoostedPlayers); ResultSet result = statement.executeQuery(selectBoostedPlayers);
@ -77,7 +76,7 @@ public class DataManager extends DataManagerAbstract {
public void deleteBoost(BoostData boostData) { public void deleteBoost(BoostData boostData) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String deleteBoost = "DELETE FROM " + this.getTablePrefix() + "boosted_players WHERE end_time = ?"; String deleteBoost = "DELETE FROM " + this.getTablePrefix() + "boosted_players WHERE end_time = ?";
PreparedStatement statement = connection.prepareStatement(deleteBoost); PreparedStatement statement = connection.prepareStatement(deleteBoost);
statement.setLong(1, boostData.getEndTime()); statement.setLong(1, boostData.getEndTime());
@ -90,7 +89,7 @@ public class DataManager extends DataManagerAbstract {
public void createLink(Hopper hopper, Location location, LinkType type) { public void createLink(Hopper hopper, Location location, LinkType type) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)"; String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(createLink); PreparedStatement statement = connection.prepareStatement(createLink);
statement.setInt(1, hopper.getId()); statement.setInt(1, hopper.getId());
@ -110,7 +109,7 @@ public class DataManager extends DataManagerAbstract {
public void updateItems(Hopper hopper, ItemType type, List<ItemStack> items) { public void updateItems(Hopper hopper, ItemType type, List<ItemStack> items) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String clearItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE hopper_id = ? AND item_type = ?"; String clearItems = "DELETE FROM " + this.getTablePrefix() + "items WHERE hopper_id = ? AND item_type = ?";
try (PreparedStatement statement = connection.prepareStatement(clearItems)) { try (PreparedStatement statement = connection.prepareStatement(clearItems)) {
statement.setInt(1, hopper.getId()); statement.setInt(1, hopper.getId());
@ -143,7 +142,7 @@ public class DataManager extends DataManagerAbstract {
public void deleteLink(Hopper hopper, Location location) { public void deleteLink(Hopper hopper, Location location) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String deleteLink = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ? AND world = ? AND x = ? AND y = ? AND z = ?"; String deleteLink = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ? AND world = ? AND x = ? AND y = ? AND z = ?";
PreparedStatement statement = connection.prepareStatement(deleteLink); PreparedStatement statement = connection.prepareStatement(deleteLink);
statement.setInt(1, hopper.getId()); statement.setInt(1, hopper.getId());
@ -160,7 +159,7 @@ public class DataManager extends DataManagerAbstract {
public void deleteLinks(Hopper hopper) { public void deleteLinks(Hopper hopper) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String deleteHopperLinks = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ?"; String deleteHopperLinks = "DELETE FROM " + this.getTablePrefix() + "links WHERE hopper_id = ?";
PreparedStatement statement = connection.prepareStatement(deleteHopperLinks); PreparedStatement statement = connection.prepareStatement(deleteHopperLinks);
statement.setInt(1, hopper.getId()); statement.setInt(1, hopper.getId());
@ -172,13 +171,14 @@ public class DataManager extends DataManagerAbstract {
} }
public void createHoppers(List<Hopper> hoppers) { public void createHoppers(List<Hopper> hoppers) {
for (Hopper hopper : hoppers) for (Hopper hopper : hoppers) {
createHopper(hopper); createHopper(hopper);
} }
}
public void createHopper(Hopper hopper) { public void createHopper(Hopper hopper) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ 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 (?, ?, ?, ?, ?, ?, ?, ?)"; 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)) { try (PreparedStatement statement = connection.prepareStatement(createHopper)) {
statement.setInt(1, hopper.getLevel().getLevel()); statement.setInt(1, hopper.getLevel().getLevel());
@ -204,20 +204,25 @@ public class DataManager extends DataManagerAbstract {
Map<ItemStack, ItemType> items = new HashMap<>(); Map<ItemStack, ItemType> items = new HashMap<>();
Filter filter = hopper.getFilter(); Filter filter = hopper.getFilter();
for (ItemStack item : filter.getWhiteList()) for (ItemStack item : filter.getWhiteList()) {
items.put(item, ItemType.WHITELIST); items.put(item, ItemType.WHITELIST);
}
for (ItemStack item : filter.getBlackList()) for (ItemStack item : filter.getBlackList()) {
items.put(item, ItemType.BLACKLIST); items.put(item, ItemType.BLACKLIST);
}
for (ItemStack item : filter.getVoidList()) for (ItemStack item : filter.getVoidList()) {
items.put(item, ItemType.VOID); items.put(item, ItemType.VOID);
}
for (ItemStack item : filter.getAutoSellWhiteList()) for (ItemStack item : filter.getAutoSellWhiteList()) {
items.put(item, ItemType.AUTO_SELL_WHITELIST); items.put(item, ItemType.AUTO_SELL_WHITELIST);
}
for (ItemStack item : filter.getAutoSellBlackList()) for (ItemStack item : filter.getAutoSellBlackList()) {
items.put(item, ItemType.AUTO_SELL_BLACKLIST); items.put(item, ItemType.AUTO_SELL_BLACKLIST);
}
String createItem = "INSERT INTO " + this.getTablePrefix() + "items (hopper_id, item_type, item) VALUES (?, ?, ?)"; String createItem = "INSERT INTO " + this.getTablePrefix() + "items (hopper_id, item_type, item) VALUES (?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(createItem)) { try (PreparedStatement statement = connection.prepareStatement(createItem)) {
@ -239,11 +244,13 @@ public class DataManager extends DataManagerAbstract {
Map<Location, LinkType> links = new HashMap<>(); Map<Location, LinkType> links = new HashMap<>();
for (Location location : hopper.getLinkedBlocks()) for (Location location : hopper.getLinkedBlocks()) {
links.put(location, LinkType.REGULAR); links.put(location, LinkType.REGULAR);
}
if (filter.getEndPoint() != null) if (filter.getEndPoint() != null) {
links.put(filter.getEndPoint(), LinkType.REJECT); links.put(filter.getEndPoint(), LinkType.REJECT);
}
String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)"; String createLink = "INSERT INTO " + this.getTablePrefix() + "links (hopper_id, link_type, world, x, y, z) VALUES (?, ?, ?, ?, ?, ?)";
try (PreparedStatement statement = connection.prepareStatement(createLink)) { try (PreparedStatement statement = connection.prepareStatement(createLink)) {
@ -269,7 +276,7 @@ public class DataManager extends DataManagerAbstract {
public void updateHopper(Hopper hopper) { public void updateHopper(Hopper hopper) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String updateHopper = "UPDATE " + this.getTablePrefix() + "placed_hoppers SET level = ?, placed_by = ?, last_opened_by = ?, teleport_trigger = ? WHERE id = ?"; String updateHopper = "UPDATE " + this.getTablePrefix() + "placed_hoppers SET level = ?, placed_by = ?, last_opened_by = ?, teleport_trigger = ? WHERE id = ?";
PreparedStatement statement = connection.prepareStatement(updateHopper); PreparedStatement statement = connection.prepareStatement(updateHopper);
statement.setInt(1, hopper.getLevel().getLevel()); statement.setInt(1, hopper.getLevel().getLevel());
@ -286,7 +293,7 @@ public class DataManager extends DataManagerAbstract {
public void deleteHopper(Hopper hopper) { public void deleteHopper(Hopper hopper) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
String deleteHopper = "DELETE FROM " + this.getTablePrefix() + "placed_hoppers WHERE id = ?"; String deleteHopper = "DELETE FROM " + this.getTablePrefix() + "placed_hoppers WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(deleteHopper)) { try (PreparedStatement statement = connection.prepareStatement(deleteHopper)) {
statement.setInt(1, hopper.getId()); statement.setInt(1, hopper.getId());
@ -312,7 +319,7 @@ public class DataManager extends DataManagerAbstract {
public void getHoppers(Consumer<Map<Integer, Hopper>> callback) { public void getHoppers(Consumer<Map<Integer, Hopper>> callback) {
this.runAsync(() -> { this.runAsync(() -> {
try (Connection connection = this.databaseConnector.getConnection()){ try (Connection connection = this.databaseConnector.getConnection()) {
Map<Integer, Hopper> hoppers = new HashMap<>(); Map<Integer, Hopper> hoppers = new HashMap<>();
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
@ -321,8 +328,9 @@ public class DataManager extends DataManagerAbstract {
while (result.next()) { while (result.next()) {
World world = Bukkit.getWorld(result.getString("world")); World world = Bukkit.getWorld(result.getString("world"));
if (world == null) if (world == null) {
continue; continue;
}
int id = result.getInt("id"); int id = result.getInt("id");
int level = result.getInt("level"); int level = result.getInt("level");
@ -342,7 +350,7 @@ public class DataManager extends DataManagerAbstract {
Hopper hopper = new HopperBuilder(location) Hopper hopper = new HopperBuilder(location)
.setId(id) .setId(id)
.setLevel(EpicHoppers.getInstance().getLevelManager().getLevel(level)) .setLevel(((EpicHoppers) this.plugin).getLevelManager().getLevel(level))
.setPlacedBy(placedBy) .setPlacedBy(placedBy)
.setLastPlayerOpened(lastOpenedBy) .setLastPlayerOpened(lastOpenedBy)
.setTeleportTrigger(teleportTrigger) .setTeleportTrigger(teleportTrigger)
@ -358,8 +366,9 @@ public class DataManager extends DataManagerAbstract {
while (result.next()) { while (result.next()) {
World world = Bukkit.getWorld(result.getString("world")); World world = Bukkit.getWorld(result.getString("world"));
if (world == null) if (world == null) {
continue; continue;
}
int id = result.getInt("hopper_id"); int id = result.getInt("hopper_id");
LinkType type = LinkType.valueOf(result.getString("link_type")); LinkType type = LinkType.valueOf(result.getString("link_type"));
@ -370,7 +379,9 @@ public class DataManager extends DataManagerAbstract {
Location location = new Location(world, x, y, z); Location location = new Location(world, x, y, z);
Hopper hopper = hoppers.get(id); Hopper hopper = hoppers.get(id);
if (hopper == null) break; if (hopper == null) {
break;
}
hopper.addLinkedBlock(location, type); hopper.addLinkedBlock(location, type);
} }
@ -392,12 +403,15 @@ public class DataManager extends DataManagerAbstract {
} }
Hopper hopper = hoppers.get(id); Hopper hopper = hoppers.get(id);
if (hopper == null) break; if (hopper == null) {
break;
}
if (item != null) if (item != null) {
hopper.getFilter().addItem(item, type); hopper.getFilter().addItem(item, type);
} }
} }
}
this.sync(() -> callback.accept(hoppers)); this.sync(() -> callback.accept(hoppers));
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();

View File

@ -9,14 +9,16 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
public class _1_InitialMigration extends DataMigration { public class _1_InitialMigration extends DataMigration {
private final EpicHoppers plugin;
public _1_InitialMigration() { public _1_InitialMigration(EpicHoppers plugin) {
super(1); super(1);
this.plugin = plugin;
} }
@Override @Override
public void migrate(Connection connection, String tablePrefix) throws SQLException { public void migrate(Connection connection, String tablePrefix) throws SQLException {
String autoIncrement = EpicHoppers.getInstance().getDatabaseConnector() instanceof MySQLConnector ? " AUTO_INCREMENT" : ""; String autoIncrement = this.plugin.getDatabaseConnector() instanceof MySQLConnector ? " AUTO_INCREMENT" : "";
// Create hoppers table // Create hoppers table
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {

View File

@ -18,7 +18,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class GUIAutoSellFilter extends CustomizableGui { public class GUIAutoSellFilter extends CustomizableGui {
private static final List<GUIAutoSellFilter> openInventories = new ArrayList<>(); private static final List<GUIAutoSellFilter> OPEN_INVENTORIES = new ArrayList<>();
private final EpicHoppers plugin; private final EpicHoppers plugin;
private final Hopper hopper; private final Hopper hopper;
@ -36,10 +36,10 @@ public class GUIAutoSellFilter extends CustomizableGui {
setDefaultItem(null); setDefaultItem(null);
setAcceptsItems(true); setAcceptsItems(true);
setOnOpen((event) -> GUIAutoSellFilter.openInventories.add(this)); setOnOpen((event) -> GUIAutoSellFilter.OPEN_INVENTORIES.add(this));
setOnClose((event) -> { setOnClose((event) -> {
GUIAutoSellFilter.openInventories.remove(this); GUIAutoSellFilter.OPEN_INVENTORIES.remove(this);
hopper.setActivePlayer(null); hopper.setActivePlayer(null);
compile(); compile();
}); });
@ -63,7 +63,7 @@ public class GUIAutoSellFilter extends CustomizableGui {
setButton("back", 8, GuiUtils.createButtonItem(CompatibleMaterial.ARROW.getItem(), setButton("back", 8, GuiUtils.createButtonItem(CompatibleMaterial.ARROW.getItem(),
plugin.getLocale().getMessage("general.nametag.back").getMessage()), plugin.getLocale().getMessage("general.nametag.back").getMessage()),
(event) -> { (event) -> {
hopper.overview(guiManager, event.player); hopper.overview(this.guiManager, event.player);
compile(); compile();
}); });
@ -80,8 +80,10 @@ public class GUIAutoSellFilter extends CustomizableGui {
int num = 0; int num = 0;
for (ItemStack m : filter.getAutoSellWhiteList()) { for (ItemStack m : filter.getAutoSellWhiteList()) {
if (num >= filter.getAutoSellWhiteList().size()) break; if (num >= filter.getAutoSellWhiteList().size()) {
setItem(whiteListSlots[num], new ItemStack(m)); break;
}
setItem(this.whiteListSlots[num], new ItemStack(m));
num++; num++;
} }
@ -98,8 +100,10 @@ public class GUIAutoSellFilter extends CustomizableGui {
num = 0; num = 0;
for (ItemStack m : filter.getAutoSellBlackList()) { for (ItemStack m : filter.getAutoSellBlackList()) {
if (num >= filter.getAutoSellBlackList().size()) break; if (num >= filter.getAutoSellBlackList().size()) {
setItem(blackListSlots[num], new ItemStack(m)); break;
}
setItem(this.blackListSlots[num], new ItemStack(m));
num++; num++;
} }
@ -109,7 +113,11 @@ public class GUIAutoSellFilter extends CustomizableGui {
indicatorMeta.setDisplayName(plugin.getLocale().getMessage("interface.autosell-filter.infotitle").getMessage()); indicatorMeta.setDisplayName(plugin.getLocale().getMessage("interface.autosell-filter.infotitle").getMessage());
ArrayList<String> loreInfo = new ArrayList<>(); ArrayList<String> loreInfo = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.autosell-filter.infolore").getMessage().split("\\|"); String[] parts = plugin
.getLocale()
.getMessage("interface.autosell-filter.infolore")
.getMessage()
.split("\\|");
for (String line : parts) { for (String line : parts) {
loreInfo.add(TextUtils.formatText(line)); loreInfo.add(TextUtils.formatText(line));
@ -127,22 +135,24 @@ public class GUIAutoSellFilter extends CustomizableGui {
} }
private void compile() { private void compile() {
ItemStack[] items = inventory.getContents(); ItemStack[] items = this.inventory.getContents();
Filter filter = hopper.getFilter(); Filter filter = this.hopper.getFilter();
List<ItemStack> whiteListItems = new ArrayList<>(); List<ItemStack> whiteListItems = new ArrayList<>();
List<ItemStack> blackListItems = new ArrayList<>(); List<ItemStack> blackListItems = new ArrayList<>();
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
for (int slot : whiteListSlots) { for (int slot : this.whiteListSlots) {
if (slot != i) continue; if (slot != i) {
continue;
}
if (items[i] != null && !items[i].getType().isAir()) { if (items[i] != null && !items[i].getType().isAir()) {
ItemStack item = items[i]; ItemStack item = items[i];
if (item.getAmount() != 1) { if (item.getAmount() != 1) {
item.setAmount(item.getAmount() - 1); item.setAmount(item.getAmount() - 1);
Bukkit.getPlayer(hopper.getLastPlayerOpened()).getInventory().addItem(item); Bukkit.getPlayer(this.hopper.getLastPlayerOpened()).getInventory().addItem(item);
item.setAmount(1); item.setAmount(1);
} }
@ -150,14 +160,16 @@ public class GUIAutoSellFilter extends CustomizableGui {
} }
} }
for (int slot : blackListSlots) { for (int slot : this.blackListSlots) {
if (slot != i) continue; if (slot != i) {
continue;
}
if (items[i] != null && !items[i].getType().isAir()) { if (items[i] != null && !items[i].getType().isAir()) {
ItemStack item = items[i]; ItemStack item = items[i];
if (item.getAmount() != 1) { if (item.getAmount() != 1) {
item.setAmount(item.getAmount() - 1); item.setAmount(item.getAmount() - 1);
Bukkit.getPlayer(hopper.getLastPlayerOpened()).getInventory().addItem(item); Bukkit.getPlayer(this.hopper.getLastPlayerOpened()).getInventory().addItem(item);
item.setAmount(1); item.setAmount(1);
} }
blackListItems.add(item); blackListItems.add(item);
@ -167,12 +179,12 @@ public class GUIAutoSellFilter extends CustomizableGui {
filter.setAutoSellWhiteList(whiteListItems); filter.setAutoSellWhiteList(whiteListItems);
filter.setAutoSellBlackList(blackListItems); filter.setAutoSellBlackList(blackListItems);
plugin.getDataManager().updateItems(hopper, ItemType.AUTO_SELL_WHITELIST, whiteListItems); this.plugin.getDataManager().updateItems(this.hopper, ItemType.AUTO_SELL_WHITELIST, whiteListItems);
plugin.getDataManager().updateItems(hopper, ItemType.AUTO_SELL_BLACKLIST, blackListItems); this.plugin.getDataManager().updateItems(this.hopper, ItemType.AUTO_SELL_BLACKLIST, blackListItems);
} }
public static void compileOpenAutoSellFilter(Hopper hopper) { public static void compileOpenAutoSellFilter(Hopper hopper) {
for (GUIAutoSellFilter autoSellFilter : openInventories) { for (GUIAutoSellFilter autoSellFilter : OPEN_INVENTORIES) {
if (autoSellFilter.hopper == hopper) { if (autoSellFilter.hopper == hopper) {
autoSellFilter.compile(); autoSellFilter.compile();
} }

View File

@ -13,9 +13,8 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
public class GUICrafting extends CustomizableGui { public class GUICrafting extends CustomizableGui {
public GUICrafting(ModuleAutoCrafting module, EpicHoppers plugin, Hopper hopper, Player player) {
public GUICrafting(ModuleAutoCrafting module, Hopper hopper, Player player) { super(plugin, "crafting");
super(EpicHoppers.getInstance(), "crafting");
setRows(3); setRows(3);
setTitle(Methods.formatName(hopper.getLevel().getLevel()) + TextUtils.formatText(" &8-&f Crafting")); setTitle(Methods.formatName(hopper.getLevel().getLevel()) + TextUtils.formatText(" &8-&f Crafting"));
setOnClose((event) -> { setOnClose((event) -> {
@ -37,20 +36,20 @@ public class GUICrafting extends CustomizableGui {
mirrorFill("mirrorfill_5", 1, 1, false, true, glass3); mirrorFill("mirrorfill_5", 1, 1, false, true, glass3);
setButton("back", 8, GuiUtils.createButtonItem(CompatibleMaterial.ARROW.getItem(), setButton("back", 8, GuiUtils.createButtonItem(CompatibleMaterial.ARROW.getItem(),
EpicHoppers.getInstance().getLocale().getMessage("general.nametag.back").getMessage()), plugin.getLocale().getMessage("general.nametag.back").getMessage()),
(event) -> { (event) -> {
hopper.overview(guiManager, event.player); hopper.overview(this.guiManager, event.player);
setItem(module, hopper, player); setItem(module, hopper, player);
} }
); );
setButton(13, module.getAutoCrafting(hopper), setButton(13, module.getAutoCrafting(hopper),
(event) -> module.setAutoCrafting(hopper, player, inventory.getItem(13))); (event) -> module.setAutoCrafting(hopper, player, this.inventory.getItem(13)));
setUnlocked(13); setUnlocked(13);
} }
public void setItem(ModuleAutoCrafting module, Hopper hopper, Player player) { public void setItem(ModuleAutoCrafting module, Hopper hopper, Player player) {
module.setAutoCrafting(hopper, player, inventory.getItem(13)); module.setAutoCrafting(hopper, player, this.inventory.getItem(13));
} }
} }

View File

@ -22,10 +22,9 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class GUIFilter extends CustomizableGui { public class GUIFilter extends CustomizableGui {
private static final List<GUIFilter> openInventories = new ArrayList<>(); private static final List<GUIFilter> OPEN_INVENTORIES = new ArrayList<>();
private final EpicHoppers plugin; private final EpicHoppers plugin;
private final Hopper hopper; private final Hopper hopper;
public GUIFilter(EpicHoppers plugin, Hopper hopper, Player player) { public GUIFilter(EpicHoppers plugin, Hopper hopper, Player player) {
@ -38,10 +37,10 @@ public class GUIFilter extends CustomizableGui {
setDefaultItem(null); setDefaultItem(null);
setAcceptsItems(true); setAcceptsItems(true);
setOnOpen((event) -> GUIFilter.openInventories.add(this)); setOnOpen((event) -> GUIFilter.OPEN_INVENTORIES.add(this));
setOnClose((event) -> { setOnClose((event) -> {
GUIFilter.openInventories.remove(this); GUIFilter.OPEN_INVENTORIES.remove(this);
hopper.setActivePlayer(null); hopper.setActivePlayer(null);
compile(); compile();
}); });
@ -68,7 +67,7 @@ public class GUIFilter extends CustomizableGui {
setButton("back", 8, GuiUtils.createButtonItem(CompatibleMaterial.ARROW.getItem(), setButton("back", 8, GuiUtils.createButtonItem(CompatibleMaterial.ARROW.getItem(),
plugin.getLocale().getMessage("general.nametag.back").getMessage()), plugin.getLocale().getMessage("general.nametag.back").getMessage()),
(event) -> { (event) -> {
hopper.overview(guiManager, event.player); hopper.overview(this.guiManager, event.player);
compile(); compile();
}); });
@ -80,7 +79,9 @@ public class GUIFilter extends CustomizableGui {
int[] awhite = {9, 10, 18, 19, 27, 28, 36, 37}; int[] awhite = {9, 10, 18, 19, 27, 28, 36, 37};
int num = 0; int num = 0;
for (ItemStack m : filter.getWhiteList()) { for (ItemStack m : filter.getWhiteList()) {
if (num >= filter.getWhiteList().size()) break; if (num >= filter.getWhiteList().size()) {
break;
}
setItem(awhite[num], new ItemStack(m)); setItem(awhite[num], new ItemStack(m));
num++; num++;
} }
@ -98,7 +99,10 @@ public class GUIFilter extends CustomizableGui {
int[] ablack = {11, 12, 20, 21, 29, 30, 38, 39}; int[] ablack = {11, 12, 20, 21, 29, 30, 38, 39};
num = 0; num = 0;
for (ItemStack m : filter.getBlackList()) { for (ItemStack m : filter.getBlackList()) {
if (num >= filter.getBlackList().size()) break; if (num >= filter.getBlackList().size()) {
break;
}
setItem(ablack[num], new ItemStack(m)); setItem(ablack[num], new ItemStack(m));
num++; num++;
} }
@ -116,37 +120,39 @@ public class GUIFilter extends CustomizableGui {
int[] voidSlots = {13, 14, 22, 23, 31, 32, 40, 41}; int[] voidSlots = {13, 14, 22, 23, 31, 32, 40, 41};
num = 0; num = 0;
for (ItemStack m : filter.getVoidList()) { for (ItemStack m : filter.getVoidList()) {
if (num >= filter.getVoidList().size()) break; if (num >= filter.getVoidList().size()) {
break;
}
setItem(voidSlots[num], new ItemStack(m)); setItem(voidSlots[num], new ItemStack(m));
num++; num++;
} }
ItemStack itemInfo = new ItemStack(CompatibleMaterial.PAPER.getMaterial()); ItemStack itemInfo = new ItemStack(CompatibleMaterial.PAPER.getMaterial());
ItemMeta itemmetaInfo = itemInfo.getItemMeta(); ItemMeta itemMetaInfo = itemInfo.getItemMeta();
itemmetaInfo.setDisplayName(plugin.getLocale().getMessage("interface.filter.infotitle").getMessage()); itemMetaInfo.setDisplayName(plugin.getLocale().getMessage("interface.filter.infotitle").getMessage());
ArrayList<String> loreInfo = new ArrayList<>(); ArrayList<String> loreInfo = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.filter.infolore").getMessage().split("\\|"); String[] parts = plugin.getLocale().getMessage("interface.filter.infolore").getMessage().split("\\|");
for (String line : parts) { for (String line : parts) {
loreInfo.add(TextUtils.formatText(line)); loreInfo.add(TextUtils.formatText(line));
} }
itemmetaInfo.setLore(loreInfo); itemMetaInfo.setLore(loreInfo);
itemInfo.setItemMeta(itemmetaInfo); itemInfo.setItemMeta(itemMetaInfo);
setItem("info", 16, itemInfo); setItem("info", 16, itemInfo);
ItemStack hook = new ItemStack(CompatibleMaterial.TRIPWIRE_HOOK.getMaterial()); ItemStack hook = new ItemStack(CompatibleMaterial.TRIPWIRE_HOOK.getMaterial());
ItemMeta hookmeta = hook.getItemMeta(); ItemMeta hookMeta = hook.getItemMeta();
hookmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.rejectsync").getMessage()); hookMeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.rejectsync").getMessage());
ArrayList<String> lorehook = new ArrayList<>(); ArrayList<String> loreHook = new ArrayList<>();
parts = plugin.getLocale().getMessage("interface.hopper.synclore") parts = plugin.getLocale().getMessage("interface.hopper.synclore")
.processPlaceholder("amount", filter.getEndPoint() != null ? 1 : 0) .processPlaceholder("amount", filter.getEndPoint() != null ? 1 : 0)
.getMessage().split("\\|"); .getMessage().split("\\|");
for (String line : parts) { for (String line : parts) {
lorehook.add(TextUtils.formatText(line)); loreHook.add(TextUtils.formatText(line));
} }
hookmeta.setLore(lorehook); hookMeta.setLore(loreHook);
hook.setItemMeta(hookmeta); hook.setItemMeta(hookMeta);
setButton("reject", 43, hook, setButton("reject", 43, hook,
(event) -> { (event) -> {
if (event.clickType == ClickType.RIGHT) { if (event.clickType == ClickType.RIGHT) {
@ -167,9 +173,9 @@ public class GUIFilter extends CustomizableGui {
} }
private void compile() { private void compile() {
ItemStack[] items = inventory.getContents(); ItemStack[] items = this.inventory.getContents();
Filter filter = hopper.getFilter(); Filter filter = this.hopper.getFilter();
List<ItemStack> owhite = new ArrayList<>(); List<ItemStack> owhite = new ArrayList<>();
List<ItemStack> oblack = new ArrayList<>(); List<ItemStack> oblack = new ArrayList<>();
@ -181,36 +187,42 @@ public class GUIFilter extends CustomizableGui {
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
for (int aa : awhite) { for (int aa : awhite) {
if (aa != i) continue; if (aa != i) {
continue;
}
if (items[i] != null && items[i].getType() != Material.AIR) { if (items[i] != null && items[i].getType() != Material.AIR) {
ItemStack item = items[i]; ItemStack item = items[i];
if (item.getAmount() != 1) { if (item.getAmount() != 1) {
item.setAmount(item.getAmount() - 1); item.setAmount(item.getAmount() - 1);
Bukkit.getPlayer(hopper.getLastPlayerOpened()).getInventory().addItem(item); Bukkit.getPlayer(this.hopper.getLastPlayerOpened()).getInventory().addItem(item);
item.setAmount(1); item.setAmount(1);
} }
owhite.add(item); owhite.add(item);
} }
} }
for (int aa : ablack) { for (int aa : ablack) {
if (aa != i) continue; if (aa != i) {
continue;
}
if (items[i] != null && items[i].getType() != Material.AIR) { if (items[i] != null && items[i].getType() != Material.AIR) {
ItemStack item = items[i]; ItemStack item = items[i];
if (item.getAmount() != 1) { if (item.getAmount() != 1) {
item.setAmount(item.getAmount() - 1); item.setAmount(item.getAmount() - 1);
Bukkit.getPlayer(hopper.getLastPlayerOpened()).getInventory().addItem(item); Bukkit.getPlayer(this.hopper.getLastPlayerOpened()).getInventory().addItem(item);
item.setAmount(1); item.setAmount(1);
} }
oblack.add(item); oblack.add(item);
} }
} }
for (int aa : avoid) { for (int aa : avoid) {
if (aa != i) continue; if (aa != i) {
continue;
}
if (items[i] != null && items[i].getType() != Material.AIR) { if (items[i] != null && items[i].getType() != Material.AIR) {
ItemStack item = items[i]; ItemStack item = items[i];
if (item.getAmount() != 1) { if (item.getAmount() != 1) {
item.setAmount(item.getAmount() - 1); item.setAmount(item.getAmount() - 1);
Bukkit.getPlayer(hopper.getLastPlayerOpened()).getInventory().addItem(item); Bukkit.getPlayer(this.hopper.getLastPlayerOpened()).getInventory().addItem(item);
item.setAmount(1); item.setAmount(1);
} }
ovoid.add(item); ovoid.add(item);
@ -220,13 +232,13 @@ public class GUIFilter extends CustomizableGui {
filter.setWhiteList(owhite); filter.setWhiteList(owhite);
filter.setBlackList(oblack); filter.setBlackList(oblack);
filter.setVoidList(ovoid); filter.setVoidList(ovoid);
plugin.getDataManager().updateItems(hopper, ItemType.WHITELIST, owhite); this.plugin.getDataManager().updateItems(this.hopper, ItemType.WHITELIST, owhite);
plugin.getDataManager().updateItems(hopper, ItemType.BLACKLIST, oblack); this.plugin.getDataManager().updateItems(this.hopper, ItemType.BLACKLIST, oblack);
plugin.getDataManager().updateItems(hopper, ItemType.VOID, ovoid); this.plugin.getDataManager().updateItems(this.hopper, ItemType.VOID, ovoid);
} }
public static void compileOpenGuiFilter(Hopper hopper) { public static void compileOpenGuiFilter(Hopper hopper) {
for (GUIFilter guiFilter : openInventories) { for (GUIFilter guiFilter : OPEN_INVENTORIES) {
if (guiFilter.hopper == hopper) { if (guiFilter.hopper == hopper) {
guiFilter.compile(); guiFilter.compile();
} }

View File

@ -4,17 +4,19 @@ import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.ServerVersion; import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.gui.CustomizableGui; import com.songoda.core.gui.CustomizableGui;
import com.songoda.core.gui.GuiUtils; import com.songoda.core.gui.GuiUtils;
import com.songoda.core.utils.NumberUtils;
import com.songoda.core.utils.TextUtils; import com.songoda.core.utils.TextUtils;
import com.songoda.core.utils.TimeUtils;
import com.songoda.epichoppers.EpicHoppers; import com.songoda.epichoppers.EpicHoppers;
import com.songoda.epichoppers.boost.BoostData; import com.songoda.epichoppers.boost.BoostData;
import com.songoda.epichoppers.hopper.Hopper; import com.songoda.epichoppers.hopper.Hopper;
import com.songoda.epichoppers.hopper.levels.Level; import com.songoda.epichoppers.hopper.levels.Level;
import com.songoda.epichoppers.hopper.levels.modules.Module; import com.songoda.epichoppers.hopper.levels.modules.Module;
import com.songoda.epichoppers.hopper.teleport.TeleportTrigger;
import com.songoda.epichoppers.player.SyncType; import com.songoda.epichoppers.player.SyncType;
import com.songoda.epichoppers.settings.Settings; import com.songoda.epichoppers.settings.Settings;
import com.songoda.epichoppers.utils.CostType; import com.songoda.epichoppers.utils.CostType;
import com.songoda.epichoppers.utils.Methods; import com.songoda.epichoppers.utils.Methods;
import com.songoda.epichoppers.hopper.teleport.TeleportTrigger;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
@ -29,7 +31,6 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class GUIOverview extends CustomizableGui { public class GUIOverview extends CustomizableGui {
private final EpicHoppers plugin; private final EpicHoppers plugin;
private final Hopper hopper; private final Hopper hopper;
private final Player player; private final Player player;
@ -48,7 +49,7 @@ public class GUIOverview extends CustomizableGui {
constructGUI(); constructGUI();
this.setOnClose(action -> { this.setOnClose(action -> {
hopper.setActivePlayer(null); hopper.setActivePlayer(null);
Bukkit.getScheduler().cancelTask(task); Bukkit.getScheduler().cancelTask(this.task);
}); });
} }
@ -65,78 +66,84 @@ public class GUIOverview extends CustomizableGui {
mirrorFill("mirrorfill_4", 1, 0, false, true, glass2); mirrorFill("mirrorfill_4", 1, 0, false, true, glass2);
mirrorFill("mirrorfill_5", 1, 1, false, true, glass3); mirrorFill("mirrorfill_5", 1, 1, false, true, glass3);
plugin.getPlayerDataManager().getPlayerData(player).setLastHopper(hopper); this.plugin.getPlayerDataManager().getPlayerData(this.player).setLastHopper(this.hopper);
Level level = hopper.getLevel(); Level level = this.hopper.getLevel();
Level nextLevel = plugin.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? plugin.getLevelManager().getLevel(level.getLevel() + 1) : null; Level nextLevel = this.plugin.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? this.plugin.getLevelManager().getLevel(level.getLevel() + 1) : null;
ItemStack perl = new ItemStack(Material.ENDER_PEARL, 1); ItemStack pearl = new ItemStack(Material.ENDER_PEARL, 1);
ItemMeta perlmeta = perl.getItemMeta(); ItemMeta pearlMeta = pearl.getItemMeta();
perlmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.perltitle").getMessage()); pearlMeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.perltitle").getMessage());
ArrayList<String> loreperl = new ArrayList<>(); ArrayList<String> lorePearl = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.hopper.perllore2") String[] parts = this.plugin.getLocale().getMessage("interface.hopper.perllore2")
.processPlaceholder("type", hopper.getTeleportTrigger() == TeleportTrigger.DISABLED .processPlaceholder(
? plugin.getLocale().getMessage("general.word.disabled").getMessage() "type",
: hopper.getTeleportTrigger().name()).getMessage().split("\\|"); this.hopper.getTeleportTrigger() == TeleportTrigger.DISABLED
? this.plugin.getLocale().getMessage("general.word.disabled").getMessage()
: this.hopper.getTeleportTrigger().name()
)
.getMessage()
.split("\\|");
for (String line : parts) { for (String line : parts) {
loreperl.add(TextUtils.formatText(line)); lorePearl.add(TextUtils.formatText(line));
} }
perlmeta.setLore(loreperl); pearlMeta.setLore(lorePearl);
perl.setItemMeta(perlmeta); pearl.setItemMeta(pearlMeta);
ItemStack filter = new ItemStack(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.COMPARATOR : Material.valueOf("REDSTONE_COMPARATOR"), 1); ItemStack filter = new ItemStack(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) ? Material.COMPARATOR : Material.valueOf("REDSTONE_COMPARATOR"), 1);
ItemMeta filtermeta = filter.getItemMeta(); ItemMeta filterMeta = filter.getItemMeta();
filtermeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.filtertitle").getMessage()); filterMeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.filtertitle").getMessage());
ArrayList<String> lorefilter = new ArrayList<>(); ArrayList<String> loreFilter = new ArrayList<>();
parts = plugin.getLocale().getMessage("interface.hopper.filterlore").getMessage().split("\\|"); parts = this.plugin.getLocale().getMessage("interface.hopper.filterlore").getMessage().split("\\|");
for (String line : parts) { for (String line : parts) {
lorefilter.add(TextUtils.formatText(line)); loreFilter.add(TextUtils.formatText(line));
} }
filtermeta.setLore(lorefilter); filterMeta.setLore(loreFilter);
filter.setItemMeta(filtermeta); filter.setItemMeta(filterMeta);
ItemStack item = new ItemStack(Material.HOPPER, 1); ItemStack item = new ItemStack(Material.HOPPER, 1);
ItemMeta itemmeta = item.getItemMeta(); ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.currentlevel").processPlaceholder("level", level.getLevel()).getMessage()); itemmeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.currentlevel").processPlaceholder("level", level.getLevel()).getMessage());
List<String> lore = level.getDescription(); List<String> lore = level.getDescription();
if (plugin.getConfig().getBoolean("Main.Allow hopper Upgrading")) { if (this.plugin.getConfig().getBoolean("Main.Allow hopper Upgrading")) {
lore.add(""); lore.add("");
if (nextLevel == null) if (nextLevel == null) {
lore.add(plugin.getLocale().getMessage("interface.hopper.alreadymaxed").getMessage()); lore.add(this.plugin.getLocale().getMessage("interface.hopper.alreadymaxed").getMessage());
else { } else {
lore.add(plugin.getLocale().getMessage("interface.hopper.nextlevel").processPlaceholder("level", nextLevel.getLevel()).getMessage()); lore.add(this.plugin.getLocale().getMessage("interface.hopper.nextlevel").processPlaceholder("level", nextLevel.getLevel()).getMessage());
lore.addAll(nextLevel.getDescription()); lore.addAll(nextLevel.getDescription());
} }
} }
BoostData boostData = plugin.getBoostManager().getBoost(hopper.getPlacedBy()); BoostData boostData = this.plugin.getBoostManager().getBoost(this.hopper.getPlacedBy());
if (boostData != null) { if (boostData != null) {
parts = plugin.getLocale().getMessage("interface.hopper.boostedstats") parts = this.plugin.getLocale().getMessage("interface.hopper.boostedstats")
.processPlaceholder("amount", Integer.toString(boostData.getMultiplier())) .processPlaceholder("amount", Integer.toString(boostData.getMultiplier()))
.processPlaceholder("time", Methods.makeReadable(boostData.getEndTime() - System.currentTimeMillis())) .processPlaceholder("time", TimeUtils.makeReadable(boostData.getEndTime() - System.currentTimeMillis()))
.getMessage().split("\\|"); .getMessage().split("\\|");
lore.add(""); lore.add("");
for (String line : parts) for (String line : parts) {
lore.add(TextUtils.formatText(line)); lore.add(TextUtils.formatText(line));
} }
}
itemmeta.setLore(lore); itemmeta.setLore(lore);
item.setItemMeta(itemmeta); item.setItemMeta(itemmeta);
ItemStack hook = new ItemStack(Material.TRIPWIRE_HOOK, 1); ItemStack hook = new ItemStack(Material.TRIPWIRE_HOOK, 1);
ItemMeta hookmeta = hook.getItemMeta(); ItemMeta hookMeta = hook.getItemMeta();
hookmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.synchopper").getMessage()); hookMeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.synchopper").getMessage());
ArrayList<String> lorehook = new ArrayList<>(); ArrayList<String> loreHook = new ArrayList<>();
parts = plugin.getLocale().getMessage("interface.hopper.synclore") parts = this.plugin.getLocale().getMessage("interface.hopper.synclore")
.processPlaceholder("amount", hopper.getLinkedBlocks().stream().distinct().count()) .processPlaceholder("amount", this.hopper.getLinkedBlocks().stream().distinct().count())
.getMessage().split("\\|"); .getMessage().split("\\|");
for (String line : parts) { for (String line : parts) {
lorehook.add(TextUtils.formatText(line)); loreHook.add(TextUtils.formatText(line));
} }
hookmeta.setLore(lorehook); hookMeta.setLore(loreHook);
hook.setItemMeta(hookmeta); hook.setItemMeta(hookMeta);
Map<Integer, Integer[]> layouts = new HashMap<>(); Map<Integer, Integer[]> layouts = new HashMap<>();
layouts.put(1, new Integer[]{22}); layouts.put(1, new Integer[]{22});
@ -152,13 +159,19 @@ public class GUIOverview extends CustomizableGui {
int amount = 1; int amount = 1;
boolean canFilter = level.isFilter() || player.hasPermission("EpicHoppers.Filter"); boolean canFilter = level.isFilter() || this.player.hasPermission("EpicHoppers.Filter");
boolean canTeleport = level.isTeleport() || player.hasPermission("EpicHoppers.Teleport"); boolean canTeleport = level.isTeleport() || this.player.hasPermission("EpicHoppers.Teleport");
if (canFilter) amount++; if (canFilter) {
if (canTeleport) amount++; amount++;
}
if (canTeleport) {
amount++;
}
List<Module> modules = level.getRegisteredModules().stream().filter(module -> List<Module> modules = level.getRegisteredModules()
module.getGUIButton(hopper) != null).collect(Collectors.toList()); .stream()
.filter(module -> module.getGUIButton(this.hopper) != null)
.collect(Collectors.toList());
amount += modules.size(); amount += modules.size();
@ -170,107 +183,111 @@ public class GUIOverview extends CustomizableGui {
if (ii == 0) { if (ii == 0) {
setButton("sync", slot, hook, setButton("sync", slot, hook,
(event) -> { (event) -> {
if (hopper.getLastPlayerOpened() != null && !hopper.getLastPlayerOpened().equals(player.getUniqueId())) { if (this.hopper.getLastPlayerOpened() != null && !this.hopper.getLastPlayerOpened().equals(this.player.getUniqueId())) {
plugin.getLocale().getMessage("event.hopper.syncdidnotplace").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.hopper.syncdidnotplace").sendPrefixedMessage(this.player);
return; return;
} }
hopper.clearLinkedBlocks(); this.hopper.clearLinkedBlocks();
plugin.getDataManager().deleteLinks(hopper); this.plugin.getDataManager().deleteLinks(this.hopper);
if (event.clickType == ClickType.RIGHT) { if (event.clickType == ClickType.RIGHT) {
plugin.getLocale().getMessage("event.hopper.desync").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.hopper.desync").sendPrefixedMessage(this.player);
constructGUI(); constructGUI();
return; return;
} else { } else {
plugin.getPlayerDataManager().getPlayerData(player).setSyncType(SyncType.REGULAR); this.plugin.getPlayerDataManager().getPlayerData(this.player).setSyncType(SyncType.REGULAR);
plugin.getLocale().getMessage("event.hopper.syncnext").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.hopper.syncnext").sendPrefixedMessage(this.player);
if (level.getLinkAmount() > 1) if (level.getLinkAmount() > 1) {
plugin.getLocale().getMessage("event.hopper.syncstart") this.plugin.getLocale().getMessage("event.hopper.syncstart")
.processPlaceholder("amount", level.getLinkAmount()) .processPlaceholder("amount", level.getLinkAmount())
.sendPrefixedMessage(player); .sendPrefixedMessage(this.player);
hopper.timeout(player);
} }
player.closeInventory();
this.hopper.timeout(this.player);
}
this.player.closeInventory();
}); });
} else if (canTeleport) { } else if (canTeleport) {
setButton("teleport", slot, perl, setButton("teleport", slot, pearl,
(event) -> { (event) -> {
if (event.clickType == ClickType.LEFT) { if (event.clickType == ClickType.LEFT) {
if (hopper.getLinkedBlocks() != null) { if (this.hopper.getLinkedBlocks() != null) {
plugin.getTeleportHandler().tpEntity(player, hopper); this.plugin.getTeleportHandler().tpEntity(this.player, this.hopper);
player.closeInventory(); this.player.closeInventory();
} }
} else { } else {
if (hopper.getTeleportTrigger() == TeleportTrigger.DISABLED) { if (this.hopper.getTeleportTrigger() == TeleportTrigger.DISABLED) {
hopper.setTeleportTrigger(TeleportTrigger.SNEAK); this.hopper.setTeleportTrigger(TeleportTrigger.SNEAK);
} else if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) { } else if (this.hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) {
hopper.setTeleportTrigger(TeleportTrigger.WALK_ON); this.hopper.setTeleportTrigger(TeleportTrigger.WALK_ON);
} else if (hopper.getTeleportTrigger() == TeleportTrigger.WALK_ON) { } else if (this.hopper.getTeleportTrigger() == TeleportTrigger.WALK_ON) {
hopper.setTeleportTrigger(TeleportTrigger.DISABLED); this.hopper.setTeleportTrigger(TeleportTrigger.DISABLED);
} }
plugin.getDataManager().updateHopper(hopper); this.plugin.getDataManager().updateHopper(this.hopper);
constructGUI(); constructGUI();
} }
}); });
canTeleport = false; canTeleport = false;
} else if (canFilter) { } else if (canFilter) {
setButton("filter", slot, filter, (event) -> { setButton("filter", slot, filter, (event) -> {
hopper.setActivePlayer(player); this.hopper.setActivePlayer(this.player);
guiManager.showGUI(player, new GUIFilter(plugin, hopper, player)); this.guiManager.showGUI(this.player, new GUIFilter(this.plugin, this.hopper, this.player));
}); });
canFilter = false; canFilter = false;
} else { } else {
if (modules.isEmpty()) break; if (modules.isEmpty()) {
break;
}
Module module = modules.get(0); Module module = modules.get(0);
modules.remove(module); modules.remove(module);
setButton(module.getName().toLowerCase().replace(" ", "_"), slot, module.getGUIButton(hopper), setButton(module.getName().toLowerCase().replace(" ", "_"), slot, module.getGUIButton(this.hopper),
(event) -> module.runButtonPress(player, hopper, event.clickType)); (event) -> module.runButtonPress(this.player, this.hopper, event.clickType));
} }
} }
if (Settings.HOPPER_UPGRADING.getBoolean()) { if (Settings.HOPPER_UPGRADING.getBoolean()) {
if (Settings.UPGRADE_WITH_XP.getBoolean() if (Settings.UPGRADE_WITH_XP.getBoolean()
&& level.getCostExperience() != -1 && level.getCostExperience() != -1
&& player.hasPermission("EpicHoppers.Upgrade.XP")) { && this.player.hasPermission("EpicHoppers.Upgrade.XP")) {
setButton("upgrade_xp", 1, 2, GuiUtils.createButtonItem( setButton("upgrade_xp", 1, 2, GuiUtils.createButtonItem(
Settings.XP_ICON.getMaterial(CompatibleMaterial.EXPERIENCE_BOTTLE), Settings.XP_ICON.getMaterial(CompatibleMaterial.EXPERIENCE_BOTTLE),
plugin.getLocale().getMessage("interface.hopper.upgradewithxp").getMessage(), this.plugin.getLocale().getMessage("interface.hopper.upgradewithxp").getMessage(),
nextLevel != null nextLevel != null
? plugin.getLocale().getMessage("interface.hopper.upgradewithxplore") ? this.plugin.getLocale().getMessage("interface.hopper.upgradewithxplore")
.processPlaceholder("cost", nextLevel.getCostExperience()).getMessage() .processPlaceholder("cost", nextLevel.getCostExperience()).getMessage()
: plugin.getLocale().getMessage("interface.hopper.alreadymaxed").getMessage()), : this.plugin.getLocale().getMessage("interface.hopper.alreadymaxed").getMessage()),
(event) -> { (event) -> {
hopper.upgrade(player, CostType.EXPERIENCE); this.hopper.upgrade(this.player, CostType.EXPERIENCE);
hopper.overview(guiManager, player); this.hopper.overview(this.guiManager, this.player);
}); });
} }
if (Settings.UPGRADE_WITH_ECONOMY.getBoolean() if (Settings.UPGRADE_WITH_ECONOMY.getBoolean()
&& level.getCostEconomy() != -1 && level.getCostEconomy() != -1
&& player.hasPermission("EpicHoppers.Upgrade.ECO")) { && this.player.hasPermission("EpicHoppers.Upgrade.ECO")) {
setButton("upgrade_economy", 1, 6, GuiUtils.createButtonItem( setButton("upgrade_economy", 1, 6, GuiUtils.createButtonItem(
Settings.ECO_ICON.getMaterial(CompatibleMaterial.SUNFLOWER), Settings.ECO_ICON.getMaterial(CompatibleMaterial.SUNFLOWER),
plugin.getLocale().getMessage("interface.hopper.upgradewitheconomy").getMessage(), this.plugin.getLocale().getMessage("interface.hopper.upgradewitheconomy").getMessage(),
nextLevel != null nextLevel != null
? plugin.getLocale().getMessage("interface.hopper.upgradewitheconomylore") ? this.plugin.getLocale().getMessage("interface.hopper.upgradewitheconomylore")
.processPlaceholder("cost", Methods.formatEconomy(nextLevel.getCostEconomy())).getMessage() .processPlaceholder("cost", NumberUtils.formatNumber(nextLevel.getCostEconomy())).getMessage()
: plugin.getLocale().getMessage("interface.hopper.alreadymaxed").getMessage()), : this.plugin.getLocale().getMessage("interface.hopper.alreadymaxed").getMessage()),
(event) -> { (event) -> {
hopper.upgrade(player, CostType.ECONOMY); this.hopper.upgrade(this.player, CostType.ECONOMY);
hopper.overview(guiManager, player); this.hopper.overview(this.guiManager, this.player);
}); });
} }
} }
setItem("hopper", 13, item); setItem("hopper", 13, item);
hopper.setLastPlayerOpened(player.getUniqueId()); this.hopper.setLastPlayerOpened(this.player.getUniqueId());
} }
private void runTask() { private void runTask() {
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> { this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(this.plugin, () -> {
if (!inventory.getViewers().isEmpty()) if (!this.inventory.getViewers().isEmpty()) {
this.constructGUI(); this.constructGUI();
}
}, 5L, 5L); }, 5L, 5L);
} }
} }

View File

@ -17,14 +17,15 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class GUISmeltable extends CustomizableGui { public class GUISmeltable extends CustomizableGui {
private final EpicHoppers plugin; private final EpicHoppers plugin;
private final Hopper hopper; private final Hopper hopper;
private int maxPages; private final int maxPages;
private ModuleAutoSmelter moduleAutoSmelter; private final ModuleAutoSmelter moduleAutoSmelter;
private static List<CompatibleMaterial> burnables = Arrays.stream(CompatibleMaterial.values()) private static final List<CompatibleMaterial> BURNABLES = Arrays
.filter(m -> m.getBurnResult() != null).collect(Collectors.toList()); .stream(CompatibleMaterial.values())
.filter(material -> material.getBurnResult() != null)
.collect(Collectors.toList());
public GUISmeltable(ModuleAutoSmelter moduleAutoSmelter, EpicHoppers plugin, Hopper hopper) { public GUISmeltable(ModuleAutoSmelter moduleAutoSmelter, EpicHoppers plugin, Hopper hopper) {
super(plugin, "smeltable"); super(plugin, "smeltable");
@ -32,9 +33,9 @@ public class GUISmeltable extends CustomizableGui {
this.hopper = hopper; this.hopper = hopper;
this.moduleAutoSmelter = moduleAutoSmelter; this.moduleAutoSmelter = moduleAutoSmelter;
int smeltables = burnables.size(); int smeltables = BURNABLES.size();
maxPages = (int) Math.ceil(smeltables / 32.); this.maxPages = (int) Math.ceil(smeltables / 32.);
setTitle(Methods.formatName(hopper.getLevel().getLevel()) + TextUtils.formatText(" &7-&f Smelting")); setTitle(Methods.formatName(hopper.getLevel().getLevel()) + TextUtils.formatText(" &7-&f Smelting"));
setRows(6); setRows(6);
@ -57,44 +58,44 @@ public class GUISmeltable extends CustomizableGui {
mirrorFill("mirrorfill_3", 0, 2, true, true, glass3); mirrorFill("mirrorfill_3", 0, 2, true, true, glass3);
mirrorFill("mirrorfill_4", 1, 0, true, true, glass2); mirrorFill("mirrorfill_4", 1, 0, true, true, glass2);
int smeltableIndex = page == 1 ? 0 : 32 * (page - 1); int smeltableIndex = this.page == 1 ? 0 : 32 * (this.page - 1);
for (int i = 9; i < 45; i++) { for (int i = 9; i < 45; i++) {
if (i == 9 || i == 17 || i == 44 || i == 36) continue; if (i == 9 || i == 17 || i == 44 || i == 36) continue;
setItem(i, null); setItem(i, null);
clearActions(i); clearActions(i);
if (smeltableIndex >= (burnables.size() - 1)) continue; if (smeltableIndex >= (BURNABLES.size() - 1)) continue;
CompatibleMaterial burnable = burnables.get(smeltableIndex); CompatibleMaterial burnable = BURNABLES.get(smeltableIndex);
setButton(i, getItemStack(burnable, moduleAutoSmelter.isSmeltable(hopper, burnable)), (event) -> { setButton(i, getItemStack(burnable, this.moduleAutoSmelter.isSmeltable(this.hopper, burnable)), (event) -> {
moduleAutoSmelter.toggleSmeltable(hopper, burnable); this.moduleAutoSmelter.toggleSmeltable(this.hopper, burnable);
setItem(event.slot, getItemStack(burnable, moduleAutoSmelter.isSmeltable(hopper, burnable))); setItem(event.slot, getItemStack(burnable, this.moduleAutoSmelter.isSmeltable(this.hopper, burnable)));
}); });
smeltableIndex++; smeltableIndex++;
} }
clearActions(51); clearActions(51);
if (page < maxPages) { if (this.page < this.maxPages) {
setButton("next", 51, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, setButton("next", 51, GuiUtils.createButtonItem(CompatibleMaterial.ARROW,
plugin.getLocale().getMessage("general.nametag.next").getMessage()), this.plugin.getLocale().getMessage("general.nametag.next").getMessage()),
(event) -> { (event) -> {
page++; this.page++;
showPage(); showPage();
}); });
} }
clearActions(47); clearActions(47);
if (page > 1) { if (this.page > 1) {
setButton("back", 47, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, setButton("back", 47, GuiUtils.createButtonItem(CompatibleMaterial.ARROW,
plugin.getLocale().getMessage("general.nametag.back").getMessage()), this.plugin.getLocale().getMessage("general.nametag.back").getMessage()),
(event) -> { (event) -> {
page--; this.page--;
showPage(); showPage();
}); });
} }
setButton("exit", 49, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR, setButton("exit", 49, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR,
plugin.getLocale().getMessage("general.nametag.exit").getMessage()), this.plugin.getLocale().getMessage("general.nametag.exit").getMessage()),
(event) -> hopper.overview(plugin.getGuiManager(), event.player)); (event) -> this.hopper.overview(this.plugin.getGuiManager(), event.player));
} }
public ItemStack getItemStack(CompatibleMaterial material, boolean enabled) { public ItemStack getItemStack(CompatibleMaterial material, boolean enabled) {
@ -104,7 +105,7 @@ public class GUISmeltable extends CustomizableGui {
meta.setLore(Arrays.asList(TextUtils.formatText(" &7-> &e" + material.getBurnResult().name()), meta.setLore(Arrays.asList(TextUtils.formatText(" &7-> &e" + material.getBurnResult().name()),
TextUtils.formatText("&7Enabled: &6" + String.valueOf(enabled).toLowerCase() + "&7."), TextUtils.formatText("&7Enabled: &6" + String.valueOf(enabled).toLowerCase() + "&7."),
"", "",
plugin.getLocale().getMessage("interface.hopper.toggle").getMessage())); this.plugin.getLocale().getMessage("interface.hopper.toggle").getMessage()));
item.setItemMeta(meta); item.setItemMeta(meta);
return item; return item;

View File

@ -8,7 +8,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
public class Filter { public class Filter {
private List<ItemStack> whiteList = new ArrayList<>(); private List<ItemStack> whiteList = new ArrayList<>();
private List<ItemStack> blackList = new ArrayList<>(); private List<ItemStack> blackList = new ArrayList<>();
private List<ItemStack> voidList = new ArrayList<>(); private List<ItemStack> voidList = new ArrayList<>();
@ -21,7 +20,7 @@ public class Filter {
public List<ItemStack> getWhiteList() { public List<ItemStack> getWhiteList() {
return whiteList != null ? whiteList : Collections.emptyList(); return this.whiteList != null ? this.whiteList : Collections.emptyList();
} }
@ -31,7 +30,7 @@ public class Filter {
public List<ItemStack> getBlackList() { public List<ItemStack> getBlackList() {
return blackList != null ? blackList : Collections.emptyList(); return this.blackList != null ? this.blackList : Collections.emptyList();
} }
@ -41,7 +40,7 @@ public class Filter {
public List<ItemStack> getVoidList() { public List<ItemStack> getVoidList() {
return voidList != null ? voidList : Collections.emptyList(); return this.voidList != null ? this.voidList : Collections.emptyList();
} }
@ -51,7 +50,7 @@ public class Filter {
public List<ItemStack> getAutoSellWhiteList() { public List<ItemStack> getAutoSellWhiteList() {
return autoSellWhiteList != null ? autoSellWhiteList : Collections.emptyList(); return this.autoSellWhiteList != null ? this.autoSellWhiteList : Collections.emptyList();
} }
@ -61,7 +60,7 @@ public class Filter {
public List<ItemStack> getAutoSellBlackList() { public List<ItemStack> getAutoSellBlackList() {
return autoSellBlackList != null ? autoSellBlackList : Collections.emptyList(); return this.autoSellBlackList != null ? this.autoSellBlackList : Collections.emptyList();
} }
@ -71,7 +70,7 @@ public class Filter {
public Location getEndPoint() { public Location getEndPoint() {
return endPoint; return this.endPoint;
} }
@ -82,19 +81,23 @@ public class Filter {
public void addItem(ItemStack item, ItemType type) { public void addItem(ItemStack item, ItemType type) {
switch (type) { switch (type) {
case WHITELIST: case WHITELIST:
whiteList.add(item); this.whiteList.add(item);
break; break;
case BLACKLIST: case BLACKLIST:
blackList.add(item); this.blackList.add(item);
break; break;
case VOID: case VOID:
voidList.add(item); this.voidList.add(item);
break; break;
case AUTO_SELL_WHITELIST: case AUTO_SELL_WHITELIST:
autoSellWhiteList.add(item); this.autoSellWhiteList.add(item);
break; break;
case AUTO_SELL_BLACKLIST: case AUTO_SELL_BLACKLIST:
autoSellBlackList.add(item); this.autoSellBlackList.add(item);
break; break;
} }
} }

View File

@ -14,7 +14,11 @@ import com.songoda.epichoppers.player.PlayerData;
import com.songoda.epichoppers.settings.Settings; import com.songoda.epichoppers.settings.Settings;
import com.songoda.epichoppers.utils.CostType; import com.songoda.epichoppers.utils.CostType;
import com.songoda.epichoppers.utils.Methods; import com.songoda.epichoppers.utils.Methods;
import org.bukkit.*; 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.block.Block;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
@ -27,16 +31,12 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
/**
* Created by songoda on 3/14/2017.
*/
public class Hopper { public class Hopper {
// Id for database use. // Id for database use.
private int id; private int id;
private final Location location; private final Location location;
private Level level = EpicHoppers.getInstance().getLevelManager().getLowestLevel(); private Level level = EpicHoppers.getPlugin(EpicHoppers.class).getLevelManager().getLowestLevel();
private UUID lastPlayerOpened = null; private UUID lastPlayerOpened = null;
private UUID placedBy = null; private UUID placedBy = null;
private final List<Location> linkedBlocks = new ArrayList<>(); private final List<Location> linkedBlocks = new ArrayList<>();
@ -55,10 +55,10 @@ public class Hopper {
} }
public void overview(GuiManager guiManager, Player player) { public void overview(GuiManager guiManager, Player player) {
if (lastPlayerOpened != null if (this.lastPlayerOpened != null &&
&& lastPlayerOpened != player.getUniqueId() this.lastPlayerOpened != player.getUniqueId() &&
&& Bukkit.getPlayer(lastPlayerOpened) != null) { Bukkit.getPlayer(this.lastPlayerOpened) != null) {
Bukkit.getPlayer(lastPlayerOpened).closeInventory(); Bukkit.getPlayer(this.lastPlayerOpened).closeInventory();
} }
HopperAccessEvent accessEvent = new HopperAccessEvent(player, this); HopperAccessEvent accessEvent = new HopperAccessEvent(player, this);
@ -67,36 +67,43 @@ public class Hopper {
return; return;
} }
if (placedBy == null) placedBy = player.getUniqueId(); if (this.placedBy == null) {
this.placedBy = player.getUniqueId();
}
EpicHoppers instance = EpicHoppers.getInstance(); EpicHoppers instance = EpicHoppers.getPlugin(EpicHoppers.class);
if (!player.hasPermission("epichoppers.overview")) return; if (!player.hasPermission("epichoppers.overview")) {
return;
}
setActivePlayer(player); setActivePlayer(player);
guiManager.showGUI(player, new GUIOverview(instance, this, player)); guiManager.showGUI(player, new GUIOverview(instance, this, player));
} }
public void forceClose() { public void forceClose() {
if (activePlayer != null) if (this.activePlayer != null) {
activePlayer.closeInventory(); this.activePlayer.closeInventory();
}
} }
public void dropItems() { public void dropItems() {
Inventory inventory = ((InventoryHolder) location.getBlock().getState()).getInventory(); Inventory inventory = ((InventoryHolder) this.location.getBlock().getState()).getInventory();
World world = location.getWorld(); World world = this.location.getWorld();
for (ItemStack itemStack : inventory.getContents()) { for (ItemStack itemStack : inventory.getContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) { if (itemStack == null || itemStack.getType() == Material.AIR) {
continue; continue;
} }
world.dropItemNaturally(location, itemStack); world.dropItemNaturally(this.location, itemStack);
} }
} }
public void upgrade(Player player, CostType type) { public void upgrade(Player player, CostType type) {
EpicHoppers plugin = EpicHoppers.getInstance(); EpicHoppers plugin = EpicHoppers.getPlugin(EpicHoppers.class);
if (!plugin.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) return; if (!plugin.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) {
return;
}
Level level = plugin.getLevelManager().getLevel(this.level.getLevel() + 1); Level level = plugin.getLevelManager().getLevel(this.level.getLevel() + 1);
int cost = type == CostType.ECONOMY ? level.getCostEconomy() : level.getCostExperience(); int cost = type == CostType.ECONOMY ? level.getCostEconomy() : level.getCostExperience();
@ -125,7 +132,7 @@ public class Hopper {
} }
private void upgradeFinal(Level level, Player player) { private void upgradeFinal(Level level, Player player) {
EpicHoppers plugin = EpicHoppers.getInstance(); EpicHoppers plugin = EpicHoppers.getPlugin(EpicHoppers.class);
this.level = level; this.level = level;
plugin.getDataManager().updateHopper(this); plugin.getDataManager().updateHopper(this);
syncName(); syncName();
@ -136,7 +143,7 @@ public class Hopper {
plugin.getLocale().getMessage("event.upgrade.maxed") plugin.getLocale().getMessage("event.upgrade.maxed")
.processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player);
} }
Location loc = location.clone().add(.5, .5, .5); Location loc = this.location.clone().add(.5, .5, .5);
if (!Settings.UPGRADE_PARTICLE_TYPE.getString().trim().isEmpty()) { if (!Settings.UPGRADE_PARTICLE_TYPE.getString().trim().isEmpty()) {
CompatibleParticleHandler.spawnParticles( CompatibleParticleHandler.spawnParticles(
@ -155,35 +162,36 @@ public class Hopper {
} }
private void syncName() { private void syncName() {
org.bukkit.block.Hopper hopper = (org.bukkit.block.Hopper) location.getBlock().getState(); org.bukkit.block.Hopper hopper = (org.bukkit.block.Hopper) this.location.getBlock().getState();
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_10)) if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_10)) {
hopper.setCustomName(Methods.formatName(level.getLevel())); hopper.setCustomName(Methods.formatName(this.level.getLevel()));
}
hopper.update(true); hopper.update(true);
} }
public void timeout(Player player) { public void timeout(Player player) {
EpicHoppers instance = EpicHoppers.getInstance(); EpicHoppers instance = EpicHoppers.getPlugin(EpicHoppers.class);
syncId = Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> { this.syncId = Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> {
PlayerData playerData = instance.getPlayerDataManager().getPlayerData(player); PlayerData playerData = instance.getPlayerDataManager().getPlayerData(player);
if (playerData.getSyncType() != null && playerData.getLastHopper() == this) { if (playerData.getSyncType() != null && playerData.getLastHopper() == this) {
instance.getLocale().getMessage("event.hopper.synctimeout").sendPrefixedMessage(player); instance.getLocale().getMessage("event.hopper.synctimeout").sendPrefixedMessage(player);
playerData.setSyncType(null); playerData.setSyncType(null);
} }
}, Settings.LINK_TIMEOUT.getLong() * level.getLinkAmount()); }, Settings.LINK_TIMEOUT.getLong() * this.level.getLinkAmount());
} }
public void link(Block toLink, boolean filtered, Player player) { public void link(Block toLink, boolean filtered, Player player) {
EpicHoppers instance = EpicHoppers.getInstance(); EpicHoppers instance = EpicHoppers.getPlugin(EpicHoppers.class);
if (location.getWorld().equals(toLink.getLocation().getWorld()) if (this.location.getWorld().equals(toLink.getLocation().getWorld())
&& !player.hasPermission("EpicHoppers.Override") && !player.hasPermission("EpicHoppers.Override")
&& !player.hasPermission("EpicHoppers.Admin") && !player.hasPermission("EpicHoppers.Admin")
&& location.distance(toLink.getLocation()) > level.getRange()) { && this.location.distance(toLink.getLocation()) > this.level.getRange()) {
instance.getLocale().getMessage("event.hopper.syncoutofrange").sendPrefixedMessage(player); instance.getLocale().getMessage("event.hopper.syncoutofrange").sendPrefixedMessage(player);
return; return;
} }
if (linkedBlocks.contains(toLink.getLocation())) { if (this.linkedBlocks.contains(toLink.getLocation())) {
instance.getLocale().getMessage("event.hopper.already").sendPrefixedMessage(player); instance.getLocale().getMessage("event.hopper.already").sendPrefixedMessage(player);
return; return;
} }
@ -200,14 +208,14 @@ public class Hopper {
} }
this.lastPlayerOpened = player.getUniqueId(); this.lastPlayerOpened = player.getUniqueId();
if (level.getLinkAmount() > 1) { if (this.level.getLinkAmount() > 1) {
if (linkedBlocks.size() >= level.getLinkAmount()) { if (this.linkedBlocks.size() >= this.level.getLinkAmount()) {
instance.getLocale().getMessage("event.hopper.syncdone").sendPrefixedMessage(player); instance.getLocale().getMessage("event.hopper.syncdone").sendPrefixedMessage(player);
cancelSync(player); cancelSync(player);
return; return;
} }
instance.getLocale().getMessage("event.hopper.syncsuccessmore") instance.getLocale().getMessage("event.hopper.syncsuccessmore")
.processPlaceholder("amount", level.getLinkAmount() - linkedBlocks.size()) .processPlaceholder("amount", this.level.getLinkAmount() - this.linkedBlocks.size())
.sendPrefixedMessage(player); .sendPrefixedMessage(player);
return; return;
} }
@ -236,31 +244,31 @@ public class Hopper {
} }
public Location getLocation() { public Location getLocation() {
return location.clone(); return this.location.clone();
} }
public Block getBlock() { public Block getBlock() {
return location.getBlock(); return this.location.getBlock();
} }
public World getWorld() { public World getWorld() {
return location.getWorld(); return this.location.getWorld();
} }
public int getX() { public int getX() {
return location.getBlockX(); return this.location.getBlockX();
} }
public int getY() { public int getY() {
return location.getBlockY(); return this.location.getBlockY();
} }
public int getZ() { public int getZ() {
return location.getBlockZ(); return this.location.getBlockZ();
} }
public Level getLevel() { public Level getLevel() {
return level; return this.level;
} }
public void setLevel(Level level) { public void setLevel(Level level) {
@ -268,7 +276,7 @@ public class Hopper {
} }
public UUID getPlacedBy() { public UUID getPlacedBy() {
return placedBy; return this.placedBy;
} }
public void setPlacedBy(UUID placedBy) { public void setPlacedBy(UUID placedBy) {
@ -276,15 +284,15 @@ public class Hopper {
} }
public UUID getLastPlayerOpened() { public UUID getLastPlayerOpened() {
return lastPlayerOpened; return this.lastPlayerOpened;
} }
public void setLastPlayerOpened(UUID uuid) { public void setLastPlayerOpened(UUID uuid) {
lastPlayerOpened = uuid; this.lastPlayerOpened = uuid;
} }
public TeleportTrigger getTeleportTrigger() { public TeleportTrigger getTeleportTrigger() {
return teleportTrigger; return this.teleportTrigger;
} }
public void setTeleportTrigger(TeleportTrigger teleportTrigger) { public void setTeleportTrigger(TeleportTrigger teleportTrigger) {
@ -292,14 +300,15 @@ public class Hopper {
} }
public List<Location> getLinkedBlocks() { public List<Location> getLinkedBlocks() {
return new ArrayList<>(linkedBlocks); return new ArrayList<>(this.linkedBlocks);
} }
public void addLinkedBlock(Location location, LinkType type) { public void addLinkedBlock(Location location, LinkType type) {
if (type == LinkType.REGULAR) if (type == LinkType.REGULAR) {
linkedBlocks.add(location); this.linkedBlocks.add(location);
else } else {
filter.setEndPoint(location); this.filter.setEndPoint(location);
}
} }
public void removeLinkedBlock(Location location) { public void removeLinkedBlock(Location location) {
@ -311,7 +320,7 @@ public class Hopper {
} }
public Filter getFilter() { public Filter getFilter() {
return filter; return this.filter;
} }
public void setFilter(Filter filter) { public void setFilter(Filter filter) {
@ -339,12 +348,12 @@ public class Hopper {
} }
public void cancelSync(Player player) { public void cancelSync(Player player) {
Bukkit.getScheduler().cancelTask(syncId); Bukkit.getScheduler().cancelTask(this.syncId);
EpicHoppers.getInstance().getPlayerDataManager().getPlayerData(player).setSyncType(null); EpicHoppers.getPlugin(EpicHoppers.class).getPlayerDataManager().getPlayerData(player).setSyncType(null);
} }
public int getId() { public int getId() {
return id; return this.id;
} }
public void setId(int id) { public void setId(int id) {
@ -352,7 +361,7 @@ public class Hopper {
} }
public Player getActivePlayer() { public Player getActivePlayer() {
return activePlayer; return this.activePlayer;
} }
public void setActivePlayer(Player activePlayer) { public void setActivePlayer(Player activePlayer) {

View File

@ -9,7 +9,6 @@ import org.bukkit.block.Block;
import java.util.UUID; import java.util.UUID;
public class HopperBuilder { public class HopperBuilder {
private final Hopper hopper; private final Hopper hopper;
public HopperBuilder(Location location) { public HopperBuilder(Location location) {
@ -31,8 +30,9 @@ public class HopperBuilder {
} }
public HopperBuilder addLinkedBlocks(LinkType type, Location... linkedBlocks) { public HopperBuilder addLinkedBlocks(LinkType type, Location... linkedBlocks) {
for (Location location : linkedBlocks) for (Location location : linkedBlocks) {
hopper.addLinkedBlock(location, type); this.hopper.addLinkedBlock(location, type);
}
return this; return this;
} }

View File

@ -13,9 +13,14 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class HopperManager { public class HopperManager {
private final Map<Location, Hopper> registeredHoppers = new HashMap<>();
private final EpicHoppers plugin;
protected boolean ready; protected boolean ready;
private final Map<Location, Hopper> registeredHoppers = new HashMap<>(); public HopperManager(EpicHoppers plugin) {
this.plugin = plugin;
}
/** /**
* Sets {@link #isReady()} to {@code true}.<br> * Sets {@link #isReady()} to {@code true}.<br>
@ -33,18 +38,19 @@ public class HopperManager {
} }
public Hopper addHopper(Hopper hopper) { public Hopper addHopper(Hopper hopper) {
registeredHoppers.put(roundLocation(hopper.getLocation()), hopper); this.registeredHoppers.put(roundLocation(hopper.getLocation()), hopper);
return hopper; return hopper;
} }
@Deprecated @Deprecated
public void addHopper(Location location, Hopper hopper) { public void addHopper(Location location, Hopper hopper) {
registeredHoppers.put(roundLocation(location), hopper); this.registeredHoppers.put(roundLocation(location), hopper);
} }
public void addHoppers(Collection<Hopper> hoppers) { public void addHoppers(Collection<Hopper> hoppers) {
for (Hopper hopper : hoppers) for (Hopper hopper : hoppers) {
registeredHoppers.put(hopper.getLocation(), hopper); this.registeredHoppers.put(hopper.getLocation(), hopper);
}
} }
/** /**
@ -56,26 +62,29 @@ public class HopperManager {
public Hopper removeHopper(Location location) { public Hopper removeHopper(Location location) {
Hopper removed = this.registeredHoppers.remove(location); Hopper removed = this.registeredHoppers.remove(location);
for (Hopper hopper : this.registeredHoppers.values()) for (Hopper hopper : this.registeredHoppers.values()) {
hopper.removeLinkedBlock(location); hopper.removeLinkedBlock(location);
}
for (Level level : EpicHoppers.getInstance().getLevelManager().getLevels().values()) for (Level level : this.plugin.getLevelManager().getLevels().values()) {
for (Module module : level.getRegisteredModules()) for (Module module : level.getRegisteredModules()) {
module.clearData(removed); module.clearData(removed);
}
}
return removed; return removed;
} }
public Hopper getHopper(Location location) { public Hopper getHopper(Location location) {
if (!registeredHoppers.containsKey(location = roundLocation(location))) { if (!this.registeredHoppers.containsKey(location = roundLocation(location))) {
if (!this.ready) { if (!this.ready) {
throw new IllegalStateException("Hoppers are still being loaded"); throw new IllegalStateException("Hoppers are still being loaded");
} }
Hopper hopper = addHopper(new Hopper(location)); Hopper hopper = addHopper(new Hopper(location));
EpicHoppers.getInstance().getDataManager().createHopper(hopper); this.plugin.getDataManager().createHopper(hopper);
} }
return registeredHoppers.get(location); return this.registeredHoppers.get(location);
} }
public Hopper getHopper(Block block) { public Hopper getHopper(Block block) {
@ -86,11 +95,11 @@ public class HopperManager {
* <em>Returns {@code false} if {@link #isReady()} is false too</em> * <em>Returns {@code false} if {@link #isReady()} is false too</em>
*/ */
public boolean isHopper(Location location) { public boolean isHopper(Location location) {
return registeredHoppers.containsKey(roundLocation(location)); return this.registeredHoppers.containsKey(roundLocation(location));
} }
public Map<Location, Hopper> getHoppers() { public Map<Location, Hopper> getHoppers() {
return Collections.unmodifiableMap(registeredHoppers); return Collections.unmodifiableMap(this.registeredHoppers);
} }
public Hopper getHopperFromPlayer(Player player) { public Hopper getHopperFromPlayer(Player player) {
@ -98,7 +107,7 @@ public class HopperManager {
throw new IllegalStateException("Hoppers are still being loaded"); throw new IllegalStateException("Hoppers are still being loaded");
} }
for (Hopper hopper : registeredHoppers.values()) { for (Hopper hopper : this.registeredHoppers.values()) {
if (hopper.getLastPlayerOpened() == player.getUniqueId()) { if (hopper.getLastPlayerOpened() == player.getUniqueId()) {
return hopper; return hopper;
} }

View File

@ -1,7 +1,5 @@
package com.songoda.epichoppers.hopper; package com.songoda.epichoppers.hopper;
public enum ItemType { public enum ItemType {
WHITELIST, BLACKLIST, VOID, AUTO_SELL_WHITELIST, AUTO_SELL_BLACKLIST WHITELIST, BLACKLIST, VOID, AUTO_SELL_WHITELIST, AUTO_SELL_BLACKLIST
} }

View File

@ -1,6 +1,5 @@
package com.songoda.epichoppers.hopper; package com.songoda.epichoppers.hopper;
public enum LinkType { public enum LinkType {
REGULAR, REJECT REGULAR, REJECT
} }

View File

@ -7,7 +7,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class Level { public class Level {
private final ArrayList<Module> registeredModules; private final ArrayList<Module> registeredModules;
private final List<String> description = new ArrayList<>(); private final List<String> description = new ArrayList<>();
private final int level, costExperience, costEconomy, range, amount, linkAmount; private final int level, costExperience, costEconomy, range, amount, linkAmount;
@ -29,91 +28,108 @@ public class Level {
} }
public void buildDescription() { public void buildDescription() {
EpicHoppers instance = EpicHoppers.getInstance(); EpicHoppers instance = EpicHoppers.getPlugin(EpicHoppers.class);
description.clear(); this.description.clear();
description.add(instance.getLocale().getMessage("interface.hopper.range") this.description.add(instance.getLocale().getMessage("interface.hopper.range")
.processPlaceholder("range", range).getMessage()); .processPlaceholder("range", this.range).getMessage());
description.add(instance.getLocale().getMessage("interface.hopper.amount") this.description.add(instance.getLocale().getMessage("interface.hopper.amount")
.processPlaceholder("amount", amount).getMessage()); .processPlaceholder("amount", this.amount).getMessage());
if (linkAmount != 1) if (this.linkAmount != 1) {
description.add(instance.getLocale().getMessage("interface.hopper.linkamount") this.description.add(instance.getLocale().getMessage("interface.hopper.linkamount")
.processPlaceholder("amount", linkAmount).getMessage()); .processPlaceholder("amount", this.linkAmount).getMessage());
if (filter) }
description.add(instance.getLocale().getMessage("interface.hopper.filter") if (this.filter) {
.processPlaceholder("enabled", EpicHoppers.getInstance().getLocale() this.description.add(instance.getLocale().getMessage("interface.hopper.filter")
.processPlaceholder("enabled", instance.getLocale()
.getMessage("general.word.enabled").getMessage()).getMessage()); .getMessage("general.word.enabled").getMessage()).getMessage());
if (teleport) }
description.add(instance.getLocale().getMessage("interface.hopper.teleport") if (this.teleport) {
.processPlaceholder("enabled", EpicHoppers.getInstance() this.description.add(instance
.getLocale().getMessage("general.word.enabled").getMessage()).getMessage()); .getLocale()
.getMessage("interface.hopper.teleport")
.processPlaceholder(
"enabled",
instance
.getLocale()
.getMessage("general.word.enabled")
.getMessage())
.getMessage());
}
for (Module module : registeredModules) { for (Module module : this.registeredModules) {
description.add(module.getDescription()); this.description.add(module.getDescription());
} }
} }
public int getLevel() { public int getLevel() {
return level; return this.level;
} }
public int getRange() { public int getRange() {
return range; return this.range;
} }
public int getAmount() { public int getAmount() {
return amount; return this.amount;
} }
public boolean isFilter() { public boolean isFilter() {
return filter; return this.filter;
} }
public boolean isTeleport() { public boolean isTeleport() {
return teleport; return this.teleport;
} }
public int getLinkAmount() { public int getLinkAmount() {
return linkAmount; return this.linkAmount;
} }
public int getCostExperience() { public int getCostExperience() {
return costExperience; return this.costExperience;
} }
public int getCostEconomy() { public int getCostEconomy() {
return costEconomy; return this.costEconomy;
} }
public List<String> getDescription() { public List<String> getDescription() {
return new ArrayList<>(description); return new ArrayList<>(this.description);
} }
public ArrayList<Module> getRegisteredModules() { public ArrayList<Module> getRegisteredModules() {
return new ArrayList<>(registeredModules); return new ArrayList<>(this.registeredModules);
} }
public void addModule(Module module) { public void addModule(Module module) {
registeredModules.add(module); this.registeredModules.add(module);
buildDescription(); buildDescription();
} }
public Module getModule(String name) { public Module getModule(String name) {
return registeredModules == null ? null : if (this.registeredModules == null) {
registeredModules.stream().filter(module -> module.getName().equals(name)).findFirst().orElse(null); return null;
}
for (Module module : this.registeredModules) {
if (module.getName().equals(name)) {
return module;
}
}
return null;
} }
} }

View File

@ -14,24 +14,22 @@ import java.util.NavigableMap;
import java.util.TreeMap; import java.util.TreeMap;
public class LevelManager { public class LevelManager {
private final NavigableMap<Integer, Level> registeredLevels = new TreeMap<>(); private final NavigableMap<Integer, Level> registeredLevels = new TreeMap<>();
public void addLevel(int level, int costExperience, int costEconomy, int range, int amount, boolean filter, boolean teleport, int linkAmount, ArrayList<Module> modules) { public void addLevel(int level, int costExperience, int costEconomy, int range, int amount, boolean filter, boolean teleport, int linkAmount, ArrayList<Module> modules) {
registeredLevels.put(level, new Level(level, costExperience, costEconomy, range, amount, filter, teleport, linkAmount, modules)); this.registeredLevels.put(level, new Level(level, costExperience, costEconomy, range, amount, filter, teleport, linkAmount, modules));
} }
public Level getLevel(int level) { public Level getLevel(int level) {
return registeredLevels.get(level); return this.registeredLevels.get(level);
} }
public Level getLevel(ItemStack item) { public Level getLevel(ItemStack item) {
NBTItem nbtItem = new NBTItem(item); NBTItem nbtItem = new NBTItem(item);
if (nbtItem.hasKey("level")) if (nbtItem.hasTag("level")) {
return getLevel(nbtItem.getInteger("level")); return getLevel(nbtItem.getInteger("level"));
}
// Legacy trash. // Legacy trash.
if (item.hasItemMeta() && item.getItemMeta().getDisplayName().contains(":")) { if (item.hasItemMeta() && item.getItemMeta().getDisplayName().contains(":")) {
@ -45,8 +43,9 @@ public class LevelManager {
public boolean isEpicHopper(ItemStack item) { public boolean isEpicHopper(ItemStack item) {
NBTCore nbt = NmsManager.getNbt(); NBTCore nbt = NmsManager.getNbt();
if (nbt.of(item).has("level")) if (nbt.of(item).has("level")) {
return true; return true;
}
return item.hasItemMeta() return item.hasItemMeta()
// Legacy Trash. // Legacy Trash.
@ -55,25 +54,25 @@ public class LevelManager {
public Level getLowestLevel() { public Level getLowestLevel() {
return registeredLevels.firstEntry().getValue(); return this.registeredLevels.firstEntry().getValue();
} }
public Level getHighestLevel() { public Level getHighestLevel() {
return registeredLevels.lastEntry().getValue(); return this.registeredLevels.lastEntry().getValue();
} }
public boolean isLevel(int level) { public boolean isLevel(int level) {
return registeredLevels.containsKey(level); return this.registeredLevels.containsKey(level);
} }
public Map<Integer, Level> getLevels() { public Map<Integer, Level> getLevels() {
return Collections.unmodifiableMap(registeredLevels); return Collections.unmodifiableMap(this.registeredLevels);
} }
public void clear() { public void clear() {
registeredLevels.clear(); this.registeredLevels.clear();
} }
} }

View File

@ -16,21 +16,20 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public abstract class Module { public abstract class Module {
private static final Map<String, Config> CONFIGS = new HashMap<>();
private static final Map<String, Config> configs = new HashMap<>();
protected final EpicHoppers plugin; protected final EpicHoppers plugin;
private final Config config; private final Config config;
public Module(EpicHoppers plugin) { public Module(EpicHoppers plugin) {
this.plugin = plugin; this.plugin = plugin;
if (!configs.containsKey(getName())) { if (!CONFIGS.containsKey(getName())) {
Config config = new Config(plugin, File.separator + "modules", getName() + ".yml"); Config config = new Config(plugin, File.separator + "modules", getName() + ".yml");
configs.put(getName(), config); CONFIGS.put(getName(), config);
config.load(); config.load();
} }
this.config = configs.get(getName()); this.config = CONFIGS.get(getName());
} }
public abstract String getName(); public abstract String getName();
@ -50,7 +49,7 @@ public abstract class Module {
} }
public void saveData(Hopper hopper, String setting, Object value, Object toCache) { public void saveData(Hopper hopper, String setting, Object value, Object toCache) {
config.set("data." + Methods.serializeLocation(hopper.getLocation()) + "." + setting, value); this.config.set("data." + Methods.serializeLocation(hopper.getLocation()) + "." + setting, value);
modifyDataCache(hopper, setting, toCache); modifyDataCache(hopper, setting, toCache);
} }
@ -60,20 +59,21 @@ public abstract class Module {
protected Object getData(Hopper hopper, String setting) { protected Object getData(Hopper hopper, String setting) {
String cacheStr = getName() + "." + setting; String cacheStr = getName() + "." + setting;
if (hopper.isDataCachedInModuleCache(cacheStr)) if (hopper.isDataCachedInModuleCache(cacheStr)) {
return hopper.getDataFromModuleCache(cacheStr); return hopper.getDataFromModuleCache(cacheStr);
}
Object data = config.get("data." + Methods.serializeLocation(hopper.getLocation()) + "." + setting); Object data = this.config.get("data." + Methods.serializeLocation(hopper.getLocation()) + "." + setting);
modifyDataCache(hopper, setting, data); modifyDataCache(hopper, setting, data);
return data; return data;
} }
public void clearData(Hopper hopper) { public void clearData(Hopper hopper) {
config.set("data." + Methods.serializeLocation(hopper.getLocation()), null); this.config.set("data." + Methods.serializeLocation(hopper.getLocation()), null);
hopper.clearModuleCache(); hopper.clearModuleCache();
} }
public void saveDataToFile() { public void saveDataToFile() {
config.save(); this.config.save();
} }
} }

View File

@ -31,15 +31,15 @@ import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class ModuleAutoCrafting extends Module { public class ModuleAutoCrafting extends Module {
private static final Map<ItemStack, Recipes> CACHED_RECIPES = new ConcurrentHashMap<>();
private static final Map<Hopper, ItemStack> CACHED_CRAFTING = new ConcurrentHashMap<>();
private static final ItemStack NO_CRAFT = new ItemStack(Material.AIR);
private static final Map<ItemStack, Recipes> cachedRecipes = new ConcurrentHashMap<>(); private final boolean crafterEjection;
private static final Map<Hopper, ItemStack> cachedCrafting = new ConcurrentHashMap<>();
private static final ItemStack noCraft = new ItemStack(Material.AIR);
private boolean crafterEjection;
public ModuleAutoCrafting(EpicHoppers plugin) { public ModuleAutoCrafting(EpicHoppers plugin) {
super(plugin); super(plugin);
crafterEjection = Settings.AUTOCRAFT_JAM_EJECT.getBoolean(); this.crafterEjection = Settings.AUTOCRAFT_JAM_EJECT.getBoolean();
} }
@Override @Override
@ -50,8 +50,9 @@ public class ModuleAutoCrafting extends Module {
@Override @Override
public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) {
final ItemStack toCraft; final ItemStack toCraft;
if (hopper == null || (toCraft = getAutoCrafting(hopper)) == null || toCraft.getType() == Material.AIR) if (hopper == null || (toCraft = getAutoCrafting(hopper)) == null || toCraft.getType() == Material.AIR) {
return; return;
}
synchronized (hopperCache) { //TODO: Check if this is required synchronized (hopperCache) { //TODO: Check if this is required
ItemStack[] items = hopperCache.cachedInventory; ItemStack[] items = hopperCache.cachedInventory;
@ -67,8 +68,12 @@ public class ModuleAutoCrafting extends Module {
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
ItemStack item = items[i]; ItemStack item = items[i];
if (item == null) continue; if (item == null) {
if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) continue; continue;
}
if (item.hasItemMeta() && item.getItemMeta().hasDisplayName()) {
continue;
}
boolean sameMaterial = Methods.isSimilarMaterial(item, ingredient.item); boolean sameMaterial = Methods.isSimilarMaterial(item, ingredient.item);
@ -82,7 +87,9 @@ public class ModuleAutoCrafting extends Module {
} }
// Still doesn't not match --> Skip this item // Still doesn't not match --> Skip this item
if (!sameMaterial) continue; if (!sameMaterial) {
continue;
}
} }
if (item.getAmount() >= amount) { if (item.getAmount() >= amount) {
@ -95,7 +102,9 @@ public class ModuleAutoCrafting extends Module {
} }
// Not enough ingredients for this recipe // Not enough ingredients for this recipe
if (amount != 0) continue recipeLoop; if (amount != 0) {
continue recipeLoop;
}
} }
boolean freeSlotAfterRemovingIngredients = boolean freeSlotAfterRemovingIngredients =
@ -105,7 +114,7 @@ public class ModuleAutoCrafting extends Module {
recipe.result.isSimilar(item))); recipe.result.isSimilar(item)));
// jam check: is this hopper gummed up? // jam check: is this hopper gummed up?
if (crafterEjection && !freeSlotAfterRemovingIngredients) { if (this.crafterEjection && !freeSlotAfterRemovingIngredients) {
// Crafter can't function if there's nowhere to put the output // Crafter can't function if there's nowhere to put the output
// ¯\_()_/¯ // ¯\_()_/¯
@ -180,10 +189,10 @@ public class ModuleAutoCrafting extends Module {
public ItemStack getGUIButton(Hopper hopper) { public ItemStack getGUIButton(Hopper hopper) {
ItemStack crafting = CompatibleMaterial.CRAFTING_TABLE.getItem(); ItemStack crafting = CompatibleMaterial.CRAFTING_TABLE.getItem();
ItemMeta craftingmeta = crafting.getItemMeta(); ItemMeta craftingmeta = crafting.getItemMeta();
craftingmeta.setDisplayName(EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.craftingtitle") craftingmeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.craftingtitle")
.getMessage()); .getMessage());
ArrayList<String> lorecrafting = new ArrayList<>(); ArrayList<String> lorecrafting = new ArrayList<>();
String[] parts = EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.craftinglore") String[] parts = this.plugin.getLocale().getMessage("interface.hopper.craftinglore")
.getMessage().split("\\|"); .getMessage().split("\\|");
for (String line : parts) { for (String line : parts) {
lorecrafting.add(TextUtils.formatText(line)); lorecrafting.add(TextUtils.formatText(line));
@ -196,7 +205,7 @@ public class ModuleAutoCrafting extends Module {
@Override @Override
public void runButtonPress(Player player, Hopper hopper, ClickType type) { public void runButtonPress(Player player, Hopper hopper, ClickType type) {
hopper.setActivePlayer(player); hopper.setActivePlayer(player);
EpicHoppers.getInstance().getGuiManager().showGUI(player, new GUICrafting(this, hopper, player)); this.plugin.getGuiManager().showGUI(player, new GUICrafting(this,this.plugin, hopper, player));
} }
@Override @Override
@ -205,26 +214,30 @@ public class ModuleAutoCrafting extends Module {
if (itemStack != null && itemStack.getType() != Material.AIR) { if (itemStack != null && itemStack.getType() != Material.AIR) {
return getRecipes(itemStack).getPossibleIngredientTypes(); return getRecipes(itemStack).getPossibleIngredientTypes();
} }
return Collections.EMPTY_LIST; return Collections.emptyList();
} }
@Override @Override
public String getDescription() { public String getDescription() {
return EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.crafting").processPlaceholder("enabled", return this.plugin.getLocale()
EpicHoppers.getInstance().getLocale().getMessage("general.word.enabled").getMessage()).getMessage(); .getMessage("interface.hopper.crafting")
.processPlaceholder("enabled", this.plugin.getLocale().getMessage("general.word.enabled").getMessage())
.getMessage();
} }
@Override @Override
public void clearData(Hopper hopper) { public void clearData(Hopper hopper) {
super.clearData(hopper); super.clearData(hopper);
cachedCrafting.remove(hopper); CACHED_CRAFTING.remove(hopper);
} }
private Recipes getRecipes(ItemStack toCraft) { private Recipes getRecipes(ItemStack toCraft) {
Recipes recipes = cachedRecipes.get(toCraft); Recipes recipes = CACHED_RECIPES.get(toCraft);
if (Settings.AUTOCRAFT_BLACKLIST.getStringList().stream() if (Settings.AUTOCRAFT_BLACKLIST.getStringList().stream()
.anyMatch(r -> r.equalsIgnoreCase(toCraft.getType().name()))) .anyMatch(r -> r.equalsIgnoreCase(toCraft.getType().name()))) {
return new Recipes(); return new Recipes();
}
if (recipes == null) { if (recipes == null) {
try { try {
recipes = new Recipes(Bukkit.getServer().getRecipesFor(toCraft)); recipes = new Recipes(Bukkit.getServer().getRecipesFor(toCraft));
@ -238,32 +251,37 @@ public class ModuleAutoCrafting extends Module {
Recipe recipe = recipeIterator.next(); Recipe recipe = recipeIterator.next();
ItemStack stack = recipe.getResult(); ItemStack stack = recipe.getResult();
if (Methods.isSimilarMaterial(stack, toCraft)) if (Methods.isSimilarMaterial(stack, toCraft)) {
recipes.addRecipe(recipe); recipes.addRecipe(recipe);
}
} catch (Throwable ignored) { } catch (Throwable ignored) {
} }
} }
} }
cachedRecipes.put(toCraft, recipes); CACHED_RECIPES.put(toCraft, recipes);
} }
return recipes; return recipes;
} }
public ItemStack getAutoCrafting(Hopper hopper) { public ItemStack getAutoCrafting(Hopper hopper) {
if (cachedCrafting.containsKey(hopper)) if (CACHED_CRAFTING.containsKey(hopper)) {
return cachedCrafting.get(hopper); return CACHED_CRAFTING.get(hopper);
}
Object autocrafting = getData(hopper, "autocrafting"); Object autocrafting = getData(hopper, "autocrafting");
ItemStack toCraft = autocrafting instanceof ItemStack ? (ItemStack) autocrafting : decode((String) autocrafting); ItemStack toCraft = autocrafting instanceof ItemStack ? (ItemStack) autocrafting : decode((String) autocrafting);
cachedCrafting.put(hopper, toCraft == null ? noCraft : toCraft); CACHED_CRAFTING.put(hopper, toCraft == null ? NO_CRAFT : toCraft);
return toCraft; return toCraft;
} }
public void setAutoCrafting(Hopper hopper, Player player, ItemStack autoCrafting) { public void setAutoCrafting(Hopper hopper, Player player, ItemStack autoCrafting) {
saveData(hopper, "autocrafting", autoCrafting == null ? null : encode(autoCrafting), autoCrafting); saveData(hopper, "autocrafting", autoCrafting == null ? null : encode(autoCrafting), autoCrafting);
cachedCrafting.put(hopper, autoCrafting == null ? noCraft : autoCrafting); CACHED_CRAFTING.put(hopper, autoCrafting == null ? NO_CRAFT : autoCrafting);
if (autoCrafting == null) return; if (autoCrafting == null) {
return;
}
int excess = autoCrafting.getAmount() - 1; int excess = autoCrafting.getAmount() - 1;
autoCrafting.setAmount(1); autoCrafting.setAmount(1);
if (excess > 0 && player != null) { if (excess > 0 && player != null) {
@ -285,7 +303,7 @@ public class ModuleAutoCrafting extends Module {
1, Short.parseShort(autoCraftingParts.length == 2 ? autoCraftingParts[1] : "0")); 1, Short.parseShort(autoCraftingParts.length == 2 ? autoCraftingParts[1] : "0"));
} }
private final static class Recipes { private static final class Recipes {
private final List<SimpleRecipe> recipes = new ArrayList<>(); private final List<SimpleRecipe> recipes = new ArrayList<>();
// Used for the blacklist to ensure that items are not going to get transferred // Used for the blacklist to ensure that items are not going to get transferred
private final List<Material> possibleIngredientTypes = new ArrayList<>(); private final List<Material> possibleIngredientTypes = new ArrayList<>();
@ -298,11 +316,11 @@ public class ModuleAutoCrafting extends Module {
} }
public List<SimpleRecipe> getRecipes() { public List<SimpleRecipe> getRecipes() {
return Collections.unmodifiableList(recipes); return Collections.unmodifiableList(this.recipes);
} }
public List<Material> getPossibleIngredientTypes() { public List<Material> getPossibleIngredientTypes() {
return Collections.unmodifiableList(possibleIngredientTypes); return Collections.unmodifiableList(this.possibleIngredientTypes);
} }
public void addRecipe(Recipe recipe) { public void addRecipe(Recipe recipe) {
@ -315,19 +333,21 @@ public class ModuleAutoCrafting extends Module {
} }
// Skip unsupported recipe type // Skip unsupported recipe type
if (simpleRecipe == null) return; if (simpleRecipe == null) {
return;
}
this.recipes.add(simpleRecipe); this.recipes.add(simpleRecipe);
// Keep a list of all possible ingredients. // Keep a list of all possible ingredients.
for (SimpleRecipe.SimpleIngredient ingredient : simpleRecipe.ingredients) { for (SimpleRecipe.SimpleIngredient ingredient : simpleRecipe.ingredients) {
if (!possibleIngredientTypes.contains(ingredient.item.getType())) { if (!this.possibleIngredientTypes.contains(ingredient.item.getType())) {
possibleIngredientTypes.add(ingredient.item.getType()); this.possibleIngredientTypes.add(ingredient.item.getType());
} }
for (ItemStack material : ingredient.alternativeTypes) { for (ItemStack material : ingredient.alternativeTypes) {
if (!possibleIngredientTypes.contains(material.getType())) { if (!this.possibleIngredientTypes.contains(material.getType())) {
possibleIngredientTypes.add(material.getType()); this.possibleIngredientTypes.add(material.getType());
} }
} }
} }
@ -338,15 +358,15 @@ public class ModuleAutoCrafting extends Module {
} }
public boolean hasRecipes() { public boolean hasRecipes() {
return !recipes.isEmpty(); return !this.recipes.isEmpty();
} }
public void clearRecipes() { public void clearRecipes() {
recipes.clear(); this.recipes.clear();
} }
} }
private final static class SimpleRecipe { private static final class SimpleRecipe {
private final SimpleIngredient[] ingredients; private final SimpleIngredient[] ingredients;
private final ItemStack result; private final ItemStack result;
@ -384,7 +404,9 @@ public class ModuleAutoCrafting extends Module {
} catch (NoSuchMethodError ignore) { // Method missing in Spigot 1.12.2 } catch (NoSuchMethodError ignore) { // Method missing in Spigot 1.12.2
} }
if (item == null) continue; if (item == null) {
continue;
}
processIngredient(ingredients, item, rChoice); processIngredient(ingredients, item, rChoice);
} }
@ -449,11 +471,11 @@ public class ModuleAutoCrafting extends Module {
} }
public int getAdditionalAmount() { public int getAdditionalAmount() {
return additionalAmount; return this.additionalAmount;
} }
public void addAdditionalAmount(int amountToAdd) { public void addAdditionalAmount(int amountToAdd) {
additionalAmount += amountToAdd; this.additionalAmount += amountToAdd;
} }
/** /**
@ -463,12 +485,15 @@ public class ModuleAutoCrafting extends Module {
* while ignoring any item amounts, true otherwise false * while ignoring any item amounts, true otherwise false
*/ */
public boolean isSimilar(Object o) { public boolean isSimilar(Object o) {
if (this == o) return true; if (this == o) {
if (o == null || getClass() != o.getClass()) return false; return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SimpleIngredient that = (SimpleIngredient) o; SimpleIngredient that = (SimpleIngredient) o;
return item.isSimilar(that.item) && return this.item.isSimilar(that.item) && Arrays.equals(this.alternativeTypes, that.alternativeTypes);
Arrays.equals(alternativeTypes, that.alternativeTypes);
} }
} }
} }

View File

@ -2,6 +2,7 @@ package com.songoda.epichoppers.hopper.levels.modules;
import com.songoda.core.compatibility.CompatibleMaterial; import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.hooks.EconomyManager; import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.utils.NumberUtils;
import com.songoda.core.utils.TextUtils; import com.songoda.core.utils.TextUtils;
import com.songoda.epichoppers.EpicHoppers; import com.songoda.epichoppers.EpicHoppers;
import com.songoda.epichoppers.gui.GUIAutoSellFilter; import com.songoda.epichoppers.gui.GUIAutoSellFilter;
@ -25,13 +26,14 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class ModuleAutoSell extends Module { public class ModuleAutoSell extends Module {
private static final Map<Hopper, Boolean> CACHED_NOTIFICATIONS = new ConcurrentHashMap<>();
private final int timeOut; private final int timeOut;
private final int hopperTickRate; private final int hopperTickRate;
private static final Map<Hopper, Boolean> cachedNotifications = new ConcurrentHashMap<>();
public ModuleAutoSell(EpicHoppers plugin, int timeOut) { public ModuleAutoSell(EpicHoppers plugin, int timeOut) {
super(plugin); super(plugin);
this.timeOut = timeOut * 20; this.timeOut = timeOut * 20;
this.hopperTickRate = Settings.HOP_TICKS.getInt(); this.hopperTickRate = Settings.HOP_TICKS.getInt();
} }
@ -46,15 +48,19 @@ public class ModuleAutoSell extends Module {
int currentTime = getTime(hopper); int currentTime = getTime(hopper);
if (currentTime == -9999) return; if (currentTime == -9999) {
return;
}
int subtract = getTime(hopper) - hopperTickRate; int subtract = getTime(hopper) - this.hopperTickRate;
if (subtract <= 0) { if (subtract <= 0) {
int amountSold = 0; int amountSold = 0;
double totalValue = 0; double totalValue = 0;
if (!EconomyManager.isEnabled()) return; if (!EconomyManager.isEnabled()) {
return;
}
OfflinePlayer player = Bukkit.getOfflinePlayer(hopper.getPlacedBy()); OfflinePlayer player = Bukkit.getOfflinePlayer(hopper.getPlacedBy());
@ -62,19 +68,23 @@ public class ModuleAutoSell extends Module {
for (int i = 0; i < hopperCache.cachedInventory.length; i++) { for (int i = 0; i < hopperCache.cachedInventory.length; i++) {
final ItemStack itemStack = hopperCache.cachedInventory[i]; final ItemStack itemStack = hopperCache.cachedInventory[i];
if (itemStack == null) continue; if (itemStack == null) {
continue;
}
Filter filter = hopper.getFilter(); Filter filter = hopper.getFilter();
if (filter.getAutoSellWhiteList().isEmpty()) { if (filter.getAutoSellWhiteList().isEmpty()) {
// Check blacklist // Check blacklist
if (filter.getAutoSellBlackList().stream().anyMatch(item -> Methods.isSimilarMaterial(itemStack, item))) if (filter.getAutoSellBlackList().stream().anyMatch(item -> Methods.isSimilarMaterial(itemStack, item))) {
continue; continue;
}
} else { } else {
// Check whitelist // Check whitelist
if (filter.getAutoSellWhiteList().stream().noneMatch(item -> Methods.isSimilarMaterial(itemStack, item))) if (filter.getAutoSellWhiteList().stream().noneMatch(item -> Methods.isSimilarMaterial(itemStack, item))) {
continue; continue;
} }
}
// Get the value from config or ShopGuiPlus or EconomyShopGui // Get the value from config or ShopGuiPlus or EconomyShopGui
double value; double value;
@ -103,7 +113,9 @@ public class ModuleAutoSell extends Module {
.map(s -> Double.valueOf(s.split(",")[1])).orElse(0.0); .map(s -> Double.valueOf(s.split(",")[1])).orElse(0.0);
} }
if (value <= 0) continue; if (value <= 0) {
continue;
}
double sellingFor = value * itemStack.getAmount(); double sellingFor = value * itemStack.getAmount();
@ -112,15 +124,16 @@ public class ModuleAutoSell extends Module {
hopperCache.removeItem(i); hopperCache.removeItem(i);
} }
if (totalValue != 0) if (totalValue != 0) {
EconomyManager.deposit(player, totalValue); EconomyManager.deposit(player, totalValue);
}
if (totalValue != 0 && player.isOnline() && isNotifying(hopper)) { if (totalValue != 0 && player.isOnline() && isNotifying(hopper)) {
plugin.getLocale().getMessage("event.hopper.autosell") this.plugin.getLocale().getMessage("event.hopper.autosell")
.processPlaceholder("items", amountSold) .processPlaceholder("items", amountSold)
.processPlaceholder("amount", Methods.formatEconomy(totalValue)).sendPrefixedMessage(player.getPlayer()); .processPlaceholder("amount", NumberUtils.formatNumber(totalValue)).sendPrefixedMessage(player.getPlayer());
} }
modifyDataCache(hopper, "time", timeOut); modifyDataCache(hopper, "time", this.timeOut);
return; return;
} }
@ -132,15 +145,18 @@ public class ModuleAutoSell extends Module {
ItemStack sellItem = CompatibleMaterial.SUNFLOWER.getItem(); ItemStack sellItem = CompatibleMaterial.SUNFLOWER.getItem();
ItemMeta sellMeta = sellItem.getItemMeta(); ItemMeta sellMeta = sellItem.getItemMeta();
sellMeta.setDisplayName(EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.selltitle").getMessage()); sellMeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.selltitle").getMessage());
ArrayList<String> loreSell = new ArrayList<>(); ArrayList<String> loreSell = new ArrayList<>();
String[] parts = EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.selllore") String[] parts = this.plugin.getLocale().getMessage("interface.hopper.selllore")
.processPlaceholder("timeleft", getTime(hopper) == -9999 ? "\u221E" : (int) Math.floor(getTime(hopper) / 20)) .processPlaceholder("timeleft", getTime(hopper) == -9999 ? "" : (int) Math.floor(getTime(hopper) / 20))
.processPlaceholder("state", isNotifying(hopper)).getMessage().split("\\|"); .processPlaceholder("state", isNotifying(hopper))
.getMessage()
.split("\\|");
for (String line : parts) for (String line : parts) {
loreSell.add(TextUtils.formatText(line)); loreSell.add(TextUtils.formatText(line));
}
sellMeta.setLore(loreSell); sellMeta.setLore(loreSell);
sellItem.setItemMeta(sellMeta); sellItem.setItemMeta(sellMeta);
@ -151,7 +167,7 @@ public class ModuleAutoSell extends Module {
public void runButtonPress(Player player, Hopper hopper, ClickType type) { public void runButtonPress(Player player, Hopper hopper, ClickType type) {
if (type == ClickType.LEFT) { if (type == ClickType.LEFT) {
if (getTime(hopper) == -9999) { if (getTime(hopper) == -9999) {
saveData(hopper, "time", timeOut); saveData(hopper, "time", this.timeOut);
} else { } else {
saveData(hopper, "time", -9999); saveData(hopper, "time", -9999);
} }
@ -160,7 +176,7 @@ public class ModuleAutoSell extends Module {
} else if (type == ClickType.SHIFT_LEFT || type == ClickType.SHIFT_RIGHT) { } else if (type == ClickType.SHIFT_LEFT || type == ClickType.SHIFT_RIGHT) {
// Any shift click opens AutoSell filter configuration GUI // Any shift click opens AutoSell filter configuration GUI
hopper.setActivePlayer(player); hopper.setActivePlayer(player);
EpicHoppers.getInstance().getGuiManager().showGUI(player, new GUIAutoSellFilter(EpicHoppers.getInstance(), hopper)); this.plugin.getGuiManager().showGUI(player, new GUIAutoSellFilter(this.plugin, hopper));
} }
} }
@ -171,33 +187,37 @@ public class ModuleAutoSell extends Module {
@Override @Override
public String getDescription() { public String getDescription() {
return EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.autosell") return this.plugin.getLocale()
.processPlaceholder("seconds", (int) Math.floor(timeOut / 20)).getMessage(); .getMessage("interface.hopper.autosell")
.processPlaceholder("seconds", (int) Math.floor(this.timeOut / 20))
.getMessage();
} }
@Override @Override
public void clearData(Hopper hopper) { public void clearData(Hopper hopper) {
super.clearData(hopper); super.clearData(hopper);
cachedNotifications.remove(hopper); CACHED_NOTIFICATIONS.remove(hopper);
} }
private boolean isNotifying(Hopper hopper) { private boolean isNotifying(Hopper hopper) {
Boolean enabled = cachedNotifications.get(hopper); Boolean enabled = CACHED_NOTIFICATIONS.get(hopper);
if (enabled == null) { if (enabled == null) {
Object notifications = getData(hopper, "notifications"); Object notifications = getData(hopper, "notifications");
cachedNotifications.put(hopper, enabled = notifications != null && (boolean) notifications); CACHED_NOTIFICATIONS.put(hopper, enabled = notifications != null && (boolean) notifications);
} }
return enabled; return enabled;
} }
public void setNotifying(Hopper hopper, boolean enable) { public void setNotifying(Hopper hopper, boolean enable) {
saveData(hopper, "notifications", enable); saveData(hopper, "notifications", enable);
cachedNotifications.put(hopper, enable); CACHED_NOTIFICATIONS.put(hopper, enable);
} }
private int getTime(Hopper hopper) { private int getTime(Hopper hopper) {
Object time = getData(hopper, "time"); Object time = getData(hopper, "time");
if (time == null) return -9999; if (time == null) {
return -9999;
}
return (int) time; return (int) time;
} }
} }

View File

@ -18,7 +18,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
public class ModuleAutoSmelter extends Module { public class ModuleAutoSmelter extends Module {
private final int timeOut; private final int timeOut;
private final int hopperTickRate; private final int hopperTickRate;
@ -35,21 +34,28 @@ public class ModuleAutoSmelter extends Module {
@Override @Override
public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) {
if (!isEnabled(hopper)) return; if (!isEnabled(hopper)) {
return;
}
int currentTime = getTime(hopper); int currentTime = getTime(hopper);
if (currentTime == -9999) {
return;
}
if (currentTime == -9999) return; int subtract = currentTime - this.hopperTickRate;
int subtract = currentTime - hopperTickRate;
if (subtract <= 0) { if (subtract <= 0) {
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
final ItemStack itemStack = hopperCache.cachedInventory[i]; final ItemStack itemStack = hopperCache.cachedInventory[i];
if (itemStack == null) continue; if (itemStack == null) {
continue;
}
CompatibleMaterial material = CompatibleMaterial.getMaterial(itemStack); CompatibleMaterial material = CompatibleMaterial.getMaterial(itemStack);
if (!isSmeltable(hopper, material)) continue; if (!isSmeltable(hopper, material)) {
continue;
}
CompatibleMaterial result = CompatibleMaterial.getMaterial(itemStack).getBurnResult(); CompatibleMaterial result = CompatibleMaterial.getMaterial(itemStack).getBurnResult();
if (hopperCache.addItem(result.getItem())) { if (hopperCache.addItem(result.getItem())) {
@ -63,7 +69,7 @@ public class ModuleAutoSmelter extends Module {
} }
} }
modifyDataCache(hopper, "time", timeOut); modifyDataCache(hopper, "time", this.timeOut);
return; return;
} }
@ -74,16 +80,20 @@ public class ModuleAutoSmelter extends Module {
public ItemStack getGUIButton(Hopper hopper) { public ItemStack getGUIButton(Hopper hopper) {
ItemStack block = CompatibleMaterial.IRON_INGOT.getItem(); ItemStack block = CompatibleMaterial.IRON_INGOT.getItem();
ItemMeta blockmeta = block.getItemMeta(); ItemMeta blockmeta = block.getItemMeta();
blockmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.smelttitle").getMessage()); blockmeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.smelttitle").getMessage());
ArrayList<String> loreblock = new ArrayList<>(); ArrayList<String> loreBlock = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.hopper.smeltlore").processPlaceholder("timeleft", String[] parts = this.plugin.getLocale().getMessage("interface.hopper.smeltlore")
getTime(hopper) == -9999 ? "\u221E" : (int) Math.floor(getTime(hopper) / 20.0)).processPlaceholder("enabled", .processPlaceholder("timeleft", getTime(hopper) == -9999 ? "" : (int) Math.floor(getTime(hopper) / 20.0))
isEnabled(hopper) ? EpicHoppers.getInstance().getLocale().getMessage("general.word.enabled").getMessage() .processPlaceholder("enabled", isEnabled(hopper) ?
: EpicHoppers.getInstance().getLocale().getMessage("general.word.disabled").getMessage()).getMessage().split("\\|"); this.plugin.getLocale().getMessage("general.word.enabled").getMessage() :
this.plugin.getLocale().getMessage("general.word.disabled").getMessage()
)
.getMessage()
.split("\\|");
for (String line : parts) { for (String line : parts) {
loreblock.add(TextUtils.formatText(line)); loreBlock.add(TextUtils.formatText(line));
} }
blockmeta.setLore(loreblock); blockmeta.setLore(loreBlock);
block.setItemMeta(blockmeta); block.setItemMeta(blockmeta);
return block; return block;
} }
@ -91,54 +101,65 @@ public class ModuleAutoSmelter extends Module {
public void runButtonPress(Player player, Hopper hopper, ClickType type) { public void runButtonPress(Player player, Hopper hopper, ClickType type) {
if (type == ClickType.LEFT) { if (type == ClickType.LEFT) {
hopper.setActivePlayer(player); hopper.setActivePlayer(player);
EpicHoppers.getInstance().getGuiManager().showGUI(player, new GUISmeltable(this, plugin, hopper)); this.plugin.getGuiManager().showGUI(player, new GUISmeltable(this, this.plugin, hopper));
} else if (type == ClickType.RIGHT) } else if (type == ClickType.RIGHT) {
toggleEnabled(hopper); toggleEnabled(hopper);
} }
}
@Override @Override
public List<Material> getBlockedItems(Hopper hopper) { public List<Material> getBlockedItems(Hopper hopper) {
if (getTime(hopper) == -9999) if (getTime(hopper) == -9999) {
return Collections.emptyList(); return Collections.emptyList();
}
List<Material> blockedItems = new ArrayList<>(); List<Material> blockedItems = new ArrayList<>();
for (CompatibleMaterial material : CompatibleMaterial.values()) for (CompatibleMaterial material : CompatibleMaterial.values()) {
if (material.getBurnResult() != null && isSmeltable(hopper, material)) if (material.getBurnResult() != null && isSmeltable(hopper, material)) {
blockedItems.add(material.getMaterial()); blockedItems.add(material.getMaterial());
}
}
return blockedItems; return blockedItems;
} }
@Override @Override
public String getDescription() { public String getDescription() {
return plugin.getLocale().getMessage("interface.hopper.autosmelt") return this.plugin.getLocale().getMessage("interface.hopper.autosmelt")
.processPlaceholder("ticks", (int) Math.floor(timeOut / 20.0)).getMessage(); .processPlaceholder("ticks", (int) Math.floor(this.timeOut / 20.0)).getMessage();
} }
private int getTime(Hopper hopper) { private int getTime(Hopper hopper) {
Object time = getData(hopper, "time"); Object time = getData(hopper, "time");
if (time == null) return -9999; if (time == null) {
return -9999;
}
return (int) time; return (int) time;
} }
private boolean isEnabled(Hopper hopper) { private boolean isEnabled(Hopper hopper) {
Object obj = getData(hopper, "time"); Object obj = getData(hopper, "time");
if (obj == null) return false; if (obj == null) {
return false;
}
return ((int) obj) != -9999; return ((int) obj) != -9999;
} }
public boolean isSmeltable(Hopper hopper, CompatibleMaterial material) { public boolean isSmeltable(Hopper hopper, CompatibleMaterial material) {
Object obj = getData(hopper, material.name()); Object obj = getData(hopper, material.name());
if (obj == null) return false; if (obj == null) {
return false;
}
return ((boolean) obj); return ((boolean) obj);
} }
private void toggleEnabled(Hopper hopper) { private void toggleEnabled(Hopper hopper) {
if (isEnabled(hopper)) if (isEnabled(hopper)) {
saveData(hopper, "time", -9999); saveData(hopper, "time", -9999);
else } else {
saveData(hopper, "time", timeOut); saveData(hopper, "time", this.timeOut);
}
} }
public void toggleSmeltable(Hopper hopper, CompatibleMaterial material) { public void toggleSmeltable(Hopper hopper, CompatibleMaterial material) {

View File

@ -25,10 +25,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream; import java.util.stream.Stream;
public class ModuleBlockBreak extends Module { public class ModuleBlockBreak extends Module {
private static final Map<Hopper, Boolean> CACHED_BLOCKS = new ConcurrentHashMap<>();
private final int ticksPerBreak; private final int ticksPerBreak;
private final Map<Hopper, Integer> blockTick = new HashMap<>(); private final Map<Hopper, Integer> blockTick = new HashMap<>();
private static final Map<Hopper, Boolean> cachedBlocks = new ConcurrentHashMap<>();
public ModuleBlockBreak(EpicHoppers plugin, int amount) { public ModuleBlockBreak(EpicHoppers plugin, int amount) {
super(plugin); super(plugin);
@ -42,47 +42,51 @@ public class ModuleBlockBreak extends Module {
@Override @Override
public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) {
if (!isEnabled(hopper)) {
if (!isEnabled(hopper))
return; return;
}
// don't try to break stuff if we can't grab stuff // don't try to break stuff if we can't grab stuff
// (for simplicity, just assume that no empty slots mean there's a good chance we won't be able to pick something new up) // (for simplicity, just assume that no empty slots mean there's a good chance we won't be able to pick something new up)
if (Stream.of(hopperCache.cachedInventory) if (Stream.of(hopperCache.cachedInventory).allMatch(item -> item != null && item.getAmount() > 0)) {
.allMatch(item -> item != null && item.getAmount() > 0))
return; return;
}
Integer tick = blockTick.get(hopper); Integer tick = this.blockTick.get(hopper);
if (tick == null) { if (tick == null) {
blockTick.put(hopper, 1); this.blockTick.put(hopper, 1);
return; return;
} else if (tick < ticksPerBreak) { } else if (tick < this.ticksPerBreak) {
blockTick.put(hopper, tick + 1); this.blockTick.put(hopper, tick + 1);
return; return;
} else { } else {
blockTick.put(hopper, 0); this.blockTick.put(hopper, 0);
} }
Block above = hopper.getLocation().getBlock().getRelative(0, 1, 0); Block above = hopper.getLocation().getBlock().getRelative(0, 1, 0);
// Don't break farm items from custom containers // Don't break farm items from custom containers
if (plugin.getContainerManager().getCustomContainer(above) != null) if (this.plugin.getContainerManager().getCustomContainer(above) != null) {
return; return;
}
// don't break blacklisted blocks, fluids, or containers // don't break blacklisted blocks, fluids, or containers
if (Settings.BLOCKBREAK_BLACKLIST.getStringList().contains(above.getType().name()) if (Settings.BLOCKBREAK_BLACKLIST.getStringList().contains(above.getType().name())
|| above.getType() == Material.WATER || above.getType() == Material.WATER
|| above.getType() == Material.LAVA || above.getType() == Material.LAVA
|| above.getType() == Material.AIR) || above.getType() == Material.AIR) {
return; return;
}
if (Settings.ALLOW_BLOCKBREAK_CONTAINERS.getBoolean() if (Settings.ALLOW_BLOCKBREAK_CONTAINERS.getBoolean()
&& above.getState() instanceof InventoryHolder) && above.getState() instanceof InventoryHolder) {
return; return;
}
// Let's break the block! // Let's break the block!
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) {
above.getWorld().playSound(above.getLocation(), Sound.BLOCK_STONE_BREAK, 1F, 1F); above.getWorld().playSound(above.getLocation(), Sound.BLOCK_STONE_BREAK, 1F, 1F);
}
Location locationAbove = above.getLocation(); Location locationAbove = above.getLocation();
locationAbove.add(.5, .5, .5); locationAbove.add(.5, .5, .5);
@ -106,35 +110,36 @@ public class ModuleBlockBreak extends Module {
} }
} }
boolean waterlogged = false; boolean waterlogged = ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)
&& above.getBlockData() instanceof org.bukkit.block.data.Waterlogged && above.getBlockData() instanceof org.bukkit.block.data.Waterlogged
&& ((org.bukkit.block.data.Waterlogged) above.getBlockData()).isWaterlogged()) { && ((org.bukkit.block.data.Waterlogged) above.getBlockData()).isWaterlogged();
waterlogged = true;
}
above.breakNaturally(new ItemStack(Material.DIAMOND_PICKAXE)); above.breakNaturally(new ItemStack(Material.DIAMOND_PICKAXE));
if (waterlogged) if (waterlogged) {
above.setType(Material.WATER); above.setType(Material.WATER);
} }
}
@Override @Override
public ItemStack getGUIButton(Hopper hopper) { public ItemStack getGUIButton(Hopper hopper) {
ItemStack block = new ItemStack(Material.IRON_ORE, 1); ItemStack block = new ItemStack(Material.IRON_ORE, 1);
ItemMeta blockmeta = block.getItemMeta(); ItemMeta blockMeta = block.getItemMeta();
blockmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.blocktitle").getMessage()); blockMeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.blocktitle").getMessage());
ArrayList<String> loreblock = new ArrayList<>(); ArrayList<String> loreBlock = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.hopper.blocklore") String[] parts = this.plugin.getLocale()
.getMessage("interface.hopper.blocklore")
.processPlaceholder("enabled", isEnabled(hopper) .processPlaceholder("enabled", isEnabled(hopper)
? plugin.getLocale().getMessage("general.word.enabled").getMessage() ? this.plugin.getLocale().getMessage("general.word.enabled").getMessage()
: plugin.getLocale().getMessage("general.word.disabled").getMessage()) : this.plugin.getLocale().getMessage("general.word.disabled").getMessage()
.getMessage().split("\\|"); )
.getMessage()
.split("\\|");
for (String line : parts) { for (String line : parts) {
loreblock.add(TextUtils.formatText(line)); loreBlock.add(TextUtils.formatText(line));
} }
blockmeta.setLore(loreblock); blockMeta.setLore(loreBlock);
block.setItemMeta(blockmeta); block.setItemMeta(blockMeta);
return block; return block;
} }
@ -150,26 +155,26 @@ public class ModuleBlockBreak extends Module {
@Override @Override
public String getDescription() { public String getDescription() {
return plugin.getLocale().getMessage("interface.hopper.blockbreak") return this.plugin.getLocale().getMessage("interface.hopper.blockbreak")
.processPlaceholder("ticks", ticksPerBreak).getMessage(); .processPlaceholder("ticks", this.ticksPerBreak).getMessage();
} }
@Override @Override
public void clearData(Hopper hopper) { public void clearData(Hopper hopper) {
super.clearData(hopper); super.clearData(hopper);
cachedBlocks.remove(hopper); CACHED_BLOCKS.remove(hopper);
} }
public void setEnabled(Hopper hopper, boolean enable) { public void setEnabled(Hopper hopper, boolean enable) {
saveData(hopper, "blockbreak", enable); saveData(hopper, "blockbreak", enable);
cachedBlocks.put(hopper, enable); CACHED_BLOCKS.put(hopper, enable);
} }
public boolean isEnabled(Hopper hopper) { public boolean isEnabled(Hopper hopper) {
Boolean enabled = cachedBlocks.get(hopper); Boolean enabled = CACHED_BLOCKS.get(hopper);
if (enabled == null) { if (enabled == null) {
Object isBlockBreaking = getData(hopper, "blockbreak"); Object isBlockBreaking = getData(hopper, "blockbreak");
cachedBlocks.put(hopper, enabled = isBlockBreaking != null && (boolean) isBlockBreaking); CACHED_BLOCKS.put(hopper, enabled = isBlockBreaking != null && (boolean) isBlockBreaking);
} }
return enabled; return enabled;
} }

View File

@ -20,7 +20,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class ModuleMobHopper extends Module { public class ModuleMobHopper extends Module {
private final int amount; private final int amount;
private final Map<Block, Integer> blockTick = new HashMap<>(); private final Map<Block, Integer> blockTick = new HashMap<>();
@ -39,41 +38,45 @@ public class ModuleMobHopper extends Module {
public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) {
Block block = hopper.getLocation().getBlock(); Block block = hopper.getLocation().getBlock();
if (!blockTick.containsKey(block)) { if (!this.blockTick.containsKey(block)) {
blockTick.put(block, 1); this.blockTick.put(block, 1);
return; return;
} }
int tick = blockTick.get(block); int tick = this.blockTick.get(block);
int put = tick + 1; int put = tick + 1;
blockTick.put(block, put); this.blockTick.put(block, put);
if (tick < amount || !isEnabled(hopper)) return; if (tick < this.amount || !isEnabled(hopper)) {
return;
}
hopper.getWorld().getNearbyEntities(hopper.getLocation(), 5, 5, 5).stream() hopper.getWorld().getNearbyEntities(hopper.getLocation(), 5, 5, 5).stream()
.filter(entity -> entity instanceof LivingEntity && !(entity instanceof Player) && .filter(entity -> entity instanceof LivingEntity && !(entity instanceof Player) &&
!(entity instanceof ArmorStand)).limit(1).forEach(entity -> { !(entity instanceof ArmorStand)).limit(1).forEach(entity -> {
Location location = hopper.getLocation().add(.5, 1, .5); Location location = hopper.getLocation().add(.5, 1, .5);
if (location.getBlock().getType() != Material.AIR) return; if (location.getBlock().getType() != Material.AIR) {
return;
}
entity.teleport(location); entity.teleport(location);
((LivingEntity) entity).damage(99999999); ((LivingEntity) entity).damage(99999999);
}); });
blockTick.remove(block); this.blockTick.remove(block);
} }
@Override @Override
public ItemStack getGUIButton(Hopper hopper) { public ItemStack getGUIButton(Hopper hopper) {
ItemStack block = new ItemStack(Material.ROTTEN_FLESH, 1); ItemStack block = new ItemStack(Material.ROTTEN_FLESH, 1);
ItemMeta blockmeta = block.getItemMeta(); ItemMeta blockMeta = block.getItemMeta();
blockmeta.setDisplayName(plugin.getLocale().getMessage("interface.hopper.mobtitle").getMessage()); blockMeta.setDisplayName(this.plugin.getLocale().getMessage("interface.hopper.mobtitle").getMessage());
ArrayList<String> loreblock = new ArrayList<>(); ArrayList<String> loreBlock = new ArrayList<>();
String[] parts = plugin.getLocale().getMessage("interface.hopper.moblore").processPlaceholder("enabled", String[] parts = this.plugin.getLocale().getMessage("interface.hopper.moblore").processPlaceholder("enabled",
isEnabled(hopper) ? EpicHoppers.getInstance().getLocale().getMessage("general.word.enabled").getMessage() isEnabled(hopper) ? this.plugin.getLocale().getMessage("general.word.enabled").getMessage()
: EpicHoppers.getInstance().getLocale().getMessage("general.word.disabled").getMessage()).getMessage().split("\\|"); : this.plugin.getLocale().getMessage("general.word.disabled").getMessage()).getMessage().split("\\|");
for (String line : parts) { for (String line : parts) {
loreblock.add(TextUtils.formatText(line)); loreBlock.add(TextUtils.formatText(line));
} }
blockmeta.setLore(loreblock); blockMeta.setLore(loreBlock);
block.setItemMeta(blockmeta); block.setItemMeta(blockMeta);
return block; return block;
} }
@ -89,8 +92,10 @@ public class ModuleMobHopper extends Module {
@Override @Override
public String getDescription() { public String getDescription() {
return plugin.getLocale().getMessage("interface.hopper.mobhopper") return this.plugin.getLocale()
.processPlaceholder("ticks", amount).getMessage(); .getMessage("interface.hopper.mobhopper")
.processPlaceholder("ticks", this.amount)
.getMessage();
} }
public boolean isEnabled(Hopper hopper) { public boolean isEnabled(Hopper hopper) {

View File

@ -31,14 +31,13 @@ import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class ModuleSuction extends Module { public class ModuleSuction extends Module {
private static final List<UUID> BLACKLIST = new ArrayList<>();
private static final boolean WILD_STACKER = Bukkit.getPluginManager().isPluginEnabled("WildStacker");
private static final boolean ULTIMATE_STACKER = Bukkit.getPluginManager().isPluginEnabled("UltimateStacker");
private final int maxSearchRadius; private final int maxSearchRadius;
private static List<UUID> blacklist = new ArrayList<>();
private static final boolean wildStacker = Bukkit.getPluginManager().isPluginEnabled("WildStacker");
private static final boolean ultimateStacker = Bukkit.getPluginManager().isPluginEnabled("UltimateStacker");
public ModuleSuction(EpicHoppers plugin, int amount) { public ModuleSuction(EpicHoppers plugin, int amount) {
super(plugin); super(plugin);
this.maxSearchRadius = amount; this.maxSearchRadius = amount;
@ -53,7 +52,9 @@ public class ModuleSuction extends Module {
public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) { public void run(Hopper hopper, StorageContainerCache.Cache hopperCache) {
double radius = getRadius(hopper) + .5; double radius = getRadius(hopper) + .5;
if (!isEnabled(hopper)) return; if (!isEnabled(hopper)) {
return;
}
Set<Item> itemsToSuck = hopper.getLocation().getWorld().getNearbyEntities(hopper.getLocation().add(0.5, 0.5, 0.5), radius, radius, radius) Set<Item> itemsToSuck = hopper.getLocation().getWorld().getNearbyEntities(hopper.getLocation().add(0.5, 0.5, 0.5), radius, radius, radius)
.stream() .stream()
@ -64,8 +65,9 @@ public class ModuleSuction extends Module {
.map(Item.class::cast) .map(Item.class::cast)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
if (itemsToSuck.isEmpty()) if (itemsToSuck.isEmpty()) {
return; return;
}
boolean filterEndpoint = hopper.getFilter().getEndPoint() != null; boolean filterEndpoint = hopper.getFilter().getEndPoint() != null;
@ -76,7 +78,6 @@ public class ModuleSuction extends Module {
} }
for (Item item : itemsToSuck) { for (Item item : itemsToSuck) {
ItemStack itemStack = item.getItemStack(); ItemStack itemStack = item.getItemStack();
if (item.getPickupDelay() == 0) { if (item.getPickupDelay() == 0) {
@ -84,21 +85,23 @@ public class ModuleSuction extends Module {
continue; continue;
} }
if (itemStack.getType().name().contains("SHULKER_BOX")) if (itemStack.getType().name().contains("SHULKER_BOX")) {
return; return;
}
if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName() && if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName() &&
itemStack.getItemMeta().getDisplayName().startsWith("***")) { itemStack.getItemMeta().getDisplayName().startsWith("***")) {
return; //Compatibility with Shop instance: https://www.spigotmc.org/resources/shop-a-simple-intuitive-shop-instance.9628/ return; //Compatibility with Shop instance: https://www.spigotmc.org/resources/shop-a-simple-intuitive-shop-instance.9628/
} }
if (blacklist.contains(item.getUniqueId())) if (BLACKLIST.contains(item.getUniqueId())) {
return; return;
}
// respect filter if no endpoint // respect filter if no endpoint
if (!filterEndpoint if (!filterEndpoint
&& !(hopper.getFilter().getWhiteList().isEmpty() && hopper.getFilter().getBlackList().isEmpty())) { && !(hopper.getFilter().getWhiteList().isEmpty() && hopper.getFilter().getBlackList().isEmpty())) {
// this hopper has a filter with no rejection endpoint, so don't absorb disalowed items // this hopper has a filter with no rejection endpoint, so don't absorb disallowed items
// whitelist has priority // whitelist has priority
if (!hopper.getFilter().getWhiteList().isEmpty()) { if (!hopper.getFilter().getWhiteList().isEmpty()) {
// is this item on the whitelist? // is this item on the whitelist?
@ -117,28 +120,30 @@ public class ModuleSuction extends Module {
if (Settings.EMIT_INVENTORYPICKUPITEMEVENT.getBoolean()) { if (Settings.EMIT_INVENTORYPICKUPITEMEVENT.getBoolean()) {
hopperInventory.setContents(hopperCache.cachedInventory); hopperInventory.setContents(hopperCache.cachedInventory);
InventoryPickupItemEvent pickupevent = new InventoryPickupItemEvent(hopperInventory, item); InventoryPickupItemEvent pickupEvent = new InventoryPickupItemEvent(hopperInventory, item);
Bukkit.getPluginManager().callEvent(pickupevent); Bukkit.getPluginManager().callEvent(pickupEvent);
if (pickupevent.isCancelled()) if (pickupEvent.isCancelled()) {
continue; continue;
} }
}
// try to add the items to the hopper // try to add the items to the hopper
int toAdd, added = hopperCache.addAny(itemStack, toAdd = getActualItemAmount(item)); int toAdd, added = hopperCache.addAny(itemStack, toAdd = getActualItemAmount(item));
if (added == 0) if (added == 0) {
return; return;
}
// items added ok! // items added ok!
if (added == toAdd) if (added == toAdd) {
item.remove(); item.remove();
else { } else {
// update the item's total // update the item's total
updateAmount(item, toAdd - added); updateAmount(item, toAdd - added);
// wait before trying to add again // wait before trying to add again
blacklist.add(item.getUniqueId()); BLACKLIST.add(item.getUniqueId());
Bukkit.getScheduler().runTaskLater(EpicHoppers.getInstance(), Bukkit.getScheduler().runTaskLater(this.plugin,
() -> blacklist.remove(item.getUniqueId()), 10L); () -> BLACKLIST.remove(item.getUniqueId()), 10L);
} }
float xx = (float) (0 + (Math.random() * .1)); float xx = (float) (0 + (Math.random() * .1));
@ -150,31 +155,33 @@ public class ModuleSuction extends Module {
} }
private int getActualItemAmount(Item item) { private int getActualItemAmount(Item item) {
if (ultimateStacker) { if (ULTIMATE_STACKER) {
return com.songoda.ultimatestacker.utils.Methods.getActualItemAmount(item); return UltimateStacker.getActualItemAmount(item);
} else if (wildStacker) } else if (WILD_STACKER) {
return WildStackerAPI.getItemAmount(item); return WildStackerAPI.getItemAmount(item);
else } else {
return item.getItemStack().getAmount(); return item.getItemStack().getAmount();
}
} }
private void updateAmount(Item item, int amount) { private void updateAmount(Item item, int amount) {
if (ultimateStacker) { if (ULTIMATE_STACKER) {
UltimateStacker.updateItemAmount(item, item.getItemStack(), amount); UltimateStacker.updateItemAmount(item, item.getItemStack(), amount);
} else if (wildStacker) } else if (WILD_STACKER) {
WildStackerAPI.getStackedItem(item).setStackAmount(amount, true); WildStackerAPI.getStackedItem(item).setStackAmount(amount, true);
else } else {
item.getItemStack().setAmount(Math.min(amount, item.getItemStack().getMaxStackSize())); item.getItemStack().setAmount(Math.min(amount, item.getItemStack().getMaxStackSize()));
} }
}
public static boolean isBlacklisted(UUID uuid) { public static boolean isBlacklisted(UUID uuid) {
return blacklist.contains(uuid); return BLACKLIST.contains(uuid);
} }
@Override @Override
public ItemStack getGUIButton(Hopper hopper) { public ItemStack getGUIButton(Hopper hopper) {
Locale locale = EpicHoppers.getInstance().getLocale(); Locale locale = this.plugin.getLocale();
ItemStack item = CompatibleMaterial.CAULDRON.getItem(); ItemStack item = CompatibleMaterial.CAULDRON.getItem();
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
meta.setDisplayName(locale.getMessage("interface.hopper.suctiontitle").getMessage()); meta.setDisplayName(locale.getMessage("interface.hopper.suctiontitle").getMessage());
@ -196,7 +203,7 @@ public class ModuleSuction extends Module {
toggleEnabled(hopper); toggleEnabled(hopper);
} else if (type == ClickType.RIGHT) { } else if (type == ClickType.RIGHT) {
int setRadius = getRadius(hopper); int setRadius = getRadius(hopper);
if (setRadius >= maxSearchRadius) { if (setRadius >= this.maxSearchRadius) {
setRadius(hopper, 1); setRadius(hopper, 1);
} else { } else {
setRadius(hopper, ++setRadius); setRadius(hopper, ++setRadius);
@ -216,7 +223,7 @@ public class ModuleSuction extends Module {
private int getRadius(Hopper hopper) { private int getRadius(Hopper hopper) {
Object foundRadius = getData(hopper, "radius"); Object foundRadius = getData(hopper, "radius");
return foundRadius == null ? maxSearchRadius : (int) foundRadius; return foundRadius == null ? this.maxSearchRadius : (int) foundRadius;
} }
private void setRadius(Hopper hopper, int radius) { private void setRadius(Hopper hopper, int radius) {
@ -230,7 +237,9 @@ public class ModuleSuction extends Module {
@Override @Override
public String getDescription() { public String getDescription() {
return EpicHoppers.getInstance().getLocale().getMessage("interface.hopper.suction") return this.plugin.getLocale()
.processPlaceholder("suction", maxSearchRadius).getMessage(); .getMessage("interface.hopper.suction")
.processPlaceholder("suction", this.maxSearchRadius)
.getMessage();
} }
} }

View File

@ -21,45 +21,49 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public class TeleportHandler { public class TeleportHandler {
private final Map<UUID, Long> lastTeleports = new HashMap<>(); private final Map<UUID, Long> lastTeleports = new HashMap<>();
private final EpicHoppers plugin; private final EpicHoppers plugin;
public TeleportHandler(EpicHoppers plugin) { public TeleportHandler(EpicHoppers plugin) {
this.plugin = plugin; this.plugin = plugin;
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this::teleportRunner, 0, Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this::teleportRunner, 0, Settings.TELEPORT_TICKS.getLong());
Settings.TELEPORT_TICKS.getLong());
} }
private void teleportRunner() { private void teleportRunner() {
if (!plugin.getHopperManager().isReady()) if (!this.plugin.getHopperManager().isReady()) {
return; return;
}
for (World world : Bukkit.getWorlds()) { for (World world : Bukkit.getWorlds()) {
for (Entity entity : world.getEntities()) { for (Entity entity : world.getEntities()) {
if (!(entity instanceof LivingEntity) || entity.getType() == EntityType.ARMOR_STAND) if (!(entity instanceof LivingEntity) || entity.getType() == EntityType.ARMOR_STAND) {
continue; continue;
}
if (!Settings.TELEPORT.getBoolean() if (!Settings.TELEPORT.getBoolean()
|| (entity instanceof Player && !entity.hasPermission("EpicHoppers.Teleport"))) || (entity instanceof Player && !entity.hasPermission("EpicHoppers.Teleport"))) {
continue; continue;
}
Location location = entity.getLocation().getBlock().getRelative(BlockFace.DOWN).getLocation(); Location location = entity.getLocation().getBlock().getRelative(BlockFace.DOWN).getLocation();
if (!this.plugin.getHopperManager().isHopper(location)) if (!this.plugin.getHopperManager().isHopper(location)) {
continue; continue;
}
Hopper hopper = this.plugin.getHopperManager().getHopper(location); Hopper hopper = this.plugin.getHopperManager().getHopper(location);
if (hopper.getTeleportTrigger() != TeleportTrigger.WALK_ON) if (hopper.getTeleportTrigger() != TeleportTrigger.WALK_ON) {
continue; continue;
}
if (this.lastTeleports.containsKey(entity.getUniqueId())) { if (this.lastTeleports.containsKey(entity.getUniqueId())) {
long duration = (new Date()).getTime() - new Date(this.lastTeleports.get(entity.getUniqueId())).getTime(); long duration = (new Date()).getTime() - new Date(this.lastTeleports.get(entity.getUniqueId())).getTime();
if (duration <= 5 * 1000) if (duration <= 5 * 1000) {
continue; continue;
} }
}
this.tpEntity(entity, hopper); this.tpEntity(entity, hopper);
this.lastTeleports.put(entity.getUniqueId(), System.currentTimeMillis()); this.lastTeleports.put(entity.getUniqueId(), System.currentTimeMillis());
@ -68,13 +72,15 @@ public class TeleportHandler {
} }
public void tpEntity(Entity entity, Hopper hopper) { public void tpEntity(Entity entity, Hopper hopper) {
if (hopper == null || !this.plugin.getHopperManager().isHopper(hopper.getLocation())) if (hopper == null || !this.plugin.getHopperManager().isHopper(hopper.getLocation())) {
return; return;
}
Hopper lastHopper = this.getChain(hopper, 1); Hopper lastHopper = this.getChain(hopper, 1);
if (!hopper.equals(lastHopper)) if (!hopper.equals(lastHopper)) {
this.doTeleport(entity, lastHopper.getLocation()); this.doTeleport(entity, lastHopper.getLocation());
} }
}
/** /**
* Recursively gets the next hopper in the linked hopper chain * Recursively gets the next hopper in the linked hopper chain
@ -84,16 +90,18 @@ public class TeleportHandler {
* @return The hopper at the end of the chain (or up to 15 in depth) * @return The hopper at the end of the chain (or up to 15 in depth)
*/ */
private Hopper getChain(Hopper lastHopper, int currentChainLength) { private Hopper getChain(Hopper lastHopper, int currentChainLength) {
if (currentChainLength > 15) if (currentChainLength > 15) {
return lastHopper; return lastHopper;
}
for (Location nextHopperLocation : lastHopper.getLinkedBlocks()) { for (Location nextHopperLocation : lastHopper.getLinkedBlocks()) {
if (nextHopperLocation.getBlock().getState() instanceof org.bukkit.block.Hopper) { if (nextHopperLocation.getBlock().getState() instanceof org.bukkit.block.Hopper) {
Hopper hopper = this.plugin.getHopperManager().getHopper(nextHopperLocation); Hopper hopper = this.plugin.getHopperManager().getHopper(nextHopperLocation);
if (hopper != null) if (hopper != null) {
return this.getChain(hopper, currentChainLength + 1); return this.getChain(hopper, currentChainLength + 1);
} }
} }
}
return lastHopper; return lastHopper;
} }

View File

@ -1,7 +1,5 @@
package com.songoda.epichoppers.hopper.teleport; package com.songoda.epichoppers.hopper.teleport;
public enum TeleportTrigger { public enum TeleportTrigger {
DISABLED, WALK_ON, SNEAK DISABLED, WALK_ON, SNEAK
} }

View File

@ -24,6 +24,8 @@ import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.permissions.PermissionAttachmentInfo;
import java.util.Objects;
/** /**
* Created by songoda on 3/14/2017. * Created by songoda on 3/14/2017.
*/ */
@ -40,63 +42,73 @@ public class BlockListeners implements Listener {
public void onBlockPlace(BlockPlaceEvent e) { public void onBlockPlace(BlockPlaceEvent e) {
Player player = e.getPlayer(); Player player = e.getPlayer();
if (e.getBlock().getType() != Material.HOPPER) if (e.getBlock().getType() != Material.HOPPER) {
return; return;
}
if (Settings.DISABLED_WORLDS.getStringList().contains(player.getWorld().getName())) if (Settings.DISABLED_WORLDS.getStringList().contains(player.getWorld().getName())) {
return; return;
}
int amt = count(e.getBlock().getChunk()); int amt = count(e.getBlock().getChunk());
int max = maxHoppers(player); int max = maxHoppers(player);
if (max != -1 && amt > max) { if (max != -1 && amt > max) {
player.sendMessage(plugin.getLocale().getMessage("event.hopper.toomany").processPlaceholder("amount", max).getMessage()); player.sendMessage(this.plugin.getLocale().getMessage("event.hopper.toomany").processPlaceholder("amount", max).getMessage());
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
ItemStack item = e.getItemInHand().clone(); ItemStack item = e.getItemInHand().clone();
if (Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !plugin.getLevelManager().isEpicHopper(item)) if (Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !this.plugin.getLevelManager().isEpicHopper(item)) {
return; return;
}
if (!plugin.getHopperManager().isReady()) { if (!this.plugin.getHopperManager().isReady()) {
player.sendMessage(plugin.getLocale().getMessage("event.hopper.notready").getMessage()); player.sendMessage(this.plugin.getLocale().getMessage("event.hopper.notready").getMessage());
e.setCancelled(true); e.setCancelled(true);
return; return;
} }
Hopper hopper = plugin.getHopperManager().addHopper( Hopper hopper = this.plugin.getHopperManager().addHopper(
new HopperBuilder(e.getBlock()) new HopperBuilder(e.getBlock())
.setLevel(plugin.getLevelManager().getLevel(item)) .setLevel(this.plugin.getLevelManager().getLevel(item))
.setPlacedBy(player) .setPlacedBy(player)
.setLastPlayerOpened(player).build()); .setLastPlayerOpened(player).build());
HopperPlaceEvent hopperPlaceEvent = new HopperPlaceEvent(player, hopper); HopperPlaceEvent hopperPlaceEvent = new HopperPlaceEvent(player, hopper);
Bukkit.getPluginManager().callEvent(hopperPlaceEvent); Bukkit.getPluginManager().callEvent(hopperPlaceEvent);
EpicHoppers.getInstance().getDataManager().createHopper(hopper); this.plugin.getDataManager().createHopper(hopper);
} }
private int maxHoppers(Player player) { private int maxHoppers(Player player) {
int limit = -1; int limit = -1;
for (PermissionAttachmentInfo permissionAttachmentInfo : player.getEffectivePermissions()) { for (PermissionAttachmentInfo permissionAttachmentInfo : player.getEffectivePermissions()) {
if (!permissionAttachmentInfo.getPermission().toLowerCase().startsWith("epichoppers.limit")) continue; if (!permissionAttachmentInfo.getPermission().toLowerCase().startsWith("epichoppers.limit")) {
continue;
}
int num = Integer.parseInt(permissionAttachmentInfo.getPermission().split("\\.")[2]); int num = Integer.parseInt(permissionAttachmentInfo.getPermission().split("\\.")[2]);
if (num > limit) if (num > limit) {
limit = num; limit = num;
} }
if (limit == -1) limit = Settings.MAX_CHUNK.getInt(); }
if (limit == -1) {
limit = Settings.MAX_CHUNK.getInt();
}
return limit; return limit;
} }
private int count(Chunk c) { private int count(Chunk chunk) {
int count = 0; int count = 0;
for (int x = 0; x < 16; x++) { for (int x = 0; x < 16; x++) {
for (int z = 0; z < 16; z++) { for (int z = 0; z < 16; z++) {
for (int y = getMinHeight(c.getWorld()); y < c.getWorld().getMaxHeight(); y++) { for (int y = getMinHeight(chunk.getWorld()); y < chunk.getWorld().getMaxHeight(); y++) {
if (c.getBlock(x, y, z).getType() == Material.HOPPER) count++; if (chunk.getBlock(x, y, z).getType() == Material.HOPPER) {
count++;
}
} }
} }
} }
@ -108,18 +120,21 @@ public class BlockListeners implements Listener {
Block block = event.getBlock(); Block block = event.getBlock();
Player player = event.getPlayer(); Player player = event.getPlayer();
if (event.getBlock().getType() != Material.HOPPER) return; if (event.getBlock().getType() != Material.HOPPER) {
return;
}
if (!plugin.getHopperManager().isReady()) { if (!this.plugin.getHopperManager().isReady()) {
player.sendMessage(plugin.getLocale().getMessage("event.hopper.notready").getMessage()); player.sendMessage(this.plugin.getLocale().getMessage("event.hopper.notready").getMessage());
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !plugin.getHopperManager().isHopper(block.getLocation())) if (Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !this.plugin.getHopperManager().isHopper(block.getLocation())) {
return; return;
}
Hopper hopper = plugin.getHopperManager().getHopper(block); Hopper hopper = this.plugin.getHopperManager().getHopper(block);
GUIFilter.compileOpenGuiFilter(hopper); GUIFilter.compileOpenGuiFilter(hopper);
GUIAutoSellFilter.compileOpenAutoSellFilter(hopper); GUIAutoSellFilter.compileOpenAutoSellFilter(hopper);
@ -131,7 +146,7 @@ public class BlockListeners implements Listener {
Bukkit.getPluginManager().callEvent(hopperBreakEvent); Bukkit.getPluginManager().callEvent(hopperBreakEvent);
event.setCancelled(true); event.setCancelled(true);
ItemStack item = plugin.newHopperItem(level); ItemStack item = this.plugin.newHopperItem(level);
hopper.dropItems(); hopper.dropItems();
@ -142,26 +157,26 @@ public class BlockListeners implements Listener {
hopper.forceClose(); hopper.forceClose();
hopper.getFilter().getWhiteList().stream() hopper.getFilter().getWhiteList().stream()
.filter(m -> m != null) .filter(Objects::nonNull)
.forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m)); .forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m));
hopper.getFilter().getBlackList().stream() hopper.getFilter().getBlackList().stream()
.filter(m -> m != null) .filter(Objects::nonNull)
.forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m)); .forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m));
hopper.getFilter().getVoidList().stream(). hopper.getFilter().getVoidList().stream().
filter(m -> m != null) filter(Objects::nonNull)
.forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m)); .forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m));
hopper.getFilter().getAutoSellWhiteList().stream() hopper.getFilter().getAutoSellWhiteList().stream()
.filter(m -> m != null) .filter(Objects::nonNull)
.forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m)); .forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m));
hopper.getFilter().getAutoSellBlackList().stream() hopper.getFilter().getAutoSellBlackList().stream()
.filter(m -> m != null) .filter(Objects::nonNull)
.forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m)); .forEach(m -> event.getBlock().getWorld().dropItemNaturally(event.getBlock().getLocation(), m));
plugin.getHopperManager().removeHopper(block.getLocation()); this.plugin.getHopperManager().removeHopper(block.getLocation());
plugin.getDataManager().deleteHopper(hopper); this.plugin.getDataManager().deleteHopper(hopper);
plugin.getPlayerDataManager().getPlayerData(player).setSyncType(null); this.plugin.getPlayerDataManager().getPlayerData(player).setSyncType(null);
} }
public int getMinHeight(World world) { public int getMinHeight(World world) {

View File

@ -7,10 +7,10 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerPickupItemEvent;
public class EntityListeners implements Listener { public class EntityListeners implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerPickup(PlayerPickupItemEvent event) { public void onPlayerPickup(PlayerPickupItemEvent event) {
if (ModuleSuction.isBlacklisted(event.getItem().getUniqueId())) if (ModuleSuction.isBlacklisted(event.getItem().getUniqueId())) {
event.setCancelled(true); event.setCancelled(true);
} }
}
} }

View File

@ -20,11 +20,7 @@ import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/**
* Created by songoda on 4/18/2017.
*/
public class HopperListeners implements Listener { public class HopperListeners implements Listener {
private final EpicHoppers plugin; private final EpicHoppers plugin;
public HopperListeners(EpicHoppers plugin) { public HopperListeners(EpicHoppers plugin) {
@ -40,15 +36,17 @@ public class HopperListeners implements Listener {
Location sourceLocation = source.getHolder() instanceof BlockState ? ((BlockState) source.getHolder()).getLocation() : null; Location sourceLocation = source.getHolder() instanceof BlockState ? ((BlockState) source.getHolder()).getLocation() : null;
Location destinationLocation = destination.getHolder() instanceof BlockState ? ((BlockState) destination.getHolder()).getLocation() : null; Location destinationLocation = destination.getHolder() instanceof BlockState ? ((BlockState) destination.getHolder()).getLocation() : null;
if (sourceLocation != null && Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !plugin.getHopperManager().isHopper(sourceLocation)) if (sourceLocation != null && Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !this.plugin.getHopperManager().isHopper(sourceLocation)) {
return; return;
}
// Hopper minecarts should be able to take care of themselves // Hopper minecarts should be able to take care of themselves
// Let EpicHoppers take over if the hopper is pointing down though // Let EpicHoppers take over if the hopper is pointing down though
if (destination.getHolder() instanceof HopperMinecart if (destination.getHolder() instanceof HopperMinecart
&& source.getHolder() instanceof org.bukkit.block.Hopper && source.getHolder() instanceof org.bukkit.block.Hopper
&& HopperDirection.getDirection(((org.bukkit.block.Hopper) source.getHolder()).getRawData()) != HopperDirection.DOWN) && HopperDirection.getDirection(((org.bukkit.block.Hopper) source.getHolder()).getRawData()) != HopperDirection.DOWN) {
return; return;
}
// Shulker boxes have a mind of their own and relentlessly steal items from hoppers // Shulker boxes have a mind of their own and relentlessly steal items from hoppers
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11) if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_11)
@ -66,14 +64,16 @@ public class HopperListeners implements Listener {
// Special cases when a hopper is picking up items // Special cases when a hopper is picking up items
if (destination.getHolder() instanceof org.bukkit.block.Hopper) { if (destination.getHolder() instanceof org.bukkit.block.Hopper) {
if (destinationLocation != null && Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !plugin.getHopperManager().isHopper(destinationLocation)) if (destinationLocation != null && Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !this.plugin.getHopperManager().isHopper(destinationLocation)) {
return; 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 Hopper and we don't need to iterate over default-valued hoppers
if (!plugin.getHopperManager().isHopper(destinationLocation)) if (!this.plugin.getHopperManager().isHopper(destinationLocation)) {
return; return;
}
Hopper toHopper = plugin.getHopperManager().getHopper(destinationLocation); Hopper 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 // 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(); final ItemStack toMove = event.getItem();
@ -153,11 +153,13 @@ public class HopperListeners implements Listener {
} }
} }
if (!(source.getHolder() instanceof org.bukkit.block.Hopper)) if (!(source.getHolder() instanceof org.bukkit.block.Hopper)) {
return; return;
}
if (destinationLocation == null) if (destinationLocation == null) {
return; return;
}
// Handle hopper push events elsewhere // Handle hopper push events elsewhere
event.setCancelled(true); event.setCancelled(true);

View File

@ -22,11 +22,7 @@ import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent; import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.InventoryHolder;
/**
* Created by songoda on 3/14/2017.
*/
public class InteractListeners implements Listener { public class InteractListeners implements Listener {
private final EpicHoppers plugin; private final EpicHoppers plugin;
public InteractListeners(EpicHoppers plugin) { public InteractListeners(EpicHoppers plugin) {
@ -36,17 +32,19 @@ public class InteractListeners implements Listener {
@EventHandler @EventHandler
public void onPlayerToggleSneakEvent(PlayerToggleSneakEvent event) { public void onPlayerToggleSneakEvent(PlayerToggleSneakEvent event) {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (player.isSneaking() && plugin.getHopperManager().isReady()) { if (player.isSneaking() && this.plugin.getHopperManager().isReady()) {
Location location = player.getLocation().getBlock().getRelative(BlockFace.SELF).getLocation(); Location location = player.getLocation().getBlock().getRelative(BlockFace.SELF).getLocation();
Location down = location.getBlock().getRelative(BlockFace.DOWN).getLocation(); Location down = location.getBlock().getRelative(BlockFace.DOWN).getLocation();
if (plugin.getHopperManager().isHopper(down)) { if (this.plugin.getHopperManager().isHopper(down)) {
Hopper hopper = plugin.getHopperManager().getHopper(down); Hopper hopper = this.plugin.getHopperManager().getHopper(down);
if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) {
plugin.getTeleportHandler().tpEntity(player, hopper); this.plugin.getTeleportHandler().tpEntity(player, hopper);
} else if (plugin.getHopperManager().isHopper(location)) { }
Hopper hopper = plugin.getHopperManager().getHopper(location); } else if (this.plugin.getHopperManager().isHopper(location)) {
if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) Hopper hopper = this.plugin.getHopperManager().getHopper(location);
plugin.getTeleportHandler().tpEntity(player, hopper); if (hopper.getTeleportTrigger() == TeleportTrigger.SNEAK) {
this.plugin.getTeleportHandler().tpEntity(player, hopper);
}
} }
} }
} }
@ -58,12 +56,12 @@ public class InteractListeners implements Listener {
|| event.getClickedBlock() == null || event.getClickedBlock() == null
|| player.isSneaking() || player.isSneaking()
|| !player.hasPermission("EpicHoppers.overview") || !player.hasPermission("EpicHoppers.overview")
|| !(event.getClickedBlock().getState() instanceof InventoryHolder || event.getClickedBlock().getType().equals(Material.ENDER_CHEST))) { || !(event.getClickedBlock().getState() instanceof InventoryHolder || event.getClickedBlock().getType() == Material.ENDER_CHEST)) {
return; return;
} }
if (Settings.USE_PROTECTION_PLUGINS.getBoolean() && ProtectionManager.canInteract(player, event.getClickedBlock().getLocation()) && WorldGuardHook.isInteractAllowed(event.getClickedBlock().getLocation())) { if (Settings.USE_PROTECTION_PLUGINS.getBoolean() && ProtectionManager.canInteract(player, event.getClickedBlock().getLocation()) && WorldGuardHook.isInteractAllowed(event.getClickedBlock().getLocation())) {
player.sendMessage(plugin.getLocale().getMessage("event.general.protected").getPrefixedMessage()); player.sendMessage(this.plugin.getLocale().getMessage("event.general.protected").getPrefixedMessage());
return; return;
} }
@ -71,26 +69,28 @@ public class InteractListeners implements Listener {
SkyBlock skyBlock = SkyBlock.getInstance(); SkyBlock skyBlock = SkyBlock.getInstance();
if (skyBlock.getWorldManager().isIslandWorld(event.getPlayer().getWorld()) && if (skyBlock.getWorldManager().isIslandWorld(event.getPlayer().getWorld()) &&
!skyBlock.getPermissionManager().hasPermission(event.getPlayer(), skyBlock.getIslandManager().getIslandAtLocation(event.getClickedBlock().getLocation()), "EpicHoppers")) !skyBlock.getPermissionManager().hasPermission(event.getPlayer(), skyBlock.getIslandManager().getIslandAtLocation(event.getClickedBlock().getLocation()), "EpicHoppers")) {
return; return;
} }
}
PlayerData playerData = plugin.getPlayerDataManager().getPlayerData(player); PlayerData playerData = this.plugin.getPlayerDataManager().getPlayerData(player);
if (playerData.getSyncType() == null) { if (playerData.getSyncType() == null) {
if (event.getClickedBlock().getType() == Material.HOPPER) { if (event.getClickedBlock().getType() == Material.HOPPER) {
if (!plugin.getHopperManager().isReady()) { if (!this.plugin.getHopperManager().isReady()) {
player.sendMessage(plugin.getLocale().getMessage("event.hopper.notready").getMessage()); player.sendMessage(this.plugin.getLocale().getMessage("event.hopper.notready").getMessage());
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
if (Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !plugin.getHopperManager().isHopper(event.getClickedBlock().getLocation())) if (Settings.ALLOW_NORMAL_HOPPERS.getBoolean() && !this.plugin.getHopperManager().isHopper(event.getClickedBlock().getLocation())) {
return; return;
}
Hopper hopper = plugin.getHopperManager().getHopper(event.getClickedBlock()); Hopper hopper = this.plugin.getHopperManager().getHopper(event.getClickedBlock());
if (!player.getInventory().getItemInHand().getType().name().contains("PICKAXE")) { if (!player.getInventory().getItemInHand().getType().name().contains("PICKAXE")) {
hopper.overview(plugin.getGuiManager(), player); hopper.overview(this.plugin.getGuiManager(), player);
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@ -98,15 +98,14 @@ public class InteractListeners implements Listener {
return; return;
} }
if (event.getClickedBlock().getState() instanceof InventoryHolder if (event.getClickedBlock().getState() instanceof InventoryHolder ||
|| (event.getClickedBlock().getType().equals(Material.ENDER_CHEST) (event.getClickedBlock().getType() == Material.ENDER_CHEST && Settings.ENDERCHESTS.getBoolean())) {
&& Settings.ENDERCHESTS.getBoolean())) {
Hopper hopper = playerData.getLastHopper(); Hopper hopper = playerData.getLastHopper();
if (event.getClickedBlock().getLocation().equals(playerData.getLastHopper().getLocation())) { if (event.getClickedBlock().getLocation().equals(playerData.getLastHopper().getLocation())) {
if (!hopper.getLinkedBlocks().isEmpty()) { if (!hopper.getLinkedBlocks().isEmpty()) {
plugin.getLocale().getMessage("event.hopper.syncfinish").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.hopper.syncfinish").sendPrefixedMessage(player);
} else { } else {
plugin.getLocale().getMessage("event.hopper.synccanceled").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.hopper.synccanceled").sendPrefixedMessage(player);
} }
hopper.cancelSync(player); hopper.cancelSync(player);
} else if (playerData.getSyncType() != null) { } else if (playerData.getSyncType() != null) {

View File

@ -8,27 +8,24 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
/**
* Created by songoda on 3/14/2017.
*/
public class InventoryListeners implements Listener { public class InventoryListeners implements Listener {
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
if (event.getCurrentItem() == null) return; if (event.getCurrentItem() == null ||
event.getRawSlot() > event.getView().getTopInventory().getSize() - 1 ||
!event.getCurrentItem().hasItemMeta()) {
return;
}
if (event.getSlot() == 64537 ||
event.getInventory().getType() != InventoryType.ANVIL ||
event.getAction() == InventoryAction.NOTHING ||
event.getCurrentItem().getType() == Material.AIR) {
return;
}
if (event.getRawSlot() > event.getView().getTopInventory().getSize() - 1) return;
if (!event.getCurrentItem().hasItemMeta()) return;
if (event.getSlot() != 64537
&& event.getInventory().getType() == InventoryType.ANVIL
&& event.getAction() != InventoryAction.NOTHING
&& event.getCurrentItem().getType() != Material.AIR) {
ItemStack item = event.getCurrentItem(); ItemStack item = event.getCurrentItem();
if (item.getType() == Material.HOPPER) { if (item.getType() == Material.HOPPER) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
}
} }

View File

@ -3,13 +3,11 @@ package com.songoda.epichoppers.player;
import com.songoda.epichoppers.hopper.Hopper; import com.songoda.epichoppers.hopper.Hopper;
public class PlayerData { public class PlayerData {
private Hopper lastHopper = null; private Hopper lastHopper = null;
private SyncType syncType = null; // Null means off. private SyncType syncType = null; // Null means off.
public Hopper getLastHopper() { public Hopper getLastHopper() {
return lastHopper; return this.lastHopper;
} }
public void setLastHopper(Hopper lastHopper) { public void setLastHopper(Hopper lastHopper) {
@ -17,7 +15,7 @@ public class PlayerData {
} }
public SyncType getSyncType() { public SyncType getSyncType() {
return syncType; return this.syncType;
} }
public void setSyncType(SyncType syncType) { public void setSyncType(SyncType syncType) {

View File

@ -9,11 +9,10 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public class PlayerDataManager { public class PlayerDataManager {
private final Map<UUID, PlayerData> registeredPlayers = new HashMap<>(); private final Map<UUID, PlayerData> registeredPlayers = new HashMap<>();
private PlayerData getPlayerData(UUID uuid) { private PlayerData getPlayerData(UUID uuid) {
return registeredPlayers.computeIfAbsent(uuid, u -> new PlayerData()); return this.registeredPlayers.computeIfAbsent(uuid, u -> new PlayerData());
} }
public PlayerData getPlayerData(Player player) { public PlayerData getPlayerData(Player player) {
@ -21,6 +20,6 @@ public class PlayerDataManager {
} }
public Collection<PlayerData> getRegisteredPlayers() { public Collection<PlayerData> getRegisteredPlayers() {
return Collections.unmodifiableCollection(registeredPlayers.values()); return Collections.unmodifiableCollection(this.registeredPlayers.values());
} }
} }

View File

@ -1,8 +1,6 @@
package com.songoda.epichoppers.player; package com.songoda.epichoppers.player;
public enum SyncType { public enum SyncType {
REGULAR, REGULAR,
FILTERED FILTERED
} }

View File

@ -10,148 +10,146 @@ import java.util.Arrays;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class Settings { public class Settings {
private static final Config CONFIG = EpicHoppers.getPlugin(EpicHoppers.class).getCoreConfig();
private static final Config config = EpicHoppers.getInstance().getCoreConfig(); public static final ConfigSetting HOPPER_UPGRADING = new ConfigSetting(CONFIG, "Main.Allow hopper Upgrading", true,
public static final ConfigSetting HOPPER_UPGRADING = new ConfigSetting(config, "Main.Allow hopper Upgrading", true,
"Should hoppers be upgradable?"); "Should hoppers be upgradable?");
public static final ConfigSetting UPGRADE_WITH_ECONOMY = new ConfigSetting(config, "Main.Upgrade With Economy", true, public static final ConfigSetting UPGRADE_WITH_ECONOMY = new ConfigSetting(CONFIG, "Main.Upgrade With Economy", true,
"Should you be able to upgrade hoppers with economy?"); "Should you be able to upgrade hoppers with economy?");
public static final ConfigSetting UPGRADE_WITH_XP = new ConfigSetting(config, "Main.Upgrade With XP", true, public static final ConfigSetting UPGRADE_WITH_XP = new ConfigSetting(CONFIG, "Main.Upgrade With XP", true,
"Should you be able to upgrade hoppers with experience?"); "Should you be able to upgrade hoppers with experience?");
public static final ConfigSetting ALLOW_NORMAL_HOPPERS = new ConfigSetting(config, "Main.Allow Normal Hoppers", false, public static final ConfigSetting ALLOW_NORMAL_HOPPERS = new ConfigSetting(CONFIG, "Main.Allow Normal Hoppers", false,
"Should natural hoppers not be epic hoppers?"); "Should natural hoppers not be epic hoppers?");
public static final ConfigSetting DISABLED_WORLDS = new ConfigSetting(config, "Main.Disabled Worlds", public static final ConfigSetting DISABLED_WORLDS = new ConfigSetting(CONFIG, "Main.Disabled Worlds",
Arrays.asList("example1", "example2"), Arrays.asList("example1", "example2"),
"Worlds where epic hoppers cannot be placed.", "Worlds where epic hoppers cannot be placed.",
"Any placed Epic Hopper will just be converted to a normal one."); "Any placed Epic Hopper will just be converted to a normal one.");
public static final ConfigSetting TELEPORT = new ConfigSetting(config, "Main.Allow Players To Teleport Through Hoppers", true, public static final ConfigSetting TELEPORT = new ConfigSetting(CONFIG, "Main.Allow Players To Teleport Through Hoppers", true,
"Should players be able to teleport through hoppers?"); "Should players be able to teleport through hoppers?");
public static final ConfigSetting ENDERCHESTS = new ConfigSetting(config, "Main.Support Enderchests", true, public static final ConfigSetting ENDERCHESTS = new ConfigSetting(CONFIG, "Main.Support Enderchests", true,
"Should hoppers dump items into a player enderchests?"); "Should hoppers dump items into a player enderchests?");
public static final ConfigSetting UPGRADE_PARTICLE_TYPE = new ConfigSetting(config, "Main.Upgrade Particle Type", "SPELL_WITCH", public static final ConfigSetting UPGRADE_PARTICLE_TYPE = new ConfigSetting(CONFIG, "Main.Upgrade Particle Type", "SPELL_WITCH",
"The type of particle shown when a hopper is upgraded."); "The type of particle shown when a hopper is upgraded.");
public static final ConfigSetting HOP_TICKS = new ConfigSetting(config, "Main.Amount of Ticks Between Hops", 8L, public static final ConfigSetting HOP_TICKS = new ConfigSetting(CONFIG, "Main.Amount of Ticks Between Hops", 8L,
"The amount of ticks between hopper transfers."); "The amount of ticks between hopper transfers.");
public static final ConfigSetting AUTOSAVE = new ConfigSetting(config, "Main.Auto Save Interval In Seconds", 15, public static final ConfigSetting AUTOSAVE = new ConfigSetting(CONFIG, "Main.Auto Save Interval In Seconds", 15,
"The amount of time in between saving to file.", "The amount of time in between saving to file.",
"This is purely a safety function to prevent against unplanned crashes or", "This is purely a safety function to prevent against unplanned crashes or",
"restarts. With that said it is advised to keep this enabled.", "restarts. With that said it is advised to keep this enabled.",
"If however you enjoy living on the edge, feel free to turn it off."); "If however you enjoy living on the edge, feel free to turn it off.");
public static final ConfigSetting TELEPORT_TICKS = new ConfigSetting(config, "Main.Amount of Ticks Between Teleport", 10L, public static final ConfigSetting TELEPORT_TICKS = new ConfigSetting(CONFIG, "Main.Amount of Ticks Between Teleport", 10L,
"The cooldown between teleports. It prevents players", "The cooldown between teleports. It prevents players",
"from getting stuck in a teleport loop."); "from getting stuck in a teleport loop.");
public static final ConfigSetting LINK_TIMEOUT = new ConfigSetting(config, "Main.Timeout When Syncing Hoppers", 300L, public static final ConfigSetting LINK_TIMEOUT = new ConfigSetting(CONFIG, "Main.Timeout When Syncing Hoppers", 300L,
"The amount of time in ticks a player has between hitting the hopper", "The amount of time in ticks a player has between hitting the hopper",
"Link button and performing the link. When the time is up the link event is canceled."); "Link button and performing the link. When the time is up the link event is canceled.");
public static final ConfigSetting MAX_CHUNK = new ConfigSetting(config, "Main.Max Hoppers Per Chunk", -1, public static final ConfigSetting MAX_CHUNK = new ConfigSetting(CONFIG, "Main.Max Hoppers Per Chunk", -1,
"The maximum amount of hoppers per chunk."); "The maximum amount of hoppers per chunk.");
public static final ConfigSetting USE_PROTECTION_PLUGINS = new ConfigSetting(config, "Main.Use Protection Plugins", true, public static final ConfigSetting USE_PROTECTION_PLUGINS = new ConfigSetting(CONFIG, "Main.Use Protection Plugins", true,
"Should we use protection plugins?"); "Should we use protection plugins?");
public static final ConfigSetting BLOCKBREAK_PARTICLE = new ConfigSetting(config, "Main.BlockBreak Particle Type", "LAVA", public static final ConfigSetting BLOCKBREAK_PARTICLE = new ConfigSetting(CONFIG, "Main.BlockBreak Particle Type", "LAVA",
"The particle shown when the block break module performs a block break."); "The particle shown when the block break module performs a block break.");
public static final ConfigSetting BLOCKBREAK_BLACKLIST = new ConfigSetting(config, "Main.BlockBreak Blacklisted Blocks", public static final ConfigSetting BLOCKBREAK_BLACKLIST = new ConfigSetting(CONFIG, "Main.BlockBreak Blacklisted Blocks",
Arrays.asList("BEDROCK", "END_PORTAL", "ENDER_PORTAL", "END_PORTAL_FRAME", "ENDER_PORTAL_FRAME", "PISTON_HEAD", "PISTON_EXTENSION", "RAIL", "RAILS", "ACTIVATOR_RAIL", "DETECTOR_RAIL", "POWERED_RAIL"), Arrays.asList("BEDROCK", "END_PORTAL", "ENDER_PORTAL", "END_PORTAL_FRAME", "ENDER_PORTAL_FRAME", "PISTON_HEAD", "PISTON_EXTENSION", "RAIL", "RAILS", "ACTIVATOR_RAIL", "DETECTOR_RAIL", "POWERED_RAIL"),
"Anything listed here will not be broken by the block break module."); "Anything listed here will not be broken by the block break module.");
public static final ConfigSetting ALLOW_BLOCKBREAK_CONTAINERS = new ConfigSetting(config, "Main.Allow BlockBreak Containers", false, public static final ConfigSetting ALLOW_BLOCKBREAK_CONTAINERS = new ConfigSetting(CONFIG, "Main.Allow BlockBreak Containers", false,
"Allow BlockBreak to break containers."); "Allow BlockBreak to break containers.");
public static final ConfigSetting AUTOCRAFT_JAM_EJECT = new ConfigSetting(config, "Main.AutoCraft Jam Eject", false, public static final ConfigSetting AUTOCRAFT_JAM_EJECT = new ConfigSetting(CONFIG, "Main.AutoCraft Jam Eject", false,
"AutoCraft module needs a free slot to craft items with.", "AutoCraft module needs a free slot to craft items with.",
"Normally, crafting hoppers won't grab items that would fill that slot.", "Normally, crafting hoppers won't grab items that would fill that slot.",
"This option ejects items if that last slot is forcibly filled"); "This option ejects items if that last slot is forcibly filled");
public static final ConfigSetting AUTOCRAFT_BLACKLIST = new ConfigSetting(config, "Main.AutoCraft Blacklist", Arrays.asList("BEDROCK", "EGG"), public static final ConfigSetting AUTOCRAFT_BLACKLIST = new ConfigSetting(CONFIG, "Main.AutoCraft Blacklist", Arrays.asList("BEDROCK", "EGG"),
"Anything listed here will not be able to be auto crafted."); "Anything listed here will not be able to be auto crafted.");
public static final ConfigSetting AUTOSELL_PRICES = new ConfigSetting(config, "Main.AutoSell Prices", public static final ConfigSetting AUTOSELL_PRICES = new ConfigSetting(CONFIG, "Main.AutoSell Prices",
Arrays.asList("STONE,0.50", "COBBLESTONE,0.20", "IRON_ORE,0.35", "COAL_ORE,0.20"), Arrays.asList("STONE,0.50", "COBBLESTONE,0.20", "IRON_ORE,0.35", "COAL_ORE,0.20"),
"These are the prices used by the auto sell module."); "These are the prices used by the auto sell module.");
public static final ConfigSetting AUTOSELL_SHOPGUIPLUS = new ConfigSetting(config, "Main.Use ShopGuiPlus for Prices", false, public static final ConfigSetting AUTOSELL_SHOPGUIPLUS = new ConfigSetting(CONFIG, "Main.Use ShopGuiPlus for Prices", false,
"Should prices be grabbed from ShopGuiPlus?", "Should prices be grabbed from ShopGuiPlus?",
"If ShopGuiPlus is not enabled or the player is offline the default price list will be used (or EconomyShopGUI if enabled).", "If ShopGuiPlus is not enabled or the player is offline the default price list will be used (or EconomyShopGUI if enabled).",
"If this is something that you do not want then you should empty the default list."); "If this is something that you do not want then you should empty the default list.");
public static final ConfigSetting AUTOSELL_ECONOMY_SHOP_GUI = new ConfigSetting(config, "Main.Use EconomyShopGUI for Prices", false, public static final ConfigSetting AUTOSELL_ECONOMY_SHOP_GUI = new ConfigSetting(CONFIG, "Main.Use EconomyShopGUI for Prices", false,
"Should prices be grabbed from EconomyShopGUI?", "Should prices be grabbed from EconomyShopGUI?",
"If 'Use ShopGuiPlus for Prices' is enabled and the player is online, this will be ignored."); "If 'Use ShopGuiPlus for Prices' is enabled and the player is online, this will be ignored.");
public static final ConfigSetting ECONOMY_PLUGIN = new ConfigSetting(config, "Main.Economy", EconomyManager.getEconomy() == null ? "Vault" : EconomyManager.getEconomy().getName(), public static final ConfigSetting ECONOMY_PLUGIN = new ConfigSetting(CONFIG, "Main.Economy", EconomyManager.getEconomy() == null ? "Vault" : EconomyManager.getEconomy().getName(),
"Which economy plugin should be used?", "Which economy plugin should be used?",
"Supported plugins you have installed: \"" + EconomyManager.getManager().getRegisteredPlugins().stream().collect(Collectors.joining("\", \"")) + "\"."); "Supported plugins you have installed: \"" + EconomyManager.getManager().getRegisteredPlugins().stream().collect(Collectors.joining("\", \"")) + "\".");
public static final ConfigSetting EMIT_INVENTORYPICKUPITEMEVENT = new ConfigSetting(config, "Main.Emit InventoryPickupItemEvent", false, public static final ConfigSetting EMIT_INVENTORYPICKUPITEMEVENT = new ConfigSetting(CONFIG, "Main.Emit InventoryPickupItemEvent", false,
"This event is used by other plugin to modify or monitor the behavior when a hopper picks up items on the ground.", "This event is used by other plugin to modify or monitor the behavior when a hopper picks up items on the ground.",
"However it is a high frequency event and may have an impact on your server performance which is why it is disabled by default.", "However it is a high frequency event and may have an impact on your server performance which is why it is disabled by default.",
"If you absolutely need this enable it but be aware of the potential performance impact."); "If you absolutely need this enable it but be aware of the potential performance impact.");
public static final ConfigSetting ECO_ICON = new ConfigSetting(config, "Interfaces.Economy Icon", "SUNFLOWER"); public static final ConfigSetting ECO_ICON = new ConfigSetting(CONFIG, "Interfaces.Economy Icon", "SUNFLOWER");
public static final ConfigSetting XP_ICON = new ConfigSetting(config, "Interfaces.XP Icon", "EXPERIENCE_BOTTLE"); public static final ConfigSetting XP_ICON = new ConfigSetting(CONFIG, "Interfaces.XP Icon", "EXPERIENCE_BOTTLE");
public static final ConfigSetting GLASS_TYPE_1 = new ConfigSetting(config, "Interfaces.Glass Type 1", "GRAY_STAINED_GLASS_PANE"); public static final ConfigSetting GLASS_TYPE_1 = new ConfigSetting(CONFIG, "Interfaces.Glass Type 1", "GRAY_STAINED_GLASS_PANE");
public static final ConfigSetting GLASS_TYPE_2 = new ConfigSetting(config, "Interfaces.Glass Type 2", "BLUE_STAINED_GLASS_PANE"); public static final ConfigSetting GLASS_TYPE_2 = new ConfigSetting(CONFIG, "Interfaces.Glass Type 2", "BLUE_STAINED_GLASS_PANE");
public static final ConfigSetting GLASS_TYPE_3 = new ConfigSetting(config, "Interfaces.Glass Type 3", "LIGHT_BLUE_STAINED_GLASS_PANE"); public static final ConfigSetting GLASS_TYPE_3 = new ConfigSetting(CONFIG, "Interfaces.Glass Type 3", "LIGHT_BLUE_STAINED_GLASS_PANE");
public static final ConfigSetting LANGUGE_MODE = new ConfigSetting(config, "System.Language Mode", "en_US", public static final ConfigSetting LANGUGE_MODE = new ConfigSetting(CONFIG, "System.Language Mode", "en_US",
"The enabled language file.", "The enabled language file.",
"More language files (if available) can be found in the plugins data folder."); "More language files (if available) can be found in the plugins data folder.");
public static final ConfigSetting MYSQL_ENABLED = new ConfigSetting(config, "MySQL.Enabled", false, "Set to 'true' to use MySQL instead of SQLite for data storage."); public static final ConfigSetting MYSQL_ENABLED = new ConfigSetting(CONFIG, "MySQL.Enabled", false, "Set to 'true' to use MySQL instead of SQLite for data storage.");
public static final ConfigSetting MYSQL_HOSTNAME = new ConfigSetting(config, "MySQL.Hostname", "localhost"); public static final ConfigSetting MYSQL_HOSTNAME = new ConfigSetting(CONFIG, "MySQL.Hostname", "localhost");
public static final ConfigSetting MYSQL_PORT = new ConfigSetting(config, "MySQL.Port", 3306); public static final ConfigSetting MYSQL_PORT = new ConfigSetting(CONFIG, "MySQL.Port", 3306);
public static final ConfigSetting MYSQL_DATABASE = new ConfigSetting(config, "MySQL.Database", "your-database"); public static final ConfigSetting MYSQL_DATABASE = new ConfigSetting(CONFIG, "MySQL.Database", "your-database");
public static final ConfigSetting MYSQL_USERNAME = new ConfigSetting(config, "MySQL.Username", "user"); public static final ConfigSetting MYSQL_USERNAME = new ConfigSetting(CONFIG, "MySQL.Username", "user");
public static final ConfigSetting MYSQL_PASSWORD = new ConfigSetting(config, "MySQL.Password", "pass"); public static final ConfigSetting MYSQL_PASSWORD = new ConfigSetting(CONFIG, "MySQL.Password", "pass");
public static final ConfigSetting MYSQL_USE_SSL = new ConfigSetting(config, "MySQL.Use SSL", false); public static final ConfigSetting MYSQL_USE_SSL = new ConfigSetting(CONFIG, "MySQL.Use SSL", false);
public static final ConfigSetting MYSQL_POOL_SIZE = new ConfigSetting(config, "MySQL.Pool Size", 3, "Determines the number of connections the pool is using. Increase this value if you are getting timeout errors when more players online."); public static final ConfigSetting MYSQL_POOL_SIZE = new ConfigSetting(CONFIG, "MySQL.Pool Size", 3, "Determines the number of connections the pool is using. Increase this value if you are getting timeout errors when more players online.");
/** /**
* In order to set dynamic economy comment correctly, this needs to be * In order to set dynamic economy comment correctly, this needs to be
* called after EconomyManager load * called after EconomyManager load
*/ */
public static void setupConfig() { public static void setupConfig() {
config.load(); CONFIG.load();
config.setAutoremove(true).setAutosave(true); CONFIG.setAutoremove(true).setAutosave(true);
// convert glass pane settings // convert glass pane settings
int color; int color;
if ((color = GLASS_TYPE_1.getInt(-1)) != -1) { if ((color = GLASS_TYPE_1.getInt(-1)) != -1) {
config.set(GLASS_TYPE_1.getKey(), CompatibleMaterial.getGlassPaneColor(color).name()); CONFIG.set(GLASS_TYPE_1.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
} }
if ((color = GLASS_TYPE_2.getInt(-1)) != -1) { if ((color = GLASS_TYPE_2.getInt(-1)) != -1) {
config.set(GLASS_TYPE_2.getKey(), CompatibleMaterial.getGlassPaneColor(color).name()); CONFIG.set(GLASS_TYPE_2.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
} }
if ((color = GLASS_TYPE_3.getInt(-1)) != -1) { if ((color = GLASS_TYPE_3.getInt(-1)) != -1) {
config.set(GLASS_TYPE_3.getKey(), CompatibleMaterial.getGlassPaneColor(color).name()); CONFIG.set(GLASS_TYPE_3.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
} }
// convert economy settings // convert economy settings
if (config.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) { if (CONFIG.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) {
config.set("Main.Economy", "Vault"); CONFIG.set("Main.Economy", "Vault");
} else if (config.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) { } else if (CONFIG.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) {
config.set("Main.Economy", "Reserve"); CONFIG.set("Main.Economy", "Reserve");
} else if (config.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("PlayerPoints")) { } else if (CONFIG.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("PlayerPoints")) {
config.set("Main.Economy", "PlayerPoints"); CONFIG.set("Main.Economy", "PlayerPoints");
} }
config.saveChanges(); CONFIG.saveChanges();
} }
} }

View File

@ -33,13 +33,8 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
/**
* Created by songoda on 3/14/2017.
*/
public class HopTask extends BukkitRunnable { public class HopTask extends BukkitRunnable {
private final EpicHoppers plugin;
// Hop to the bop to the be bop top.
private EpicHoppers plugin;
private final int hopTicks; private final int hopTicks;
public HopTask(EpicHoppers plugin) { public HopTask(EpicHoppers plugin) {
@ -50,22 +45,24 @@ public class HopTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
for (final com.songoda.epichoppers.hopper.Hopper hopper : plugin.getHopperManager().getHoppers().values()) { for (final com.songoda.epichoppers.hopper.Hopper hopper : this.plugin.getHopperManager().getHoppers().values()) {
try { try {
// Get this hoppers location. // Get this hopper's location.
Location location = hopper.getLocation(); Location location = hopper.getLocation();
// Skip if chunk is not loaded. // Skip if chunk is not loaded.
if (location.getWorld() == null || !location.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) if (location.getWorld() == null || !location.getWorld().isChunkLoaded(location.getBlockX() >> 4, location.getBlockZ() >> 4)) {
continue; continue;
}
// Get Hopper Block. // Get Hopper Block.
Block block = location.getBlock(); Block block = location.getBlock();
// If block is not a hopper continue. // If block is not a hopper continue.
if (block.getType() != Material.HOPPER) if (block.getType() != Material.HOPPER) {
continue; continue;
}
// If hopper block is powered, update its redstone state and continue. // If hopper block is powered, update its redstone state and continue.
if (block.getBlockPower() > 0) { if (block.getBlockPower() > 0) {
@ -73,11 +70,12 @@ public class HopTask extends BukkitRunnable {
continue; continue;
} }
if (!hopper.tryTick(this.hopTicks, true)) if (!hopper.tryTick(this.hopTicks, true)) {
continue; continue;
}
// Amount to be moved. // Amount to be moved.
BoostData boostData = plugin.getBoostManager().getBoost(hopper.getPlacedBy()); BoostData boostData = this.plugin.getBoostManager().getBoost(hopper.getPlacedBy());
int maxToMove = hopper.getLevel().getAmount() * (boostData == null ? 1 : boostData.getMultiplier()); int maxToMove = hopper.getLevel().getAmount() * (boostData == null ? 1 : boostData.getMultiplier());
// Get hopper state data. // Get hopper state data.
@ -99,8 +97,9 @@ public class HopTask extends BukkitRunnable {
// Add banned materials to list. // Add banned materials to list.
List<Material> materials = module.getBlockedItems(hopper); List<Material> materials = module.getBlockedItems(hopper);
if (materials != null && !materials.isEmpty()) if (materials != null && !materials.isEmpty()) {
blockedMaterials.addAll(materials); blockedMaterials.addAll(materials);
}
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
@ -124,16 +123,18 @@ public class HopTask extends BukkitRunnable {
|| (hopperCache.cacheChanged[i] && item.getAmount() - hopperCache.cacheAdded[i] < maxToMove) || (hopperCache.cacheChanged[i] && item.getAmount() - hopperCache.cacheAdded[i] < maxToMove)
// skip if blocked or voidlisted // skip if blocked or voidlisted
|| blockedMaterials.contains(item.getType()) || blockedMaterials.contains(item.getType())
|| hopper.getFilter().getVoidList().stream().anyMatch(itemStack -> Methods.isSimilarMaterial(itemStack, item))) || hopper.getFilter().getVoidList().stream().anyMatch(itemStack -> Methods.isSimilarMaterial(itemStack, item))) {
continue; continue;
}
doProcess = true; doProcess = true;
break; break;
} }
if (!doProcess) if (!doProcess) {
continue; continue;
}
CustomContainer container = plugin.getContainerManager().getCustomContainer(pointingLocation.getBlock()); CustomContainer container = this.plugin.getContainerManager().getCustomContainer(pointingLocation.getBlock());
if (container != null) { if (container != null) {
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
final ItemStack item = hopperCache.cachedInventory[i]; final ItemStack item = hopperCache.cachedInventory[i];
@ -165,22 +166,26 @@ public class HopTask extends BukkitRunnable {
} }
private void debt(ItemStack item, int amountToMove, InventoryHolder currentHolder) { private void debt(ItemStack item, int amountToMove, InventoryHolder currentHolder) {
if (item.getAmount() - amountToMove > 0) if (item.getAmount() - amountToMove > 0) {
item.setAmount(item.getAmount() - amountToMove); item.setAmount(item.getAmount() - amountToMove);
else } else {
currentHolder.getInventory().removeItem(item); currentHolder.getInventory().removeItem(item);
} }
}
private StorageContainerCache.Cache getFilterEndpoint(com.songoda.epichoppers.hopper.Hopper hopper) { private StorageContainerCache.Cache getFilterEndpoint(com.songoda.epichoppers.hopper.Hopper hopper) {
// Get endpoint location. // Get endpoint location.
Location endPoint = hopper.getFilter().getEndPoint(); Location endPoint = hopper.getFilter().getEndPoint();
// Check for null. // Check for null.
if (endPoint == null) return null; if (endPoint == null) {
return null;
}
// Make sure chunk is loaded. // Make sure chunk is loaded.
if (!endPoint.getWorld().isChunkLoaded(endPoint.getBlockX() >> 4, endPoint.getBlockZ() >> 4)) if (!endPoint.getWorld().isChunkLoaded(endPoint.getBlockX() >> 4, endPoint.getBlockZ() >> 4)) {
return null; return null;
}
// Fetch Cache // Fetch Cache
StorageContainerCache.Cache cache = StorageContainerCache.getCachedInventory(endPoint.getBlock()); StorageContainerCache.Cache cache = StorageContainerCache.getCachedInventory(endPoint.getBlock());
@ -202,7 +207,7 @@ public class HopTask extends BukkitRunnable {
Collection<Entity> nearbyEntities = null; Collection<Entity> nearbyEntities = null;
StorageContainerCache.Cache aboveCache = null; StorageContainerCache.Cache aboveCache = null;
CustomContainer container = plugin.getContainerManager().getCustomContainer(above); CustomContainer container = this.plugin.getContainerManager().getCustomContainer(above);
if ((container != null) if ((container != null)
|| (above.getType() != Material.AIR) || (above.getType() != Material.AIR)
&& (above.getType() != Material.HOPPER || HopperDirection.getDirection(above.getState().getRawData()) != HopperDirection.DOWN) && (above.getType() != Material.HOPPER || HopperDirection.getDirection(above.getState().getRawData()) != HopperDirection.DOWN)
@ -223,8 +228,9 @@ public class HopTask extends BukkitRunnable {
pullableSlots = IntStream.rangeClosed(0, contents.length - 1).toArray(); pullableSlots = IntStream.rangeClosed(0, contents.length - 1).toArray();
} else { } else {
if ((aboveInvHolder = this.getRandomInventoryHolderFromEntities(nearbyEntities)) == null if ((aboveInvHolder = this.getRandomInventoryHolderFromEntities(nearbyEntities)) == null
|| ((Minecart) aboveInvHolder).getLocation().getBlockY() + 1 == above.getY()) || ((Minecart) aboveInvHolder).getLocation().getBlockY() + 1 == above.getY()) {
return; return;
}
if (aboveInvHolder instanceof StorageMinecart) { if (aboveInvHolder instanceof StorageMinecart) {
pullableSlots = IntStream.rangeClosed(0, 26).toArray(); pullableSlots = IntStream.rangeClosed(0, 26).toArray();
} else { } else {
@ -243,13 +249,15 @@ public class HopTask extends BukkitRunnable {
final ItemStack toMove = contents[i]; final ItemStack toMove = contents[i];
// If item is invalid, try the next slot. // If item is invalid, try the next slot.
if (toMove == null || toMove.getAmount() == 0) if (toMove == null || toMove.getAmount() == 0) {
continue; continue;
}
// if we're not moving the item that we're trying to craft, we need to verify that we're not trying to fill the last slot // if we're not moving the item that we're trying to craft, we need to verify that we're not trying to fill the last slot
// (filling every slot leaves no room for the crafter to function) // (filling every slot leaves no room for the crafter to function)
if (toCraft != null && !Methods.isSimilarMaterial(toMove, toCraft) && !Methods.canMoveReserved(hopperCache.cachedInventory, toMove)) if (toCraft != null && !Methods.isSimilarMaterial(toMove, toCraft) && !Methods.canMoveReserved(hopperCache.cachedInventory, toMove)) {
continue; continue;
}
// respect whitelist/blacklist filters // respect whitelist/blacklist filters
if (toHopper.getFilter().getEndPoint() == null if (toHopper.getFilter().getEndPoint() == null
@ -285,9 +293,9 @@ public class HopTask extends BukkitRunnable {
if (aboveCache != null) { if (aboveCache != null) {
aboveCache.removeItems(itemToMove); aboveCache.removeItems(itemToMove);
} else { } else {
if (container != null) if (container != null) {
container.removeFromContainer(itemToMove, amountToMove); container.removeFromContainer(itemToMove, amountToMove);
else { } else {
this.debt(itemToMove, amountToMove, aboveInvHolder); this.debt(itemToMove, amountToMove, aboveInvHolder);
} }
} }
@ -309,9 +317,7 @@ public class HopTask extends BukkitRunnable {
// Add container that the hopper is attached to physically. // Add container that the hopper is attached to physically.
final Location pointingLocation = hopper.getLocation().add(hopperDirection.getX(), hopperDirection.getY(), hopperDirection.getZ()); final Location pointingLocation = hopper.getLocation().add(hopperDirection.getX(), hopperDirection.getY(), hopperDirection.getZ());
if (!linkedContainers.contains(pointingLocation) if (!linkedContainers.contains(pointingLocation)
&& pointingLocation.getWorld().isChunkLoaded( && pointingLocation.getWorld().isChunkLoaded(pointingLocation.getBlockX() >> 4, pointingLocation.getBlockZ() >> 4)) {
pointingLocation.getBlockX() >> 4,
pointingLocation.getBlockZ() >> 4)) {
switch (pointingLocation.getBlock().getType().name()) { switch (pointingLocation.getBlock().getType().name()) {
case "AIR": case "AIR":
case "RAILS": case "RAILS":
@ -330,8 +336,9 @@ public class HopTask extends BukkitRunnable {
for (Location targetLocation : linkedContainers) { for (Location targetLocation : linkedContainers) {
// Don't check if it's not in a loaded chunk // Don't check if it's not in a loaded chunk
if (!targetLocation.getWorld().isChunkLoaded(targetLocation.getBlockX() >> 4, targetLocation.getBlockZ() >> 4)) if (!targetLocation.getWorld().isChunkLoaded(targetLocation.getBlockX() >> 4, targetLocation.getBlockZ() >> 4)) {
continue; continue;
}
// special case for ender chests // special case for ender chests
final Block targetBlock = targetLocation.getBlock(); final Block targetBlock = targetLocation.getBlock();
@ -343,8 +350,9 @@ public class HopTask extends BukkitRunnable {
StorageContainerCache.Cache cache = new StorageContainerCache.Cache(targetBlock.getType(), destinationInventory.getContents()); StorageContainerCache.Cache cache = new StorageContainerCache.Cache(targetBlock.getType(), destinationInventory.getContents());
if (tryPush(hopper, hopperCache, cache, filterCache, maxToMove, blockedMaterials)) { if (tryPush(hopper, hopperCache, cache, filterCache, maxToMove, blockedMaterials)) {
// update inventory and exit // update inventory and exit
if (cache.isDirty()) if (cache.isDirty()) {
destinationInventory.setContents(cache.cachedInventory); destinationInventory.setContents(cache.cachedInventory);
}
return; return;
} }
} }
@ -352,7 +360,7 @@ public class HopTask extends BukkitRunnable {
continue; continue;
} }
CustomContainer container = plugin.getContainerManager().getCustomContainer(targetLocation.getBlock()); CustomContainer container = this.plugin.getContainerManager().getCustomContainer(targetLocation.getBlock());
if (container != null && tryPushCustomContainer(hopper, hopperCache, container, filterCache, maxToMove, blockedMaterials)) { if (container != null && tryPushCustomContainer(hopper, hopperCache, container, filterCache, maxToMove, blockedMaterials)) {
return; return;
} }
@ -366,9 +374,10 @@ public class HopTask extends BukkitRunnable {
} }
// Now attempt to push items into this container and exit on success // Now attempt to push items into this container and exit on success
if (tryPush(hopper, hopperCache, targetCache, filterCache, maxToMove, blockedMaterials)) if (tryPush(hopper, hopperCache, targetCache, filterCache, maxToMove, blockedMaterials)) {
return; return;
} }
}
// if we've gotten this far, check if we can push into a minecart // if we've gotten this far, check if we can push into a minecart
if (checkForMinecarts) { if (checkForMinecarts) {
@ -377,8 +386,9 @@ public class HopTask extends BukkitRunnable {
.map(InventoryHolder.class::cast).collect(Collectors.toSet())) { .map(InventoryHolder.class::cast).collect(Collectors.toSet())) {
StorageContainerCache.Cache cache = new StorageContainerCache.Cache(Material.CHEST, minecartInventory.getInventory().getContents()); StorageContainerCache.Cache cache = new StorageContainerCache.Cache(Material.CHEST, minecartInventory.getInventory().getContents());
if (tryPush(hopper, hopperCache, cache, filterCache, maxToMove, blockedMaterials)) { if (tryPush(hopper, hopperCache, cache, filterCache, maxToMove, blockedMaterials)) {
if (cache.isDirty()) if (cache.isDirty()) {
minecartInventory.getInventory().setContents(cache.cachedInventory); minecartInventory.getInventory().setContents(cache.cachedInventory);
}
return; return;
} }
} }
@ -401,8 +411,9 @@ public class HopTask extends BukkitRunnable {
|| (hopperCache.cacheChanged[i] && item.getAmount() - hopperCache.cacheAdded[i] < maxToMove) || (hopperCache.cacheChanged[i] && item.getAmount() - hopperCache.cacheAdded[i] < maxToMove)
// skip if blocked or voidlisted // skip if blocked or voidlisted
|| blockedMaterials.contains(item.getType()) || blockedMaterials.contains(item.getType())
|| hopper.getFilter().getVoidList().stream().anyMatch(itemStack -> Methods.isSimilarMaterial(itemStack, item))) || hopper.getFilter().getVoidList().stream().anyMatch(itemStack -> Methods.isSimilarMaterial(itemStack, item))) {
continue; continue;
}
// Create item that will be moved. // Create item that will be moved.
ItemStack itemToMove = item.clone(); ItemStack itemToMove = item.clone();
@ -449,8 +460,9 @@ public class HopTask extends BukkitRunnable {
|| (hopperCache.cacheChanged[i] && item.getAmount() - hopperCache.cacheAdded[i] < maxToMove) || (hopperCache.cacheChanged[i] && item.getAmount() - hopperCache.cacheAdded[i] < maxToMove)
// skip if blocked or voidlisted // skip if blocked or voidlisted
|| blockedMaterials.contains(item.getType()) || blockedMaterials.contains(item.getType())
|| hopper.getFilter().getVoidList().stream().anyMatch(itemStack -> Methods.isSimilarMaterial(itemStack, item))) || hopper.getFilter().getVoidList().stream().anyMatch(itemStack -> Methods.isSimilarMaterial(itemStack, item))) {
continue; continue;
}
// Create item that will be moved. // Create item that will be moved.
ItemStack itemToMove = item.clone(); ItemStack itemToMove = item.clone();
@ -506,8 +518,9 @@ public class HopTask extends BukkitRunnable {
* @return A set of valid pullable slots * @return A set of valid pullable slots
*/ */
private int[] getPullableSlots(Material material, int contentsLength) { private int[] getPullableSlots(Material material, int contentsLength) {
if (material.name().contains("SHULKER_BOX")) if (material.name().contains("SHULKER_BOX")) {
return IntStream.rangeClosed(0, 26).toArray(); return IntStream.rangeClosed(0, 26).toArray();
}
switch (material.name()) { switch (material.name()) {
case "BARREL": case "BARREL":
@ -542,10 +555,12 @@ public class HopTask extends BukkitRunnable {
List<InventoryHolder> inventoryHolders = new ArrayList<>(); List<InventoryHolder> inventoryHolders = new ArrayList<>();
entities.stream().filter(e -> e.getType() == EntityType.MINECART_CHEST || e.getType() == EntityType.MINECART_HOPPER) entities.stream().filter(e -> e.getType() == EntityType.MINECART_CHEST || e.getType() == EntityType.MINECART_HOPPER)
.forEach(e -> inventoryHolders.add((InventoryHolder) e)); .forEach(e -> inventoryHolders.add((InventoryHolder) e));
if (inventoryHolders.isEmpty()) if (inventoryHolders.isEmpty()) {
return null; return null;
if (inventoryHolders.size() == 1) }
if (inventoryHolders.size() == 1) {
return inventoryHolders.get(0); return inventoryHolders.get(0);
}
return inventoryHolders.get(ThreadLocalRandom.current().nextInt(inventoryHolders.size())); return inventoryHolders.get(ThreadLocalRandom.current().nextInt(inventoryHolders.size()));
} }
} }

View File

@ -1,7 +1,5 @@
package com.songoda.epichoppers.utils; package com.songoda.epichoppers.utils;
public enum CostType { public enum CostType {
ECONOMY, EXPERIENCE ECONOMY, EXPERIENCE
} }

View File

@ -4,7 +4,6 @@ import org.bukkit.Location;
import org.bukkit.block.BlockFace; import org.bukkit.block.BlockFace;
public enum HopperDirection { public enum HopperDirection {
DOWN(0, 8, 0, -1, 0), DOWN(0, 8, 0, -1, 0),
NORTH(2, 10, 0, 0, -1), NORTH(2, 10, 0, 0, -1),
SOUTH(3, 11, 0, 0, 1), SOUTH(3, 11, 0, 0, 1),
@ -28,9 +27,11 @@ public enum HopperDirection {
} }
public static HopperDirection getDirection(int value) { public static HopperDirection getDirection(int value) {
for (HopperDirection hopperDirection : HopperDirection.values()) for (HopperDirection hopperDirection : HopperDirection.values()) {
if (hopperDirection.getPowered() == value || hopperDirection.getUnpowered() == value) if (hopperDirection.getPowered() == value || hopperDirection.getUnpowered() == value) {
return hopperDirection; return hopperDirection;
}
}
return null; return null;
} }
@ -54,22 +55,22 @@ public enum HopperDirection {
} }
public int getX() { public int getX() {
return x; return this.x;
} }
public int getY() { public int getY() {
return y; return this.y;
} }
public int getZ() { public int getZ() {
return z; return this.z;
} }
public int getUnpowered() { public int getUnpowered() {
return unpowered; return this.unpowered;
} }
public int getPowered() { public int getPowered() {
return powered; return this.powered;
} }
} }

View File

@ -10,14 +10,7 @@ import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;
/**
* Created by songoda on 2/24/2017.
*/
public class Methods { public class Methods {
public static boolean isSimilarMaterial(ItemStack is1, ItemStack is2) { public static boolean isSimilarMaterial(ItemStack is1, ItemStack is2) {
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) || if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) ||
is1.getDurability() == Short.MAX_VALUE || is2.getDurability() == Short.MAX_VALUE) { is1.getDurability() == Short.MAX_VALUE || is2.getDurability() == Short.MAX_VALUE) {
@ -29,7 +22,9 @@ public class Methods {
} }
public static boolean canMove(Inventory inventory, ItemStack item) { public static boolean canMove(Inventory inventory, ItemStack item) {
if (inventory.firstEmpty() != -1) return true; if (inventory.firstEmpty() != -1) {
return true;
}
final ItemMeta itemMeta = item.getItemMeta(); final ItemMeta itemMeta = item.getItemMeta();
for (ItemStack stack : inventory) { for (ItemStack stack : inventory) {
@ -44,7 +39,9 @@ public class Methods {
} }
public static boolean canMoveReserved(Inventory inventory, ItemStack item) { public static boolean canMoveReserved(Inventory inventory, ItemStack item) {
if (inventory.firstEmpty() != inventory.getSize() - 1) return true; if (inventory.firstEmpty() != inventory.getSize() - 1) {
return true;
}
final ItemMeta itemMeta = item.getItemMeta(); final ItemMeta itemMeta = item.getItemMeta();
final ItemStack[] contents = inventory.getContents(); final ItemStack[] contents = inventory.getContents();
@ -64,8 +61,9 @@ public class Methods {
final ItemMeta itemMeta = item.getItemMeta(); final ItemMeta itemMeta = item.getItemMeta();
for (int i = 0; i < contents.length - 2; i++) { for (int i = 0; i < contents.length - 2; i++) {
final ItemStack stack = contents[i]; final ItemStack stack = contents[i];
if (stack == null || stack.getAmount() == 0) if (stack == null || stack.getAmount() == 0) {
return true; return true;
}
final ItemMeta stackMeta; final ItemMeta stackMeta;
if (isSimilarMaterial(stack, item) && (stack.getAmount() + item.getAmount()) < stack.getMaxStackSize() if (isSimilarMaterial(stack, item) && (stack.getAmount() + item.getAmount()) < stack.getMaxStackSize()
&& ((itemMeta == null) == ((stackMeta = stack.getItemMeta()) == null)) && ((itemMeta == null) == ((stackMeta = stack.getItemMeta()) == null))
@ -77,23 +75,24 @@ public class Methods {
} }
public static String formatName(int level) { public static String formatName(int level) {
EpicHoppers instance = EpicHoppers.getInstance(); EpicHoppers instance = EpicHoppers.getPlugin(EpicHoppers.class);
String name = instance.getLocale().getMessage("general.nametag.nameformat") String name = instance.getLocale()
.processPlaceholder("level", level).getMessage(); .getMessage("general.nametag.nameformat")
.processPlaceholder("level", level)
.getMessage();
return TextUtils.formatText(name); return TextUtils.formatText(name);
} }
public static void doParticles(Entity entity, Location location) { public static void doParticles(Entity entity, Location location) {
EpicHoppers instance = EpicHoppers.getInstance(); EpicHoppers instance = EpicHoppers.getPlugin(EpicHoppers.class);
location.setX(location.getX() + .5); location.setX(location.getX() + .5);
location.setY(location.getY() + .5); location.setY(location.getY() + .5);
location.setZ(location.getZ() + .5); location.setZ(location.getZ() + .5);
entity.getWorld().spawnParticle(org.bukkit.Particle.valueOf(instance.getConfig().getString("Main.Upgrade Particle Type")), location, 200, .5, .5, .5); entity.getWorld().spawnParticle(org.bukkit.Particle.valueOf(instance.getConfig().getString("Main.Upgrade Particle Type")), location, 200, .5, .5, .5);
} }
/** /**
* Serializes the location specified. * Serializes the location specified.
* *
@ -101,8 +100,9 @@ public class Methods {
* @return The serialized data. * @return The serialized data.
*/ */
public static String serializeLocation(Location location) { public static String serializeLocation(Location location) {
if (location == null || location.getWorld() == null) if (location == null || location.getWorld() == null) {
return ""; return "";
}
String w = location.getWorld().getName(); String w = location.getWorld().getName();
double x = location.getX(); double x = location.getX();
double y = location.getY(); double y = location.getY();
@ -111,84 +111,4 @@ public class Methods {
str = str.replace(".0", "").replace(".", "/"); str = str.replace(".0", "").replace(".", "/");
return str; return str;
} }
/**
* Makes the specified Unix Epoch time human readable as per the format settings in the Arconix config.
*
* @param time The time to convert.
* @return A human readable string representing to specified time.
*/
public static String makeReadable(Long time) {
if (time == null)
return "";
StringBuilder sb = new StringBuilder();
long days = TimeUnit.MILLISECONDS.toDays(time);
long hours = TimeUnit.MILLISECONDS.toHours(time) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(time));
long minutes = TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time));
long seconds = TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time));
if (days != 0L)
sb.append(" ").append(days).append("d");
if (hours != 0L)
sb.append(" ").append(hours).append("h");
if (minutes != 0L)
sb.append(" ").append(minutes).append("m");
if (seconds != 0L)
sb.append(" ").append(seconds).append("s");
return sb.toString().trim();
}
public static long parseTime(String input) {
long result = 0;
StringBuilder number = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isDigit(c)) {
number.append(c);
} else if (Character.isLetter(c) && (number.length() > 0)) {
result += convert(Integer.parseInt(number.toString()), c);
number = new StringBuilder();
}
}
return result;
}
private static long convert(long value, char unit) {
switch (unit) {
case 'd':
return value * 1000 * 60 * 60 * 24;
case 'h':
return value * 1000 * 60 * 60;
case 'm':
return value * 1000 * 60;
case 's':
return value * 1000;
default:
return 0;
}
}
/**
* Formats the specified double into the Economy format specified in the Arconix config.
*
* @param amt The double to format.
* @return The economy formatted double.
*/
public static String formatEconomy(double amt) {
DecimalFormat formatter = new DecimalFormat(amt == Math.ceil(amt) ? "#,###" : "#,###.00");
return formatter.format(amt);
}
public static boolean isInt(String number) {
if (number == null || number.equals(""))
return false;
try {
Integer.parseInt(number);
} catch (NumberFormatException e) {
return false;
}
return true;
}
} }

View File

@ -21,25 +21,24 @@ import java.util.Map;
* containers in large batches * containers in large batches
*/ */
public class StorageContainerCache { public class StorageContainerCache {
private static final Map<Block, Cache> INVENTORY_CACHE = new HashMap<>();
private static final Map<Block, Cache> inventoryCache = new HashMap<>();
// need to get the topmost inventory for a double chest, and save as that block // need to get the topmost inventory for a double chest, and save as that block
public static Cache getCachedInventory(Block b) { public static Cache getCachedInventory(Block block) {
Cache cache = inventoryCache.get(b); Cache cache = INVENTORY_CACHE.get(block);
if (cache == null) { if (cache == null) {
Material type = b.getType(); Material type = block.getType();
if (type == Material.CHEST || type == Material.TRAPPED_CHEST) { if (type == Material.CHEST || type == Material.TRAPPED_CHEST) {
Block b2 = findAdjacentDoubleChest(b); Block b2 = findAdjacentDoubleChest(block);
//System.out.println("Adjacent to " + b + " = " + b2); //System.out.println("Adjacent to " + block + " = " + b2);
if (b2 != null && (cache = inventoryCache.get(b2)) != null) { if (b2 != null && (cache = INVENTORY_CACHE.get(b2)) != null) {
return cache; return cache;
} }
} }
BlockState blockState = b.getState(); BlockState blockState = block.getState();
if (blockState instanceof InventoryHolder) { if (blockState instanceof InventoryHolder) {
//System.out.println("Load " + b.getLocation()); //System.out.println("Load " + block.getLocation());
inventoryCache.put(b, cache = new Cache(b, ((InventoryHolder) blockState).getInventory().getContents())); INVENTORY_CACHE.put(block, cache = new Cache(block, ((InventoryHolder) blockState).getInventory().getContents()));
} }
} }
return cache; return cache;
@ -47,30 +46,27 @@ public class StorageContainerCache {
/** /**
* Look for a double chest adjacent to a chest * Look for a double chest adjacent to a chest
*
* @param block
* @return
*/ */
public static Block findAdjacentDoubleChest(Block block) { public static Block findAdjacentDoubleChest(Block block) {
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) { if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) {
final BlockData d = block.getBlockData(); final BlockData blockData = block.getBlockData();
if (d instanceof Chest) { if (blockData instanceof Chest) {
final Chest c = (Chest) d; final Chest chest = (Chest) blockData;
if (c.getType() != Chest.Type.SINGLE) { if (chest.getType() != Chest.Type.SINGLE) {
// this is a double chest - check the other chest for registration data // this is a double chest - check the other chest for registration data
Block other = null; Block other = null;
switch (c.getFacing()) { switch (chest.getFacing()) {
case SOUTH: case SOUTH:
other = block.getRelative(c.getType() != Chest.Type.RIGHT ? BlockFace.WEST : BlockFace.EAST); other = block.getRelative(chest.getType() != Chest.Type.RIGHT ? BlockFace.WEST : BlockFace.EAST);
break; break;
case NORTH: case NORTH:
other = block.getRelative(c.getType() != Chest.Type.RIGHT ? BlockFace.EAST : BlockFace.WEST); other = block.getRelative(chest.getType() != Chest.Type.RIGHT ? BlockFace.EAST : BlockFace.WEST);
break; break;
case EAST: case EAST:
other = block.getRelative(c.getType() != Chest.Type.RIGHT ? BlockFace.SOUTH : BlockFace.NORTH); other = block.getRelative(chest.getType() != Chest.Type.RIGHT ? BlockFace.SOUTH : BlockFace.NORTH);
break; break;
case WEST: case WEST:
other = block.getRelative(c.getType() != Chest.Type.RIGHT ? BlockFace.NORTH : BlockFace.SOUTH); other = block.getRelative(chest.getType() != Chest.Type.RIGHT ? BlockFace.NORTH : BlockFace.SOUTH);
break; break;
default: default:
break; break;
@ -84,7 +80,7 @@ public class StorageContainerCache {
} else { } else {
// legacy check // legacy check
Material material = block.getType(); Material material = block.getType();
BlockFace[] faces = new BlockFace[] {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}; BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST};
for (BlockFace face : faces) { for (BlockFace face : faces) {
Block adjacentBlock = block.getRelative(face); Block adjacentBlock = block.getRelative(face);
@ -97,7 +93,7 @@ public class StorageContainerCache {
} }
public static void update() { public static void update() {
inventoryCache.entrySet().stream() INVENTORY_CACHE.entrySet().stream()
.filter(e -> e.getValue().dirty) .filter(e -> e.getValue().dirty)
.forEach(e -> { .forEach(e -> {
//System.out.println("Update " + e.getKey().getLocation()); //System.out.println("Update " + e.getKey().getLocation());
@ -115,11 +111,10 @@ public class StorageContainerCache {
NmsManager.getWorld().updateAdjacentComparators(e.getKey()); NmsManager.getWorld().updateAdjacentComparators(e.getKey());
}); });
inventoryCache.clear(); INVENTORY_CACHE.clear();
} }
public static class Cache { public static class Cache {
public final Material type; public final Material type;
public final Block block; public final Block block;
public ItemStack[] cachedInventory; public ItemStack[] cachedInventory;
@ -135,9 +130,9 @@ public class StorageContainerCache {
this.cacheAdded = new int[cachedInventory.length]; this.cacheAdded = new int[cachedInventory.length];
} }
public Cache(Block b, ItemStack[] cachedInventory) { public Cache(Block block, ItemStack[] cachedInventory) {
this.block = b; this.block = block;
this.type = b.getType(); this.type = block.getType();
this.cachedInventory = cachedInventory; this.cachedInventory = cachedInventory;
this.cacheChanged = new boolean[cachedInventory.length]; this.cacheChanged = new boolean[cachedInventory.length];
this.cacheAdded = new int[cachedInventory.length]; this.cacheAdded = new int[cachedInventory.length];
@ -152,50 +147,50 @@ public class StorageContainerCache {
} }
public void setContents(ItemStack[] items) { public void setContents(ItemStack[] items) {
if (cachedInventory == null || items.length == cachedInventory.length) { if (this.cachedInventory == null || items.length == this.cachedInventory.length) {
cachedInventory = items; this.cachedInventory = items;
for (int i = 0; i < cachedInventory.length; i++) { for (int i = 0; i < this.cachedInventory.length; i++) {
cacheChanged[i] = true; this.cacheChanged[i] = true;
} }
dirty = true; this.dirty = true;
} }
} }
public void setItem(int item, ItemStack itemStack) { public void setItem(int item, ItemStack itemStack) {
if (cachedInventory != null) { if (this.cachedInventory != null) {
cachedInventory[item] = itemStack; this.cachedInventory[item] = itemStack;
cacheChanged[item] = true; this.cacheChanged[item] = true;
dirty = true; this.dirty = true;
} }
} }
public void removeItem(int item) { public void removeItem(int item) {
if (cachedInventory != null) { if (this.cachedInventory != null) {
cachedInventory[item] = null; this.cachedInventory[item] = null;
cacheChanged[item] = true; this.cacheChanged[item] = true;
dirty = true; this.dirty = true;
} }
} }
public void removeItems(ItemStack item) { public void removeItems(ItemStack item) {
if (cachedInventory != null && item != null) { if (this.cachedInventory != null && item != null) {
int toRemove = item.getAmount(); int toRemove = item.getAmount();
for (int i = 0; toRemove > 0 && i < cachedInventory.length; i++) { for (int i = 0; toRemove > 0 && i < this.cachedInventory.length; i++) {
final ItemStack cacheItem = cachedInventory[i]; final ItemStack cacheItem = this.cachedInventory[i];
if (cacheItem != null && cacheItem.getAmount() != 0 && item.isSimilar(cacheItem)) { if (cacheItem != null && cacheItem.getAmount() != 0 && item.isSimilar(cacheItem)) {
int have = cacheItem.getAmount(); int have = cacheItem.getAmount();
if (have > toRemove) { if (have > toRemove) {
cachedInventory[i].setAmount(have - toRemove); this.cachedInventory[i].setAmount(have - toRemove);
cacheChanged[i] = true; this.cacheChanged[i] = true;
toRemove = 0; toRemove = 0;
} else { } else {
cachedInventory[i] = null; this.cachedInventory[i] = null;
cacheChanged[i] = true; this.cacheChanged[i] = true;
toRemove -= have; toRemove -= have;
} }
} }
} }
dirty = dirty | (toRemove != item.getAmount()); this.dirty = this.dirty | (toRemove != item.getAmount());
} }
} }
@ -207,37 +202,37 @@ public class StorageContainerCache {
* @return how many items were added * @return how many items were added
*/ */
public int addAny(ItemStack item, int amountToAdd) { public int addAny(ItemStack item, int amountToAdd) {
// Don't transfer shulker boxes into other shulker boxes, that's a bad idea. // Don't transfer shulker boxes into other shulker boxes, that's a bad idea.
if (type.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) if (this.type.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) {
return 0; return 0;
}
int totalAdded = 0; int totalAdded = 0;
if (cachedInventory != null && item != null) { if (this.cachedInventory != null && item != null) {
final int maxStack = item.getMaxStackSize(); final int maxStack = item.getMaxStackSize();
for (int i = 0; amountToAdd > 0 && i < cachedInventory.length; i++) { for (int i = 0; amountToAdd > 0 && i < this.cachedInventory.length; i++) {
final ItemStack cacheItem = cachedInventory[i]; final ItemStack cacheItem = this.cachedInventory[i];
if (cacheItem == null || cacheItem.getAmount() == 0) { if (cacheItem == null || cacheItem.getAmount() == 0) {
// free slot! // free slot!
int toAdd = Math.min(maxStack, amountToAdd); int toAdd = Math.min(maxStack, amountToAdd);
cachedInventory[i] = item.clone(); this.cachedInventory[i] = item.clone();
cachedInventory[i].setAmount(toAdd); this.cachedInventory[i].setAmount(toAdd);
cacheChanged[i] = true; this.cacheChanged[i] = true;
cacheAdded[i] = toAdd; this.cacheAdded[i] = toAdd;
totalAdded += toAdd; totalAdded += toAdd;
amountToAdd -= toAdd; amountToAdd -= toAdd;
} else if (maxStack > cacheItem.getAmount() && item.isSimilar(cacheItem)) { } else if (maxStack > cacheItem.getAmount() && item.isSimilar(cacheItem)) {
// free space! // free space!
int toAdd = Math.min(maxStack - cacheItem.getAmount(), amountToAdd); int toAdd = Math.min(maxStack - cacheItem.getAmount(), amountToAdd);
cachedInventory[i].setAmount(toAdd + cacheItem.getAmount()); this.cachedInventory[i].setAmount(toAdd + cacheItem.getAmount());
cacheChanged[i] = true; this.cacheChanged[i] = true;
cacheAdded[i] += toAdd; this.cacheAdded[i] += toAdd;
totalAdded += toAdd; totalAdded += toAdd;
amountToAdd -= toAdd; amountToAdd -= toAdd;
} }
} }
if (totalAdded != 0) { if (totalAdded != 0) {
dirty = true; this.dirty = true;
} }
} }
return totalAdded; return totalAdded;
@ -250,12 +245,14 @@ public class StorageContainerCache {
* @return true if the item was added * @return true if the item was added
*/ */
public boolean addItem(ItemStack item) { public boolean addItem(ItemStack item) {
if (cachedInventory == null || item == null || item.getAmount() <= 0) if (this.cachedInventory == null || item == null || item.getAmount() <= 0) {
return false; return false;
}
// Don't transfer shulker boxes into other shulker boxes, that's a bad idea. // Don't transfer shulker boxes into other shulker boxes, that's a bad idea.
if (type.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) if (this.type.name().contains("SHULKER_BOX") && item.getType().name().contains("SHULKER_BOX")) {
return false; return false;
}
// grab the amount to move and the max item stack size // grab the amount to move and the max item stack size
int toAdd = item.getAmount(); int toAdd = item.getAmount();
@ -263,7 +260,7 @@ public class StorageContainerCache {
boolean[] check = null; boolean[] check = null;
// some destination containers have special conditions // some destination containers have special conditions
switch (type.name()) { switch (this.type.name()) {
case "BREWING_STAND": { case "BREWING_STAND": {
// first compile a list of what slots to check // first compile a list of what slots to check
@ -274,10 +271,11 @@ public class StorageContainerCache {
check[0] = check[1] = check[2] = true; check[0] = check[1] = check[2] = true;
} }
// fuel in 5th position, input in 4th // fuel in 5th position, input in 4th
if (item.getType() == Material.BLAZE_POWDER) if (item.getType() == Material.BLAZE_POWDER) {
check[4] = true; check[4] = true;
else if (CompatibleMaterial.getMaterial(item).isBrewingStandIngredient()) } else if (CompatibleMaterial.getMaterial(item).isBrewingStandIngredient()) {
check[3] = true; check[3] = true;
}
break; break;
} }
@ -290,10 +288,11 @@ public class StorageContainerCache {
boolean isFuel = !item.getType().name().contains("LOG") && CompatibleMaterial.getMaterial(item.getType()).isFuel(); boolean isFuel = !item.getType().name().contains("LOG") && CompatibleMaterial.getMaterial(item.getType()).isFuel();
// fuel is 2nd slot, input is first // fuel is 2nd slot, input is first
if (isFuel) if (isFuel) {
check[1] = true; check[1] = true;
else } else {
check[0] = true; check[0] = true;
}
break; break;
} }
@ -303,15 +302,16 @@ public class StorageContainerCache {
// we can reduce calls to ItemStack.isSimilar() by caching what cells to look at // we can reduce calls to ItemStack.isSimilar() by caching what cells to look at
if (check == null) { if (check == null) {
check = new boolean[cachedInventory.length]; check = new boolean[this.cachedInventory.length];
for (int i = 0; toAdd > 0 && i < check.length; i++) for (int i = 0; toAdd > 0 && i < check.length; i++) {
check[i] = true; check[i] = true;
} }
}
// first verify that we can add this item // first verify that we can add this item
for (int i = 0; toAdd > 0 && i < cachedInventory.length; i++) { for (int i = 0; toAdd > 0 && i < this.cachedInventory.length; i++) {
if (check[i]) { if (check[i]) {
final ItemStack cacheItem = cachedInventory[i]; final ItemStack cacheItem = this.cachedInventory[i];
if (cacheItem == null || cacheItem.getAmount() == 0) { if (cacheItem == null || cacheItem.getAmount() == 0) {
// free slot! // free slot!
toAdd -= Math.min(maxStack, toAdd); toAdd -= Math.min(maxStack, toAdd);
@ -320,36 +320,38 @@ public class StorageContainerCache {
// free space! // free space!
toAdd -= Math.min(maxStack - cacheItem.getAmount(), toAdd); toAdd -= Math.min(maxStack - cacheItem.getAmount(), toAdd);
check[i] = true; check[i] = true;
} else } else {
check[i] = false; check[i] = false;
} }
} }
}
if (toAdd <= 0) { if (toAdd <= 0) {
// all good to add! // all good to add!
toAdd = item.getAmount(); toAdd = item.getAmount();
for (int i = 0; toAdd > 0 && i < cachedInventory.length; i++) { for (int i = 0; toAdd > 0 && i < this.cachedInventory.length; i++) {
if (!check[i]) if (!check[i]) {
continue; continue;
final ItemStack cacheItem = cachedInventory[i]; }
final ItemStack cacheItem = this.cachedInventory[i];
if (cacheItem == null || cacheItem.getAmount() == 0) { if (cacheItem == null || cacheItem.getAmount() == 0) {
// free slot! // free slot!
int adding = Math.min(maxStack, toAdd); int adding = Math.min(maxStack, toAdd);
cachedInventory[i] = item.clone(); this.cachedInventory[i] = item.clone();
cachedInventory[i].setAmount(adding); this.cachedInventory[i].setAmount(adding);
cacheChanged[i] = true; this.cacheChanged[i] = true;
cacheAdded[i] = adding; this.cacheAdded[i] = adding;
toAdd -= adding; toAdd -= adding;
} else if (maxStack > cacheItem.getAmount()) { } else if (maxStack > cacheItem.getAmount()) {
// free space! // free space!
// (no need to check item.isSimilar(cacheItem), since we have that cached in check[]) // (no need to check item.isSimilar(cacheItem), since we have that cached in check[])
int adding = Math.min(maxStack - cacheItem.getAmount(), toAdd); int adding = Math.min(maxStack - cacheItem.getAmount(), toAdd);
cachedInventory[i].setAmount(adding + cacheItem.getAmount()); this.cachedInventory[i].setAmount(adding + cacheItem.getAmount());
cacheChanged[i] = true; this.cacheChanged[i] = true;
cacheAdded[i] += adding; this.cacheAdded[i] += adding;
toAdd -= adding; toAdd -= adding;
} }
} }
dirty = true; this.dirty = true;
return true; return true;
} }
return false; return false;