Heavy code style changes and slight refactoring

This commit is contained in:
Christian Koop 2023-06-26 16:24:37 +02:00
parent 9ae08d75ed
commit 2627d28d8f
No known key found for this signature in database
GPG Key ID: 89A8181384E010A3
34 changed files with 726 additions and 726 deletions

View File

@ -14,6 +14,7 @@ import com.songoda.core.hooks.EconomyManager;
import com.songoda.core.hooks.HologramManager; import com.songoda.core.hooks.HologramManager;
import com.songoda.core.hooks.ProtectionManager; import com.songoda.core.hooks.ProtectionManager;
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.epicfurnaces.boost.BoostData; import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.boost.BoostManager; import com.songoda.epicfurnaces.boost.BoostManager;
import com.songoda.epicfurnaces.commands.CommandBoost; import com.songoda.epicfurnaces.commands.CommandBoost;
@ -65,8 +66,6 @@ import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class EpicFurnaces extends SongodaPlugin { public class EpicFurnaces extends SongodaPlugin {
private static EpicFurnaces INSTANCE;
private final Config furnaceRecipeFile = new Config(this, "Furnace Recipes.yml"); private final Config furnaceRecipeFile = new Config(this, "Furnace Recipes.yml");
private final Config levelsFile = new Config(this, "levels.yml"); private final Config levelsFile = new Config(this, "levels.yml");
@ -81,13 +80,16 @@ public class EpicFurnaces extends SongodaPlugin {
private DatabaseConnector databaseConnector; private DatabaseConnector databaseConnector;
private DataManager dataManager; private DataManager dataManager;
/**
* @deprecated Use {@link #getPlugin(Class)} instead
*/
@Deprecated
public static EpicFurnaces getInstance() { public static EpicFurnaces getInstance() {
return INSTANCE; return EpicFurnaces.getPlugin(EpicFurnaces.class);
} }
@Override @Override
public void onPluginLoad() { public void onPluginLoad() {
INSTANCE = this;
} }
@Override @Override
@ -132,14 +134,14 @@ public class EpicFurnaces extends SongodaPlugin {
new CommandGive(this), new CommandGive(this),
new CommandReload(this), new CommandReload(this),
new CommandRemote(this), new CommandRemote(this),
new CommandSettings(this, guiManager) new CommandSettings(this, this.guiManager)
); );
loadLevelManager(); loadLevelManager();
this.furnaceManager = new FurnaceManager(); this.furnaceManager = new FurnaceManager();
this.boostManager = new BoostManager(); this.boostManager = new BoostManager(this);
this.blacklistHandler = new BlacklistHandler(); this.blacklistHandler = new BlacklistHandler(this);
// Database stuff. // Database stuff.
try { try {
@ -165,7 +167,7 @@ public class EpicFurnaces 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()); new _1_InitialMigration(this));
dataMigrationManager.runMigrations(); dataMigrationManager.runMigrations();
Bukkit.getScheduler().runTaskAsynchronously(this, () -> { Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
@ -178,7 +180,7 @@ public class EpicFurnaces extends SongodaPlugin {
converted = true; converted = true;
Storage storage = new StorageYaml(this); Storage storage = new StorageYaml(this);
if (storage.containsGroup("charged")) { if (storage.containsGroup("charged")) {
console.sendMessage("[" + getDescription().getName() + "] " + ChatColor.RED + this.console.sendMessage("[" + getDescription().getName() + "] " + ChatColor.RED +
"Conversion process starting. Do NOT turn off your server." + "Conversion process starting. Do NOT turn off your server." +
"EpicFurnaces hasn't fully loaded yet, so make sure users don't" + "EpicFurnaces hasn't fully loaded yet, so make sure users don't" +
"interact with the plugin until the conversion process is complete."); "interact with the plugin until the conversion process is complete.");
@ -186,20 +188,25 @@ public class EpicFurnaces extends SongodaPlugin {
List<Furnace> furnaces = new ArrayList<>(); List<Furnace> furnaces = new ArrayList<>();
for (StorageRow row : storage.getRowsByGroup("charged")) { for (StorageRow row : storage.getRowsByGroup("charged")) {
Location location = Methods.unserializeLocation(row.getKey()); Location location = Methods.unserializeLocation(row.getKey());
if (location == null) continue; if (location == null) {
continue;
}
if (row.get("level").asInt() == 0) continue; if (row.get("level").asInt() == 0) {
continue;
}
String placedByStr = row.get("placedby").asString(); String placedByStr = row.get("placedby").asString();
UUID placedBy = placedByStr == null ? null : UUID.fromString(placedByStr); UUID placedBy = placedByStr == null ? null : UUID.fromString(placedByStr);
List<String> list = row.get("accesslist").asStringList(); List<String> list = row.get("accesslist").asStringList();
if (!list.isEmpty()) { if (!list.isEmpty()) {
for (String uuid : new ArrayList<>(list)) for (String uuid : new ArrayList<>(list)) {
if (uuid.contains(":")) { if (uuid.contains(":")) {
list = new ArrayList<>(); list = new ArrayList<>();
break; break;
} }
}
} }
List<UUID> usableList = list.stream().map(UUID::fromString).collect(Collectors.toList()); List<UUID> usableList = list.stream().map(UUID::fromString).collect(Collectors.toList());
@ -211,23 +218,24 @@ public class EpicFurnaces extends SongodaPlugin {
} }
furnaces.add(new FurnaceBuilder(location) furnaces.add(new FurnaceBuilder(location)
.setLevel(levelManager.getLevel(row.get("level").asInt())) .setLevel(this.levelManager.getLevel(row.get("level").asInt()))
.setNickname(row.get("nickname").asString()) .setNickname(row.get("nickname").asString())
.setUses(row.get("uses").asInt()) .setUses(row.get("uses").asInt())
.setToLevel(toLevel) .setToLevel(toLevel)
.setAccessList(usableList) .setAccessList(usableList)
.setPlacedBy(placedBy).build()); .setPlacedBy(placedBy).build());
} }
dataManager.createFurnaces(furnaces); this.dataManager.createFurnaces(furnaces);
} }
// Adding in Boosts // Adding in Boosts
if (storage.containsGroup("boosts")) { if (storage.containsGroup("boosts")) {
for (StorageRow row : storage.getRowsByGroup("boosts")) { for (StorageRow row : storage.getRowsByGroup("boosts")) {
if (row.get("uuid").asObject() == null) if (row.get("uuid").asObject() == null) {
continue; continue;
}
dataManager.createBoost(new BoostData( this.dataManager.createBoost(new BoostData(
row.get("amount").asInt(), row.get("amount").asInt(),
Long.parseLong(row.getKey()), Long.parseLong(row.getKey()),
UUID.fromString(row.get("uuid").asString()))); UUID.fromString(row.get("uuid").asString())));
@ -237,9 +245,9 @@ public class EpicFurnaces extends SongodaPlugin {
} }
final boolean finalConverted = converted; final boolean finalConverted = converted;
dataManager.runAsync(() -> { this.dataManager.runAsync(() -> {
if (finalConverted) { if (finalConverted) {
console.sendMessage("[" + getDescription().getName() + "] " + ChatColor.GREEN + "Conversion complete :)"); this.console.sendMessage("[" + getDescription().getName() + "] " + ChatColor.GREEN + "Conversion complete :)");
} }
this.dataManager.getFurnaces((furnaces) -> { this.dataManager.getFurnaces((furnaces) -> {
@ -249,18 +257,18 @@ public class EpicFurnaces extends SongodaPlugin {
}); });
}); });
setupRecipies(); setupRecipes();
// Start Tasks // Start Tasks
FurnaceTask.startTask(this); FurnaceTask.startTask(this);
HologramTask.startTask(this); HologramTask.startTask(this);
// Register Listeners // Register Listeners
guiManager.init(); this.guiManager.init();
PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
pluginManager.registerEvents(new BlockListeners(this), this); pluginManager.registerEvents(new BlockListeners(this), this);
pluginManager.registerEvents(new FurnaceListeners(this), this); pluginManager.registerEvents(new FurnaceListeners(this), this);
pluginManager.registerEvents(new InteractListeners(this, guiManager), this); pluginManager.registerEvents(new InteractListeners(this, this.guiManager), this);
pluginManager.registerEvents(new InventoryListeners(this), this); pluginManager.registerEvents(new InventoryListeners(this), this);
pluginManager.registerEvents(new EntityListeners(this), this); pluginManager.registerEvents(new EntityListeners(this), this);
} }
@ -279,7 +287,7 @@ public class EpicFurnaces extends SongodaPlugin {
@Override @Override
public List<Config> getExtraConfig() { public List<Config> getExtraConfig() {
return Collections.singletonList(levelsFile); return Collections.singletonList(this.levelsFile);
} }
public void clearHologram(Furnace furnace) { public void clearHologram(Furnace furnace) {
@ -288,18 +296,24 @@ public class EpicFurnaces extends SongodaPlugin {
public void updateHolograms(Collection<Furnace> furnaces) { public void updateHolograms(Collection<Furnace> furnaces) {
// are holograms enabled? // are holograms enabled?
if (!Settings.HOLOGRAMS.getBoolean() || !HologramManager.getManager().isEnabled()) return; if (!Settings.HOLOGRAMS.getBoolean() || !HologramManager.getManager().isEnabled()) {
return;
}
Map<String, List<String>> holograms = new HashMap<>(); Map<String, List<String>> holograms = new HashMap<>();
for (Furnace furnace : furnaces) { for (Furnace furnace : furnaces) {
// don't try to load furnaces in chunks that aren't loaded // don't try to load furnaces in chunks that aren't loaded
if (!furnace.isInLoadedChunk()) continue; if (!furnace.isInLoadedChunk()) {
continue;
}
BlockState state = furnace.getLocation().getBlock().getState(); BlockState state = furnace.getLocation().getBlock().getState();
// verify that this is a furnace // verify that this is a furnace
if (!(state instanceof org.bukkit.block.Furnace)) continue; if (!(state instanceof org.bukkit.block.Furnace)) {
continue;
}
org.bukkit.block.Furnace furnaceBlock = ((org.bukkit.block.Furnace) state); org.bukkit.block.Furnace furnaceBlock = ((org.bukkit.block.Furnace) state);
@ -320,7 +334,7 @@ public class EpicFurnaces extends SongodaPlugin {
sb.append("&c="); sb.append("&c=");
} }
progress = Methods.formatText(sb.toString()); progress = TextUtils.formatText(sb.toString());
} else { } else {
progress = getLocale().getMessage("general.hologram.outoffuel").getMessage(); progress = getLocale().getMessage("general.hologram.outoffuel").getMessage();
} }
@ -352,22 +366,23 @@ public class EpicFurnaces extends SongodaPlugin {
} }
private void loadLevelManager() { private void loadLevelManager() {
if (!levelsFile.getFile().exists()) if (!this.levelsFile.getFile().exists()) {
this.saveResource("levels.yml", false); this.saveResource("levels.yml", false);
levelsFile.load(); }
this.levelsFile.load();
// Load an plugin of LevelManager // Load a plugin 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 : levelsFile.getKeys(false)) { for (String levelName : this.levelsFile.getKeys(false)) {
int level = Integer.parseInt(levelName.split("-")[1]); int level = Integer.parseInt(levelName.split("-")[1]);
ConfigurationSection levels = levelsFile.getConfigurationSection(levelName); ConfigurationSection levels = this.levelsFile.getConfigurationSection(levelName);
int costExperiance = levels.getInt("Cost-xp"); int costExperience = levels.getInt("Cost-xp");
int costEconomy = levels.getInt("Cost-eco"); int costEconomy = levels.getInt("Cost-eco");
String performanceStr = levels.getString("Performance"); String performanceStr = levels.getString("Performance");
@ -389,23 +404,23 @@ public class EpicFurnaces extends SongodaPlugin {
} }
} }
levelManager.addLevel(level, costExperiance, costEconomy, performance, reward, fuelDuration, overheat, fuelShare, materials); this.levelManager.addLevel(level, costExperience, costEconomy, performance, reward, fuelDuration, overheat, fuelShare, materials);
} }
} }
private void setupRecipies() { private void setupRecipes() {
File config = new File(getDataFolder(), "Furnace Recipes.yml"); File config = new File(getDataFolder(), "Furnace Recipes.yml");
if (!config.exists()) { if (!config.exists()) {
saveResource("Furnace Recipes.yml", false); saveResource("Furnace Recipes.yml", false);
} }
furnaceRecipeFile.load(); this.furnaceRecipeFile.load();
if (Settings.CUSTOM_RECIPES.getBoolean()) { if (Settings.CUSTOM_RECIPES.getBoolean()) {
ConfigurationSection cs = furnaceRecipeFile.getConfigurationSection("Recipes"); ConfigurationSection cs = this.furnaceRecipeFile.getConfigurationSection("Recipes");
for (String key : cs.getKeys(false)) { for (String key : cs.getKeys(false)) {
Material item = Material.valueOf(key.toUpperCase()); Material item = Material.valueOf(key.toUpperCase());
Material result = Material.valueOf(furnaceRecipeFile.getString("Recipes." + key.toUpperCase() + ".result")); Material result = Material.valueOf(this.furnaceRecipeFile.getString("Recipes." + key.toUpperCase() + ".result"));
int amount = furnaceRecipeFile.getInt("Recipes." + key.toUpperCase() + ".amount"); int amount = this.furnaceRecipeFile.getInt("Recipes." + key.toUpperCase() + ".amount");
getServer().addRecipe(new FurnaceRecipe(new ItemStack(result, amount), item)); getServer().addRecipe(new FurnaceRecipe(new ItemStack(result, amount), item));
} }
@ -415,7 +430,7 @@ public class EpicFurnaces extends SongodaPlugin {
public boolean isLeveledFurnace(ItemStack itemStack) { public boolean isLeveledFurnace(ItemStack itemStack) {
NBTItem nbtItem = new NBTItem(itemStack); NBTItem nbtItem = new NBTItem(itemStack);
return nbtItem.hasKey("level") && nbtItem.hasKey("uses"); return nbtItem.hasTag("level") && nbtItem.hasTag("uses");
} }
public ItemStack createLeveledFurnace(Material material, int level, int uses) { public ItemStack createLeveledFurnace(Material material, int level, int uses) {
@ -423,7 +438,7 @@ public class EpicFurnaces extends SongodaPlugin {
if (Settings.FURNACE_ITEM.getBoolean()) { if (Settings.FURNACE_ITEM.getBoolean()) {
ItemMeta itemmeta = item.getItemMeta(); ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(Methods.formatText(Methods.formatName(level))); itemmeta.setDisplayName(TextUtils.formatText(Methods.formatName(level)));
item.setItemMeta(itemmeta); item.setItemMeta(itemmeta);
} }
@ -437,8 +452,9 @@ public class EpicFurnaces extends SongodaPlugin {
public int getFurnaceLevel(ItemStack item) { public int getFurnaceLevel(ItemStack item) {
NBTItem nbtItem = new NBTItem(item); NBTItem nbtItem = new NBTItem(item);
if (nbtItem.hasKey("level")) if (nbtItem.hasTag("level")) {
return nbtItem.getInteger("level"); return nbtItem.getInteger("level");
}
// Legacy trash. // Legacy trash.
if (item.getItemMeta().getDisplayName().contains(":")) { if (item.getItemMeta().getDisplayName().contains(":")) {
@ -452,8 +468,9 @@ public class EpicFurnaces extends SongodaPlugin {
public int getFurnaceUses(ItemStack item) { public int getFurnaceUses(ItemStack item) {
NBTItem nbtItem = new NBTItem(item); NBTItem nbtItem = new NBTItem(item);
if (nbtItem.hasKey("uses")) if (nbtItem.hasTag("uses")) {
return nbtItem.getInteger("uses"); return nbtItem.getInteger("uses");
}
// Legacy trash. // Legacy trash.
if (item.getItemMeta().getDisplayName().contains(":")) { if (item.getItemMeta().getDisplayName().contains(":")) {
@ -465,34 +482,34 @@ public class EpicFurnaces extends SongodaPlugin {
} }
public Config getFurnaceRecipeFile() { public Config getFurnaceRecipeFile() {
return furnaceRecipeFile; return this.furnaceRecipeFile;
} }
public CommandManager getCommandManager() { public CommandManager getCommandManager() {
return commandManager; return this.commandManager;
} }
public BoostManager getBoostManager() { public BoostManager getBoostManager() {
return boostManager; return this.boostManager;
} }
public BlacklistHandler getBlacklistHandler() { public BlacklistHandler getBlacklistHandler() {
return blacklistHandler; return this.blacklistHandler;
} }
public FurnaceManager getFurnaceManager() { public FurnaceManager getFurnaceManager() {
return furnaceManager; return this.furnaceManager;
} }
public LevelManager getLevelManager() { public LevelManager getLevelManager() {
return levelManager; return this.levelManager;
} }
public DatabaseConnector getDatabaseConnector() { public DatabaseConnector getDatabaseConnector() {
return databaseConnector; return this.databaseConnector;
} }
public DataManager getDataManager() { public DataManager getDataManager() {
return dataManager; return this.dataManager;
} }
} }

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,23 +15,23 @@ 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;
} }
@ -43,8 +42,7 @@ public class BoostData {
if (!(obj instanceof BoostData)) return false; 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 && this.endTime == other.endTime
&& Objects.equals(player, other.player); && Objects.equals(this.player, other.player);
} }
} }

View File

@ -2,18 +2,27 @@ package com.songoda.epicfurnaces.boost;
import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.EpicFurnaces;
import java.util.*; import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class BoostManager { public class BoostManager {
private final EpicFurnaces plugin;
private final Set<BoostData> registeredBoosts = new HashSet<>(); private final Set<BoostData> registeredBoosts = new HashSet<>();
public BoostManager(EpicFurnaces plugin) {
this.plugin = plugin;
}
public void addBoostToPlayer(BoostData data) { public void addBoostToPlayer(BoostData data) {
this.registeredBoosts.add(data); this.registeredBoosts.add(data);
} }
public void addBoosts(List<BoostData> boosts) { public void addBoosts(List<BoostData> boosts) {
registeredBoosts.addAll(boosts); this.registeredBoosts.addAll(boosts);
} }
public void removeBoostFromPlayer(BoostData data) { public void removeBoostFromPlayer(BoostData data) {
@ -21,16 +30,19 @@ public class BoostManager {
} }
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);
EpicFurnaces.getInstance().getDataManager().deleteBoost(boostData); this.plugin.getDataManager().deleteBoost(boostData);
} }
return boostData; return boostData;
} }

View File

@ -1,9 +1,10 @@
package com.songoda.epicfurnaces.commands; package com.songoda.epicfurnaces.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.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.boost.BoostData; import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.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;
@ -13,7 +14,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
public class CommandBoost extends AbstractCommand { public class CommandBoost extends AbstractCommand {
private final EpicFurnaces instance; private final EpicFurnaces instance;
public CommandBoost(EpicFurnaces instance) { public CommandBoost(EpicFurnaces instance) {
@ -24,36 +24,34 @@ 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) {
instance.getLocale().newMessage("&7Syntax error...").sendPrefixedMessage(sender); this.instance.getLocale().newMessage("&7Syntax error...").sendPrefixedMessage(sender);
return ReturnType.SYNTAX_ERROR; return ReturnType.SYNTAX_ERROR;
} }
if (!Methods.isInt(args[1])) { if (!NumberUtils.isInt(args[1])) {
instance.getLocale().newMessage("&6" + args[1] + " &7is not a number...").sendPrefixedMessage(sender); this.instance.getLocale().newMessage("&6" + args[1] + " &7is not a number...").sendPrefixedMessage(sender);
return ReturnType.SYNTAX_ERROR; return ReturnType.SYNTAX_ERROR;
} }
long duration = 0L; long duration = 0L;
if (args.length > 2) { if (args.length > 2) {
for (int i = 0; i < args.length; i++) { for (String line : args) {
String line = args[i]; long time = TimeUtils.parseTime(line);
long time = Methods.parseTime(line);
duration += time; duration += time;
} }
} }
Player player = Bukkit.getPlayer(args[0]); Player player = Bukkit.getPlayer(args[0]);
if (player == null) { if (player == null) {
instance.getLocale().newMessage("&cThat player does not exist or is not online...").sendPrefixedMessage(sender); this.instance.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());
instance.getBoostManager().addBoostToPlayer(boostData); this.instance.getBoostManager().addBoostToPlayer(boostData);
instance.getDataManager().createBoost(boostData); this.instance.getDataManager().createBoost(boostData);
instance.getLocale().newMessage("&7Successfully boosted &6" + Bukkit.getPlayer(args[0]).getName() this.instance.getLocale().newMessage("&7Successfully boosted &6" + Bukkit.getPlayer(args[0]).getName()
+ "'s &7furnace reward amounts &6" + args[1] + "x" + (duration == 0L ? "" : (" for " + Methods.makeReadable(duration))) + "&7.").sendPrefixedMessage(sender); + "'s &7furnace reward amounts &6" + args[1] + "x" + (duration == 0L ? "" : (" for " + TimeUtils.makeReadable(duration))) + "&7.").sendPrefixedMessage(sender);
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }

View File

@ -11,7 +11,6 @@ import org.bukkit.entity.Player;
import java.util.List; import java.util.List;
public class CommandGive extends AbstractCommand { public class CommandGive extends AbstractCommand {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
public CommandGive(EpicFurnaces plugin) { public CommandGive(EpicFurnaces plugin) {
@ -21,16 +20,18 @@ public class CommandGive extends AbstractCommand {
@Override @Override
protected ReturnType runCommand(CommandSender sender, String... args) { protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length == 1) return ReturnType.SYNTAX_ERROR; if (args.length == 1) {
return ReturnType.SYNTAX_ERROR;
}
Level level = plugin.getLevelManager().getLowestLevel(); Level level = this.plugin.getLevelManager().getLowestLevel();
Player player; Player player;
if (args.length != 0 && Bukkit.getPlayer(args[0]) == null) { if (args.length != 0 && 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 if (args.length == 0) { } else if (args.length == 0) {
if (!(sender instanceof Player)) { if (!(sender instanceof Player)) {
plugin.getLocale().newMessage("&cYou need to be a player to give a farm item to yourself.").sendPrefixedMessage(sender); this.plugin.getLocale().newMessage("&cYou need to be a player to give a farm item to yourself.").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
player = (Player) sender; player = (Player) sender;
@ -39,23 +40,23 @@ public class CommandGive extends AbstractCommand {
} }
if (args.length >= 2 && !plugin.getLevelManager().isLevel(Integer.parseInt(args[1]))) { if (args.length >= 2 && !this.plugin.getLevelManager().isLevel(Integer.parseInt(args[1]))) {
plugin.getLocale().newMessage("&cNot a valid level... The current valid levels are: &4" this.plugin.getLocale().newMessage("&cNot a valid level... The current valid levels are: &4"
+ plugin.getLevelManager().getLowestLevel().getLevel() + "-" + this.plugin.getLevelManager().getLowestLevel().getLevel() + "-"
+ plugin.getLevelManager().getHighestLevel().getLevel() + "&c.").sendPrefixedMessage(sender); + this.plugin.getLevelManager().getHighestLevel().getLevel() + "&c.").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} else if (args.length != 0) { } else if (args.length != 0) {
level = plugin.getLevelManager().getLevel(Integer.parseInt(args[1])); level = this.plugin.getLevelManager().getLevel(Integer.parseInt(args[1]));
} }
player.getInventory().addItem(plugin.createLeveledFurnace(Material.FURNACE, level.getLevel(), 0)); player.getInventory().addItem(this.plugin.createLeveledFurnace(Material.FURNACE, level.getLevel(), 0));
plugin.getLocale().getMessage("command.give.success") this.plugin.getLocale().getMessage("command.give.success")
.processPlaceholder("level", level.getLevel()).sendPrefixedMessage(sender); .processPlaceholder("level", level.getLevel()).sendPrefixedMessage(sender);
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }
@Override @Override
protected List<String> onTab(CommandSender commandSender, String... strings) { protected List<String> onTab(CommandSender sender, String... args) {
return null; return null;
} }

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 EpicFurnaces plugin; private final EpicFurnaces plugin;
public CommandReload(EpicFurnaces plugin) { public CommandReload(EpicFurnaces plugin) {
@ -17,8 +16,8 @@ public class CommandReload extends AbstractCommand {
@Override @Override
protected AbstractCommand.ReturnType runCommand(CommandSender sender, String... args) { protected AbstractCommand.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

@ -13,7 +13,6 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
public class CommandRemote extends AbstractCommand { public class CommandRemote extends AbstractCommand {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
public CommandRemote(EpicFurnaces plugin) { public CommandRemote(EpicFurnaces plugin) {
@ -25,39 +24,43 @@ public class CommandRemote extends AbstractCommand {
protected ReturnType runCommand(CommandSender sender, String... args) { protected ReturnType runCommand(CommandSender sender, String... args) {
Player player = ((Player) sender); Player player = ((Player) sender);
if (!Settings.REMOTE.getBoolean() || !sender.hasPermission("EpicFurnaces.Remote")) { if (!Settings.REMOTE.getBoolean() || !sender.hasPermission("EpicFurnaces.Remote")) {
plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender); this.plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
if (args.length < 1) return ReturnType.SYNTAX_ERROR; if (args.length < 1) {
return ReturnType.SYNTAX_ERROR;
}
String name = String.join(" ", args); String name = String.join(" ", args);
Furnace furnace = plugin.getFurnaceManager().getFurnaces().values() Furnace furnace = this.plugin.getFurnaceManager().getFurnaces().values()
.stream().filter(f -> f.getNickname() != null .stream().filter(f -> f.getNickname() != null
&& f.getNickname().equalsIgnoreCase(name)).findFirst().orElse(null); && f.getNickname().equalsIgnoreCase(name)).findFirst().orElse(null);
if (furnace == null) { if (furnace == null) {
plugin.getLocale().getMessage("event.remote.notfound").sendPrefixedMessage(sender); this.plugin.getLocale().getMessage("event.remote.notfound").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
if (!furnace.isInLoadedChunk()) { if (!furnace.isInLoadedChunk()) {
plugin.getLocale().getMessage("event.remote.notloaded").sendPrefixedMessage(sender); this.plugin.getLocale().getMessage("event.remote.notloaded").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
for (UUID uuid : furnace.getAccessList()) { for (UUID uuid : furnace.getAccessList()) {
if (!uuid.equals(((Player) sender).getUniqueId())) continue; if (!uuid.equals(((Player) sender).getUniqueId())) {
Block b = furnace.getLocation().getBlock(); continue;
org.bukkit.block.Furnace furnaceBlock = (org.bukkit.block.Furnace) b.getState(); }
Block block = furnace.getLocation().getBlock();
org.bukkit.block.Furnace furnaceBlock = (org.bukkit.block.Furnace) block.getState();
Inventory inventory = furnaceBlock.getInventory(); Inventory inventory = furnaceBlock.getInventory();
player.openInventory(inventory); player.openInventory(inventory);
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }
plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender); this.plugin.getLocale().getMessage("event.general.nopermission").sendPrefixedMessage(sender);
return ReturnType.FAILURE; return ReturnType.FAILURE;
} }
@Override @Override
protected List<String> onTab(CommandSender commandSender, String... strings) { protected List<String> onTab(CommandSender sender, String... args) {
return null; return null;
} }

View File

@ -10,7 +10,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 EpicFurnaces plugin; private final EpicFurnaces plugin;
private final GuiManager guiManager; private final GuiManager guiManager;
@ -22,12 +21,12 @@ public class CommandSettings extends AbstractCommand {
@Override @Override
protected ReturnType runCommand(CommandSender sender, String... args) { protected ReturnType runCommand(CommandSender sender, String... args) {
guiManager.showGUI((Player) sender, new PluginConfigGui(plugin)); this.guiManager.showGUI((Player) sender, new PluginConfigGui(this.plugin));
return ReturnType.SUCCESS; return ReturnType.SUCCESS;
} }
@Override @Override
protected List<String> onTab(CommandSender commandSender, String... strings) { protected List<String> onTab(CommandSender sender, String... args) {
return null; return null;
} }

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 EpicFurnacesPermission extends BasicPermission { public class EpicFurnacesPermission extends BasicPermission {
public EpicFurnacesPermission() { public EpicFurnacesPermission() {
super("EpicFurnaces", CompatibleMaterial.FIRE_CHARGE, PermissionType.GENERIC); super("EpicFurnaces", CompatibleMaterial.FIRE_CHARGE, PermissionType.GENERIC);
} }
} }

View File

@ -3,17 +3,14 @@ package com.songoda.epicfurnaces.compatibility;
import com.songoda.skyblock.SkyBlock; import com.songoda.skyblock.SkyBlock;
import com.songoda.skyblock.permission.BasicPermission; import com.songoda.skyblock.permission.BasicPermission;
import java.lang.reflect.InvocationTargetException;
public class FabledSkyBlockLoader { public class FabledSkyBlockLoader {
public FabledSkyBlockLoader() { public FabledSkyBlockLoader() {
SkyBlock.getInstance().getPermissionManager().registerPermission(new EpicFurnacesPermission()); SkyBlock.getInstance().getPermissionManager().registerPermission(new EpicFurnacesPermission());
try { try {
SkyBlock.getInstance().getPermissionManager().registerPermission( SkyBlock.getInstance().getPermissionManager().registerPermission((BasicPermission) Class.forName("com.songoda.epicfurnaces.compatibility.EpicFurnacesPermission").getDeclaredConstructor().newInstance());
(BasicPermission) Class.forName("com.songoda.epicfurnaces.compatibility.EpicFurnacesPermission").getDeclaredConstructor().newInstance()); } catch (ReflectiveOperationException ex) {
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { ex.printStackTrace();
e.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 EpicFurnaces plugin;
public _1_InitialMigration() { public _1_InitialMigration(EpicFurnaces 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 = EpicFurnaces.getInstance().getDatabaseConnector() instanceof MySQLConnector ? " AUTO_INCREMENT" : ""; String autoIncrement = this.plugin.getDatabaseConnector() instanceof MySQLConnector ? " AUTO_INCREMENT" : "";
// Create furnaces table. // Create furnaces table.
try (Statement statement = connection.createStatement()) { try (Statement statement = connection.createStatement()) {
@ -58,6 +60,5 @@ public class _1_InitialMigration extends DataMigration {
"end_time BIGINT NOT NULL " + "end_time BIGINT NOT NULL " +
")"); ")");
} }
} }
} }

View File

@ -39,7 +39,7 @@ import java.util.UUID;
* Created by songoda on 3/7/2017. * Created by songoda on 3/7/2017.
*/ */
public class Furnace { public class Furnace {
private final EpicFurnaces plugin = EpicFurnaces.getInstance(); private final EpicFurnaces plugin = EpicFurnaces.getPlugin(EpicFurnaces.class);
private final String hologramId = UUID.randomUUID().toString(); private final String hologramId = UUID.randomUUID().toString();
@ -47,7 +47,7 @@ public class Furnace {
private int id; private int id;
private final Location location; private final Location location;
private Level level = plugin.getLevelManager().getLowestLevel(); private Level level = this.plugin.getLevelManager().getLowestLevel();
private String nickname = null; private String nickname = null;
private UUID placedBy = null; private UUID placedBy = null;
private int uses, radiusOverheatLast, radiusFuelshareLast = 0; private int uses, radiusOverheatLast, radiusFuelshareLast = 0;
@ -63,38 +63,46 @@ public class Furnace {
} }
public void overview(GuiManager guiManager, Player player) { public void overview(GuiManager guiManager, Player player) {
if (placedBy == null) placedBy = player.getUniqueId(); if (this.placedBy == null) {
this.placedBy = player.getUniqueId();
}
if (!player.hasPermission("epicfurnaces.overview")) return; if (!player.hasPermission("epicfurnaces.overview")) {
if (Settings.USE_PROTECTION_PLUGINS.getBoolean() && !ProtectionManager.canInteract(player, location)) {
player.sendMessage(plugin.getLocale().getMessage("event.general.protected").getPrefixedMessage());
return; return;
} }
guiManager.showGUI(player, new GUIOverview(plugin, this, player)); if (Settings.USE_PROTECTION_PLUGINS.getBoolean() && !ProtectionManager.canInteract(player, this.location)) {
player.sendMessage(this.plugin.getLocale().getMessage("event.general.protected").getPrefixedMessage());
return;
}
guiManager.showGUI(player, new GUIOverview(this.plugin, this, player));
} }
public void plus(FurnaceSmeltEvent event) { public void plus(FurnaceSmeltEvent event) {
Block block = location.getBlock(); Block block = this.location.getBlock();
if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")) return; if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")) {
return;
}
this.uses++; this.uses++;
plugin.getDataManager().queueFurnaceForUpdate(this); this.plugin.getDataManager().queueFurnaceForUpdate(this);
CompatibleMaterial material = CompatibleMaterial.getMaterial(event.getResult()); CompatibleMaterial material = CompatibleMaterial.getMaterial(event.getResult());
int needed = -1; int needed = -1;
if (level.getMaterials().containsKey(material)) { if (this.level.getMaterials().containsKey(material)) {
int amount = addToLevel(material, 1); int amount = addToLevel(material, 1);
plugin.getDataManager().updateLevelupItems(this, material, amount); this.plugin.getDataManager().updateLevelupItems(this, material, amount);
needed = level.getMaterials().get(material) - getToLevel(material); needed = this.level.getMaterials().get(material) - getToLevel(material);
} }
if (level.getReward() == null) return; if (this.level.getReward() == null) {
return;
}
String reward = level.getReward(); String reward = this.level.getReward();
int min = 1; int min = 1;
int max = 1; int max = 1;
if (reward.contains(":")) { if (reward.contains(":")) {
@ -110,9 +118,9 @@ public class Furnace {
} }
} }
if (Settings.UPGRADE_BY_SMELTING.getBoolean() if (Settings.UPGRADE_BY_SMELTING.getBoolean() &&
&& needed == 0 needed == 0 &&
&& plugin.getLevelManager().getLevel(level.getLevel() + 1) != null) { this.plugin.getLevelManager().getLevel(this.level.getLevel() + 1) != null) {
this.toLevel.remove(material); this.toLevel.remove(material);
levelUp(); levelUp();
} }
@ -121,30 +129,35 @@ public class Furnace {
FurnaceInventory inventory = (FurnaceInventory) ((InventoryHolder) block.getState()).getInventory(); FurnaceInventory inventory = (FurnaceInventory) ((InventoryHolder) block.getState()).getInventory();
if (event.getSource().getType().name().contains("SPONGE") || event.getSource().getType().name().contains("COBBLESTONE") || event.getSource().getType().name().contains("DEEPSLATE")) if (event.getSource().getType().name().contains("SPONGE") ||
event.getSource().getType().name().contains("COBBLESTONE") ||
event.getSource().getType().name().contains("DEEPSLATE")) {
return; return;
}
int num = Integer.parseInt(reward); int num = Integer.parseInt(reward);
double rand = Math.random() * 100; double rand = Math.random() * 100;
if (rand >= num if (rand >= num
|| event.getResult().equals(Material.SPONGE) || event.getResult().equals(Material.SPONGE)
|| Settings.NO_REWARDS_FROM_RECIPES.getBoolean() || Settings.NO_REWARDS_FROM_RECIPES.getBoolean()
&& plugin.getFurnaceRecipeFile().contains("Recipes." + inventory.getSmelting().getType().toString())) { && this.plugin.getFurnaceRecipeFile().contains("Recipes." + inventory.getSmelting().getType())) {
return; return;
} }
int randomAmount = min == max ? min : (int) (Math.random() * ((max - min) + 1)) + min; int randomAmount = min == max ? min : (int) (Math.random() * ((max - min) + 1)) + min;
BoostData boostData = plugin.getBoostManager().getBoost(placedBy); BoostData boostData = this.plugin.getBoostManager().getBoost(this.placedBy);
randomAmount = randomAmount * (boostData == null ? 1 : boostData.getMultiplier()); randomAmount = randomAmount * (boostData == null ? 1 : boostData.getMultiplier());
event.getResult().setAmount(Math.min(event.getResult().getAmount() + randomAmount, event.getResult().getMaxStackSize())); event.getResult().setAmount(Math.min(event.getResult().getAmount() + randomAmount, event.getResult().getMaxStackSize()));
} }
public void upgrade(Player player, CostType type) { public void upgrade(Player player, CostType type) {
if (!plugin.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) return; if (!this.plugin.getLevelManager().getLevels().containsKey(this.level.getLevel() + 1)) {
return;
}
Level level = plugin.getLevelManager().getLevel(this.level.getLevel() + 1); Level level = this.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();
if (type == CostType.ECONOMY) { if (type == CostType.ECONOMY) {
@ -153,7 +166,7 @@ public class Furnace {
return; return;
} }
if (!EconomyManager.hasBalance(player, cost)) { if (!EconomyManager.hasBalance(player, cost)) {
plugin.getInstance().getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player);
return; return;
} }
EconomyManager.withdrawBalance(player, cost); EconomyManager.withdrawBalance(player, cost);
@ -165,7 +178,7 @@ public class Furnace {
} }
upgradeFinal(player); upgradeFinal(player);
} else { } else {
plugin.getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.upgrade.cannotafford").sendPrefixedMessage(player);
} }
} }
} }
@ -173,55 +186,63 @@ public class Furnace {
private void upgradeFinal(Player player) { private void upgradeFinal(Player player) {
levelUp(); levelUp();
syncName(); syncName();
plugin.getDataManager().queueFurnaceForUpdate(this); this.plugin.getDataManager().queueFurnaceForUpdate(this);
if (plugin.getLevelManager().getHighestLevel() != level) { if (this.plugin.getLevelManager().getHighestLevel() != this.level) {
plugin.getLocale().getMessage("event.upgrade.success") this.plugin.getLocale().getMessage("event.upgrade.success")
.processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); .processPlaceholder("level", this.level.getLevel()).sendPrefixedMessage(player);
} else { } else {
plugin.getLocale().getMessage("event.upgrade.maxed") this.plugin.getLocale().getMessage("event.upgrade.maxed")
.processPlaceholder("level", level.getLevel()).sendPrefixedMessage(player); .processPlaceholder("level", this.level.getLevel()).sendPrefixedMessage(player);
} }
Location loc = location.clone().add(.5, .5, .5); Location loc = this.location.clone().add(.5, .5, .5);
if (!ServerVersion.isServerVersionAtLeast(ServerVersion.V1_12)) return; if (!ServerVersion.isServerVersionAtLeast(ServerVersion.V1_12)) {
return;
}
player.getWorld().spawnParticle(org.bukkit.Particle.valueOf(plugin.getConfig().getString("Main.Upgrade Particle Type")), loc, 200, .5, .5, .5); player.getWorld().spawnParticle(org.bukkit.Particle.valueOf(this.plugin.getConfig().getString("Main.Upgrade Particle Type")), loc, 200, .5, .5, .5);
if (plugin.getLevelManager().getHighestLevel() != level) { if (this.plugin.getLevelManager().getHighestLevel() != this.level) {
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 15.0F); player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 0.6F, 15.0F);
} else { } else {
player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 2F, 25.0F); player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 2F, 25.0F);
if (!ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) return; if (!ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) {
return;
}
player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_CHIME, 2F, 25.0F); player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_CHIME, 2F, 25.0F);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_CHIME, 1.2F, 35.0F), 5L); Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, () -> player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_CHIME, 1.2F, 35.0F), 5L);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_CHIME, 1.8F, 35.0F), 10L); Bukkit.getScheduler().scheduleSyncDelayedTask(this.plugin, () -> player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_CHIME, 1.8F, 35.0F), 10L);
} }
} }
public void levelUp() { public void levelUp() {
level = plugin.getLevelManager().getLevel(this.level.getLevel() + 1); this.level = this.plugin.getLevelManager().getLevel(this.level.getLevel() + 1);
} }
private void syncName() { private void syncName() {
org.bukkit.block.Furnace furnace = (org.bukkit.block.Furnace) location.getBlock().getState(); org.bukkit.block.Furnace furnace = (org.bukkit.block.Furnace) this.location.getBlock().getState();
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_10)) if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_10)) {
furnace.setCustomName(Methods.formatName(level.getLevel())); furnace.setCustomName(Methods.formatName(this.level.getLevel()));
}
furnace.update(true); furnace.update(true);
} }
public void updateCook() { public void updateCook() {
Block block = location.getBlock(); Block block = this.location.getBlock();
if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")) return; if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")) {
return;
}
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, () -> { Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, () -> {
int num = getPerformanceTotal(block.getType()); int num = getPerformanceTotal(block.getType());
int max = (block.getType().name().contains("BLAST") || block.getType().name().contains("SMOKER") ? 100 : 200); int max = (block.getType().name().contains("BLAST") || block.getType().name().contains("SMOKER") ? 100 : 200);
if (num >= max) if (num >= max) {
num = max - 1; num = max - 1;
}
if (num != 0) { if (num != 0) {
BlockState bs = (block.getState()); BlockState bs = (block.getState());
@ -233,17 +254,17 @@ public class Furnace {
public Level getLevel() { public Level getLevel() {
return level; return this.level;
} }
public List<UUID> getAccessList() { public List<UUID> getAccessList() {
return Collections.unmodifiableList(accessList); return Collections.unmodifiableList(this.accessList);
} }
public int getPerformanceTotal(Material material) { public int getPerformanceTotal(Material material) {
String cap = (material.name().contains("BLAST") || material.name().contains("SMOKER") ? "100" : "200"); String cap = (material.name().contains("BLAST") || material.name().contains("SMOKER") ? "100" : "200");
String equation = "(" + level.getPerformance() + " / 100) * " + cap; String equation = "(" + this.level.getPerformance() + " / 100) * " + cap;
return (int) MathUtils.eval(equation); return (int) MathUtils.eval(equation);
} }
@ -252,66 +273,71 @@ public class Furnace {
} }
public boolean addToAccessList(UUID uuid) { public boolean addToAccessList(UUID uuid) {
return accessList.add(uuid); return this.accessList.add(uuid);
} }
public boolean removeFromAccessList(UUID uuid) { public boolean removeFromAccessList(UUID uuid) {
return accessList.remove(uuid); return this.accessList.remove(uuid);
} }
public boolean isOnAccessList(OfflinePlayer player) { public boolean isOnAccessList(OfflinePlayer player) {
return accessList.contains(player.getUniqueId()); return this.accessList.contains(player.getUniqueId());
} }
public void clearAccessList() { public void clearAccessList() {
accessList.clear(); this.accessList.clear();
} }
public List<Location> getRadius(boolean overHeat) { public List<Location> getRadius(boolean overHeat) {
if (overHeat) if (overHeat) {
return radiusOverheat.isEmpty() ? null : Collections.unmodifiableList(radiusOverheat); return this.radiusOverheat.isEmpty() ? null : Collections.unmodifiableList(this.radiusOverheat);
else } else {
return radiusFuelshare.isEmpty() ? null : Collections.unmodifiableList(radiusFuelshare); return this.radiusFuelshare.isEmpty() ? null : Collections.unmodifiableList(this.radiusFuelshare);
}
} }
public void addToRadius(Location location, boolean overHeat) { public void addToRadius(Location location, boolean overHeat) {
if (overHeat) if (overHeat) {
radiusOverheat.add(location); this.radiusOverheat.add(location);
else } else {
radiusFuelshare.add(location); this.radiusFuelshare.add(location);
}
} }
public void clearRadius(boolean overHeat) { public void clearRadius(boolean overHeat) {
if (overHeat) if (overHeat) {
radiusOverheat.clear(); this.radiusOverheat.clear();
else } else {
radiusFuelshare.clear(); this.radiusFuelshare.clear();
}
} }
public int getRadiusLast(boolean overHeat) { public int getRadiusLast(boolean overHeat) {
if (overHeat) if (overHeat) {
return radiusOverheatLast; return this.radiusOverheatLast;
else } else {
return radiusFuelshareLast; return this.radiusFuelshareLast;
}
} }
public void setRadiusLast(int radiusLast, boolean overHeat) { public void setRadiusLast(int radiusLast, boolean overHeat) {
if (overHeat) if (overHeat) {
this.radiusOverheatLast = radiusLast; this.radiusOverheatLast = radiusLast;
else } else {
this.radiusFuelshareLast = radiusLast; this.radiusFuelshareLast = radiusLast;
}
} }
public Location getLocation() { public Location getLocation() {
return location.clone(); return this.location.clone();
} }
public boolean isInLoadedChunk() { public boolean isInLoadedChunk() {
return location != null && location.getWorld() != null && location.getWorld().isChunkLoaded(((int) location.getX()) >> 4, ((int) location.getZ()) >> 4); return this.location != null && this.location.getWorld() != null && this.location.getWorld().isChunkLoaded(((int) this.location.getX()) >> 4, ((int) this.location.getZ()) >> 4);
} }
public void setLevel(Level level) { public void setLevel(Level level) {
@ -319,7 +345,7 @@ public class Furnace {
} }
public String getNickname() { public String getNickname() {
return nickname; return this.nickname;
} }
public void setNickname(String nickname) { public void setNickname(String nickname) {
@ -327,7 +353,7 @@ public class Furnace {
} }
public UUID getPlacedBy() { public UUID getPlacedBy() {
return placedBy; return this.placedBy;
} }
public void setPlacedBy(UUID placedBy) { public void setPlacedBy(UUID placedBy) {
@ -335,7 +361,7 @@ public class Furnace {
} }
public int getUses() { public int getUses() {
return uses; return this.uses;
} }
public void setUses(int uses) { public void setUses(int uses) {
@ -343,13 +369,14 @@ public class Furnace {
} }
public int getToLevel(CompatibleMaterial material) { public int getToLevel(CompatibleMaterial material) {
if (!this.toLevel.containsKey(material)) if (!this.toLevel.containsKey(material)) {
return 0; return 0;
}
return this.toLevel.get(material); return this.toLevel.get(material);
} }
public Map<CompatibleMaterial, Integer> getToLevel() { public Map<CompatibleMaterial, Integer> getToLevel() {
return Collections.unmodifiableMap(toLevel); return Collections.unmodifiableMap(this.toLevel);
} }
public int addToLevel(CompatibleMaterial material, int amount) { public int addToLevel(CompatibleMaterial material, int amount) {
@ -364,7 +391,7 @@ public class Furnace {
} }
public int getRadiusOverheatLast() { public int getRadiusOverheatLast() {
return radiusOverheatLast; return this.radiusOverheatLast;
} }
public void setRadiusOverheatLast(int radiusOverheatLast) { public void setRadiusOverheatLast(int radiusOverheatLast) {
@ -372,7 +399,7 @@ public class Furnace {
} }
public int getRadiusFuelshareLast() { public int getRadiusFuelshareLast() {
return radiusFuelshareLast; return this.radiusFuelshareLast;
} }
public void setRadiusFuelshareLast(int radiusFuelshareLast) { public void setRadiusFuelshareLast(int radiusFuelshareLast) {
@ -380,7 +407,7 @@ public class Furnace {
} }
public int getId() { public int getId() {
return id; return this.id;
} }
public void setId(int id) { public void setId(int id) {
@ -388,20 +415,25 @@ public class Furnace {
} }
public void dropItems() { public void dropItems() {
FurnaceInventory inventory = (FurnaceInventory) ((InventoryHolder) location.getBlock().getState()).getInventory(); FurnaceInventory inventory = (FurnaceInventory) ((InventoryHolder) this.location.getBlock().getState()).getInventory();
ItemStack fuel = inventory.getFuel(); ItemStack fuel = inventory.getFuel();
ItemStack smelting = inventory.getSmelting(); ItemStack smelting = inventory.getSmelting();
ItemStack result = inventory.getResult(); ItemStack result = inventory.getResult();
World world = location.getWorld(); World world = this.location.getWorld();
if (world == null) return; if (world == null) {
return;
}
if (fuel != null) if (fuel != null) {
world.dropItemNaturally(location, fuel); world.dropItemNaturally(this.location, fuel);
if (smelting != null) }
world.dropItemNaturally(location, smelting); if (smelting != null) {
if (result != null) world.dropItemNaturally(this.location, smelting);
world.dropItemNaturally(location, result); }
if (result != null) {
world.dropItemNaturally(this.location, result);
}
} }
public String getHologramId() { public String getHologramId() {

View File

@ -9,7 +9,6 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public class FurnaceBuilder { public class FurnaceBuilder {
//Level level, String nickname, int uses, int tolevel, List<String> accessList, UUID placedBy //Level level, String nickname, int uses, int tolevel, List<String> accessList, UUID placedBy
private final Furnace furnace; private final Furnace furnace;
@ -34,14 +33,16 @@ public class FurnaceBuilder {
} }
public FurnaceBuilder setToLevel(Map<CompatibleMaterial, Integer> toLevel) { public FurnaceBuilder setToLevel(Map<CompatibleMaterial, Integer> toLevel) {
for (Map.Entry<CompatibleMaterial, Integer> entry : toLevel.entrySet()) for (Map.Entry<CompatibleMaterial, Integer> entry : toLevel.entrySet()) {
this.furnace.addToLevel(entry.getKey(), entry.getValue()); this.furnace.addToLevel(entry.getKey(), entry.getValue());
}
return this; return this;
} }
public FurnaceBuilder setAccessList(List<UUID> accessList) { public FurnaceBuilder setAccessList(List<UUID> accessList) {
for (UUID uuid : accessList) for (UUID uuid : accessList) {
this.furnace.addToAccessList(uuid); this.furnace.addToAccessList(uuid);
}
return this; return this;
} }

View File

@ -13,13 +13,12 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class FurnaceManager { public class FurnaceManager {
private final Map<Location, Furnace> registeredFurnaces = new HashMap<>(); private final Map<Location, Furnace> registeredFurnaces = new HashMap<>();
private final Multimap<GameArea, Furnace> tickingFurnaces = MultimapBuilder.hashKeys().hashSetValues().build(); private final Multimap<GameArea, Furnace> tickingFurnaces = MultimapBuilder.hashKeys().hashSetValues().build();
public Furnace addFurnace(Furnace furnace) { public Furnace addFurnace(Furnace furnace) {
tickingFurnaces.put(GameArea.of(furnace.getLocation()), furnace); this.tickingFurnaces.put(GameArea.of(furnace.getLocation()), furnace);
return registeredFurnaces.put(roundLocation(furnace.getLocation()), furnace); return this.registeredFurnaces.put(roundLocation(furnace.getLocation()), furnace);
} }
public void addFurnaces(Collection<Furnace> furnaces) { public void addFurnaces(Collection<Furnace> furnaces) {
@ -29,22 +28,22 @@ public class FurnaceManager {
} }
public Furnace removeFurnace(Location location) { public Furnace removeFurnace(Location location) {
Furnace furnace = registeredFurnaces.remove(location); Furnace furnace = this.registeredFurnaces.remove(location);
if (furnace != null) { if (furnace != null) {
tickingFurnaces.remove(GameArea.of(furnace.getLocation()), furnace); this.tickingFurnaces.remove(GameArea.of(furnace.getLocation()), furnace);
} }
return furnace; return furnace;
} }
public Furnace getFurnace(Location location) { public Furnace getFurnace(Location location) {
if (!Settings.ALLOW_NORMAL_FURNACES.getBoolean() && !registeredFurnaces.containsKey(location)) { if (!Settings.ALLOW_NORMAL_FURNACES.getBoolean() && !this.registeredFurnaces.containsKey(location)) {
addFurnace(new FurnaceBuilder(location).build()); addFurnace(new FurnaceBuilder(location).build());
} }
return registeredFurnaces.get(location); return this.registeredFurnaces.get(location);
} }
public Collection<Furnace> getFurnaces(GameArea gameArea) { public Collection<Furnace> getFurnaces(GameArea gameArea) {
return tickingFurnaces.get(gameArea); return this.tickingFurnaces.get(gameArea);
} }
public Furnace getFurnace(Block block) { public Furnace getFurnace(Block block) {
@ -52,7 +51,7 @@ public class FurnaceManager {
} }
public Map<Location, Furnace> getFurnaces() { public Map<Location, Furnace> getFurnaces() {
return Collections.unmodifiableMap(registeredFurnaces); return Collections.unmodifiableMap(this.registeredFurnaces);
} }
private Location roundLocation(Location location) { private Location roundLocation(Location location) {

View File

@ -10,14 +10,19 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class Level { public class Level {
private final int level;
private final int costExperience;
private final int costEconomy;
private final int performance;
private final int fuelDuration;
private final int overheat;
private final int fuelShare;
private int level, costExperience, costEconomy, performance, fuelDuration, overheat, fuelShare; private Map<CompatibleMaterial, Integer> materials;
private Map<CompatibleMaterial, Integer> materials = new LinkedHashMap<>(); private final String reward;
private String reward; private final List<String> description = new ArrayList<>();
private List<String> description = new ArrayList<>();
Level(int level, int costExperience, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare, Map<CompatibleMaterial, Integer> materials) { Level(int level, int costExperience, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare, Map<CompatibleMaterial, Integer> materials) {
this.level = level; this.level = level;
@ -30,75 +35,90 @@ public class Level {
this.fuelShare = fuelShare; this.fuelShare = fuelShare;
this.materials = materials; this.materials = materials;
EpicFurnaces plugin = EpicFurnaces.getInstance(); EpicFurnaces plugin = EpicFurnaces.getPlugin(EpicFurnaces.class);
if (performance != 0) if (performance != 0) {
description.add(plugin.getLocale().getMessage("interface.furnace.performance") this.description.add(plugin.getLocale()
.processPlaceholder("amount", performance + "%").getMessage()); .getMessage("interface.furnace.performance")
.processPlaceholder("amount", performance + "%")
.getMessage());
}
if (reward != null) if (reward != null) {
description.add(plugin.getLocale().getMessage("interface.furnace.reward") this.description.add(plugin.getLocale()
.processPlaceholder("amount", reward.split("%:")[0] + "%").getMessage()); .getMessage("interface.furnace.reward")
.processPlaceholder("amount", reward.split("%:")[0] + "%")
.getMessage());
}
if (fuelDuration != 0) if (fuelDuration != 0) {
description.add(plugin.getLocale().getMessage("interface.furnace.fuelduration") this.description.add(plugin.getLocale()
.processPlaceholder("amount", fuelDuration + "%").getMessage()); .getMessage("interface.furnace.fuelduration")
.processPlaceholder("amount", fuelDuration + "%")
.getMessage());
}
if (fuelShare != 0) if (fuelShare != 0) {
description.add(plugin.getLocale().getMessage("interface.furnace.fuelshare") this.description.add(plugin.getLocale()
.processPlaceholder("amount", fuelShare).getMessage()); .getMessage("interface.furnace.fuelshare")
.processPlaceholder("amount", fuelShare)
.getMessage());
}
if (overheat != 0) if (overheat != 0) {
description.add(plugin.getLocale().getMessage("interface.furnace.overheat") this.description.add(plugin.getLocale()
.processPlaceholder("amount", overheat).getMessage()); .getMessage("interface.furnace.overheat")
.processPlaceholder("amount", overheat)
.getMessage());
}
} }
public List<String> getDescription() { public List<String> getDescription() {
return new ArrayList<>(description); return new ArrayList<>(this.description);
} }
public int getLevel() { public int getLevel() {
return level; return this.level;
} }
public int getPerformance() { public int getPerformance() {
return performance; return this.performance;
} }
public String getReward() { public String getReward() {
return reward; return this.reward;
} }
public int getOverheat() { public int getOverheat() {
return overheat; return this.overheat;
} }
public int getFuelShare() { public int getFuelShare() {
return fuelShare; return this.fuelShare;
} }
public int getFuelDuration() { public int getFuelDuration() {
return fuelDuration; return this.fuelDuration;
} }
public int getCostExperience() { public int getCostExperience() {
return costExperience; return this.costExperience;
} }
public int getCostEconomy() { public int getCostEconomy() {
return costEconomy; return this.costEconomy;
} }
public Map<CompatibleMaterial, Integer> getMaterials() { public Map<CompatibleMaterial, Integer> getMaterials() {
return Collections.unmodifiableMap(materials); return Collections.unmodifiableMap(this.materials);
} }
} }

View File

@ -8,41 +8,36 @@ 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 performance, String reward, int fuelDuration, int overheat, int fuelShare, Map<CompatibleMaterial, Integer> materials) {
public void addLevel(int level, int costExperiance, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare, Map<CompatibleMaterial, Integer> materials) { this.registeredLevels.put(level, new Level(level, costExperience, costEconomy, performance, reward, fuelDuration, overheat, fuelShare, materials));
registeredLevels.put(level, new Level(level, costExperiance, costEconomy, performance, reward, fuelDuration, overheat, fuelShare, materials));
} }
public Level getLevel(int level) { public Level getLevel(int level) {
return registeredLevels.get(level); return this.registeredLevels.get(level);
} }
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

@ -4,6 +4,9 @@ import com.songoda.core.compatibility.CompatibleMaterial;
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.input.ChatPrompt; import com.songoda.core.input.ChatPrompt;
import com.songoda.core.utils.NumberUtils;
import com.songoda.core.utils.TextUtils;
import com.songoda.core.utils.TimeUtils;
import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.boost.BoostData; import com.songoda.epicfurnaces.boost.BoostData;
import com.songoda.epicfurnaces.furnace.Furnace; import com.songoda.epicfurnaces.furnace.Furnace;
@ -24,7 +27,6 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
public class GUIOverview extends CustomizableGui { public class GUIOverview extends CustomizableGui {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
private final Furnace furnace; private final Furnace furnace;
private final Player player; private final Player player;
@ -42,7 +44,7 @@ public class GUIOverview extends CustomizableGui {
setTitle(Methods.formatName(furnace.getLevel().getLevel())); setTitle(Methods.formatName(furnace.getLevel().getLevel()));
runTask(); runTask();
constructGUI(); constructGUI();
this.setOnClose(action -> Bukkit.getScheduler().cancelTask(task)); this.setOnClose(action -> Bukkit.getScheduler().cancelTask(this.task));
} }
private void constructGUI() { private void constructGUI() {
@ -58,15 +60,15 @@ 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);
Level level = furnace.getLevel(); Level level = this.furnace.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;
// main furnace information icon // main furnace information icon
setItem("information",1, 4, GuiUtils.createButtonItem( setItem("information", 1, 4, GuiUtils.createButtonItem(
CompatibleMaterial.getMaterial(furnace.getLocation().getBlock().getType()), CompatibleMaterial.getMaterial(this.furnace.getLocation().getBlock().getType()),
plugin.getLocale().getMessage("interface.furnace.currentlevel") this.plugin.getLocale().getMessage("interface.furnace.currentlevel")
.processPlaceholder("level", level.getLevel()).getMessage(), .processPlaceholder("level", level.getLevel()).getMessage(),
getFurnaceDescription(furnace, level, nextLevel))); getFurnaceDescription(this.furnace, level, nextLevel)));
// check how many info icons we have to show // check how many info icons we have to show
int num = -1; int num = -1;
@ -89,142 +91,144 @@ public class GUIOverview extends CustomizableGui {
int current = 0; int current = 0;
if (level.getPerformance() != 0) { if (level.getPerformance() != 0) {
setItem("performance", infoIconOrder[num][current++], GuiUtils.createButtonItem( setItem("performance", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.PERFORMANCE_ICON.getMaterial(CompatibleMaterial.REDSTONE), Settings.PERFORMANCE_ICON.getMaterial(CompatibleMaterial.REDSTONE),
plugin.getLocale().getMessage("interface.furnace.performancetitle").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.performancetitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.performanceinfo") this.plugin.getLocale().getMessage("interface.furnace.performanceinfo")
.processPlaceholder("amount", level.getPerformance()).getMessage().split("\\|"))); .processPlaceholder("amount", level.getPerformance()).getMessage().split("\\|")));
} }
if (level.getReward() != null) { if (level.getReward() != null) {
setItem("reward", infoIconOrder[num][current++], GuiUtils.createButtonItem( setItem("reward", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.REWARD_ICON.getMaterial(CompatibleMaterial.GOLDEN_APPLE), Settings.REWARD_ICON.getMaterial(CompatibleMaterial.GOLDEN_APPLE),
plugin.getLocale().getMessage("interface.furnace.rewardtitle").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.rewardtitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.rewardinfo") this.plugin.getLocale().getMessage("interface.furnace.rewardinfo")
.processPlaceholder("amount", level.getReward().split(":")[0].replace("%", "")) .processPlaceholder("amount", level.getReward().split(":")[0].replace("%", ""))
.getMessage().split("\\|"))); .getMessage().split("\\|")));
} }
if (level.getFuelDuration() != 0) { if (level.getFuelDuration() != 0) {
setItem("fuel", infoIconOrder[num][current++], GuiUtils.createButtonItem( setItem("fuel", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.FUEL_DURATION_ICON.getMaterial(CompatibleMaterial.COAL), Settings.FUEL_DURATION_ICON.getMaterial(CompatibleMaterial.COAL),
plugin.getLocale().getMessage("interface.furnace.fueldurationtitle").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.fueldurationtitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.fueldurationinfo") this.plugin.getLocale().getMessage("interface.furnace.fueldurationinfo")
.processPlaceholder("amount", level.getFuelDuration()) .processPlaceholder("amount", level.getFuelDuration())
.getMessage().split("\\|"))); .getMessage().split("\\|")));
} }
if (level.getFuelShare() != 0) { if (level.getFuelShare() != 0) {
setItem("fuel_share", infoIconOrder[num][current++], GuiUtils.createButtonItem( setItem("fuel_share", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.FUEL_SHARE_ICON.getMaterial(CompatibleMaterial.COAL_BLOCK), Settings.FUEL_SHARE_ICON.getMaterial(CompatibleMaterial.COAL_BLOCK),
plugin.getLocale().getMessage("interface.furnace.fuelsharetitle").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.fuelsharetitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.fuelshareinfo") this.plugin.getLocale().getMessage("interface.furnace.fuelshareinfo")
.processPlaceholder("amount", level.getOverheat() * 3) .processPlaceholder("amount", level.getOverheat() * 3)
.getMessage().split("\\|"))); .getMessage().split("\\|")));
} }
if (level.getOverheat() != 0) { if (level.getOverheat() != 0) {
setItem("overheat", infoIconOrder[num][current++], GuiUtils.createButtonItem( setItem("overheat", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.OVERHEAT_ICON.getMaterial(CompatibleMaterial.FIRE_CHARGE), Settings.OVERHEAT_ICON.getMaterial(CompatibleMaterial.FIRE_CHARGE),
plugin.getLocale().getMessage("interface.furnace.overheattitle").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.overheattitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.overheatinfo") this.plugin.getLocale().getMessage("interface.furnace.overheatinfo")
.processPlaceholder("amount", level.getOverheat() * 3) .processPlaceholder("amount", level.getOverheat() * 3)
.getMessage().split("\\|"))); .getMessage().split("\\|")));
} }
// remote control // remote control
if (Settings.REMOTE.getBoolean() && player.hasPermission("EpicFurnaces.Remote")) { if (Settings.REMOTE.getBoolean() && this.player.hasPermission("EpicFurnaces.Remote")) {
setButton("remote", 4, GuiUtils.createButtonItem( setButton("remote", 4, GuiUtils.createButtonItem(
CompatibleMaterial.TRIPWIRE_HOOK, CompatibleMaterial.TRIPWIRE_HOOK,
plugin.getLocale().getMessage("interface.furnace.remotefurnace").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.remotefurnace").getMessage(),
getFurnaceRemoteLore(furnace)), getFurnaceRemoteLore(this.furnace)),
ClickType.LEFT, (event) -> { ClickType.LEFT, (event) -> {
ChatPrompt.showPrompt(plugin, event.player, plugin.getLocale().getMessage("event.remote.enter").getMessage(), ChatPrompt.showPrompt(this.plugin, event.player, this.plugin.getLocale().getMessage("event.remote.enter").getMessage(),
promptEvent -> { promptEvent -> {
for (Furnace other : plugin.getFurnaceManager().getFurnaces().values()) { for (Furnace other : this.plugin.getFurnaceManager().getFurnaces().values()) {
if (other.getNickname() == null) { if (other.getNickname() == null) {
continue; continue;
} }
if (other.getNickname().equalsIgnoreCase(promptEvent.getMessage())) { if (other.getNickname().equalsIgnoreCase(promptEvent.getMessage())) {
plugin.getLocale().getMessage("event.remote.nicknameinuse").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.remote.nicknameinuse").sendPrefixedMessage(this.player);
return; return;
} }
} }
plugin.getDataManager().queueFurnaceForUpdate(furnace); this.plugin.getDataManager().queueFurnaceForUpdate(this.furnace);
furnace.setNickname(promptEvent.getMessage()); this.furnace.setNickname(promptEvent.getMessage());
plugin.getLocale().getMessage("event.remote.nicknamesuccess").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.remote.nicknamesuccess").sendPrefixedMessage(this.player);
}).setOnClose(() -> guiManager.showGUI(player, new GUIOverview(plugin, furnace, player))); }).setOnClose(() -> this.guiManager.showGUI(this.player, new GUIOverview(this.plugin, this.furnace, this.player)));
}).setAction(4, ClickType.RIGHT, (event) -> { }).setAction(4, ClickType.RIGHT, (event) -> {
guiManager.showGUI(player, new GUIRemoteAccess(plugin, furnace, player)); this.guiManager.showGUI(this.player, new GUIRemoteAccess(this.plugin, this.furnace, this.player));
}); });
} }
if (Settings.UPGRADE_WITH_XP.getBoolean() if (Settings.UPGRADE_WITH_XP.getBoolean()
&& level.getCostExperience() != -1 && level.getCostExperience() != -1
&& player.hasPermission("EpicFurnaces.Upgrade.XP")) { && this.player.hasPermission("EpicFurnaces.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.furnace.upgradewithxp").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.upgradewithxp").getMessage(),
nextLevel != null nextLevel != null
? plugin.getLocale().getMessage("interface.furnace.upgradewithxplore") ? this.plugin.getLocale().getMessage("interface.furnace.upgradewithxplore")
.processPlaceholder("cost", nextLevel.getCostExperience()).getMessage() .processPlaceholder("cost", nextLevel.getCostExperience()).getMessage()
: plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()), : this.plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()),
(event) -> { (event) -> {
furnace.upgrade(player, CostType.EXPERIENCE); this.furnace.upgrade(this.player, CostType.EXPERIENCE);
furnace.overview(guiManager, player); this.furnace.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("EpicFurnaces.Upgrade.ECO")) { && this.player.hasPermission("EpicFurnaces.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.furnace.upgradewitheconomy").getMessage(), this.plugin.getLocale().getMessage("interface.furnace.upgradewitheconomy").getMessage(),
nextLevel != null nextLevel != null
? plugin.getLocale().getMessage("interface.furnace.upgradewitheconomylore") ? this.plugin.getLocale().getMessage("interface.furnace.upgradewitheconomylore")
.processPlaceholder("cost", Methods.formatEconomy(nextLevel.getCostEconomy())).getMessage() .processPlaceholder("cost", NumberUtils.formatNumber(nextLevel.getCostEconomy())).getMessage()
: plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()), : this.plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()),
(event) -> { (event) -> {
furnace.upgrade(player, CostType.ECONOMY); this.furnace.upgrade(this.player, CostType.ECONOMY);
furnace.overview(guiManager, player); this.furnace.overview(this.guiManager, this.player);
}); });
} }
} }
private void runTask() { private void runTask() {
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> { this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(this.plugin, () -> {
if (inventory.getViewers().size() != 0) if (this.inventory.getViewers().size() != 0) {
this.constructGUI(); this.constructGUI();
}
}, 5L, 5L); }, 5L, 5L);
} }
List<String> getFurnaceDescription(Furnace furnace, Level level, Level nextLevel) { List<String> getFurnaceDescription(Furnace furnace, Level level, Level nextLevel) {
ArrayList<String> lore = new ArrayList<>(); ArrayList<String> lore = new ArrayList<>();
lore.add(plugin.getLocale().getMessage("interface.furnace.smeltedx") lore.add(this.plugin.getLocale().getMessage("interface.furnace.smeltedx")
.processPlaceholder("amount", furnace.getUses()).getMessage()); .processPlaceholder("amount", furnace.getUses()).getMessage());
lore.addAll(level.getDescription()); lore.addAll(level.getDescription());
lore.add(""); lore.add("");
if (nextLevel == null) { if (nextLevel == null) {
lore.add(plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()); lore.add(this.plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage());
} else { } else {
lore.add(plugin.getLocale().getMessage("interface.furnace.level") lore.add(this.plugin.getLocale().getMessage("interface.furnace.level")
.processPlaceholder("level", nextLevel.getLevel()).getMessage()); .processPlaceholder("level", nextLevel.getLevel()).getMessage());
lore.addAll(nextLevel.getDescription()); lore.addAll(nextLevel.getDescription());
if (Settings.UPGRADE_BY_SMELTING.getBoolean()) { if (Settings.UPGRADE_BY_SMELTING.getBoolean()) {
lore.add(plugin.getLocale().getMessage("interface.furnace.itemsneeded").getMessage()); lore.add(this.plugin.getLocale().getMessage("interface.furnace.itemsneeded").getMessage());
for (Map.Entry<CompatibleMaterial, Integer> entry : level.getMaterials().entrySet()) for (Map.Entry<CompatibleMaterial, Integer> entry : level.getMaterials().entrySet()) {
lore.add(plugin.getLocale().getMessage("interface.furnace.neededitem") lore.add(this.plugin.getLocale().getMessage("interface.furnace.neededitem")
.processPlaceholder("amount", entry.getValue() - furnace.getToLevel(entry.getKey())) .processPlaceholder("amount", entry.getValue() - furnace.getToLevel(entry.getKey()))
.processPlaceholder("type", Methods.cleanString(entry.getKey().name())) .processPlaceholder("type", Methods.cleanString(entry.getKey().name()))
.getMessage()); .getMessage());
}
} }
} }
BoostData boostData = plugin.getBoostManager().getBoost(furnace.getPlacedBy()); BoostData boostData = this.plugin.getBoostManager().getBoost(furnace.getPlacedBy());
if (boostData != null) { if (boostData != null) {
lore.addAll(Arrays.asList(plugin.getLocale().getMessage("interface.button.boostedstats") lore.addAll(Arrays.asList(this.plugin.getLocale().getMessage("interface.button.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("\\|")));
} }
return lore; return lore;
@ -232,20 +236,20 @@ public class GUIOverview extends CustomizableGui {
List<String> getFurnaceRemoteLore(Furnace furnace) { List<String> getFurnaceRemoteLore(Furnace furnace) {
String nickname = furnace.getNickname(); String nickname = furnace.getNickname();
ArrayList<String> lorehook = new ArrayList<>(Arrays.asList(plugin.getLocale().getMessage("interface.furnace.remotefurnacelore") ArrayList<String> loreHook = new ArrayList<>(Arrays.asList(this.plugin.getLocale().getMessage("interface.furnace.remotefurnacelore")
.processPlaceholder("nickname", nickname == null ? "Unset" : nickname).getMessage().split("\\|"))); .processPlaceholder("nickname", nickname == null ? "Unset" : nickname).getMessage().split("\\|")));
if (nickname != null) { if (nickname != null) {
lorehook.addAll(Arrays.asList(plugin.getLocale().getMessage("interface.furnace.utilize") loreHook.addAll(Arrays.asList(this.plugin.getLocale().getMessage("interface.furnace.utilize")
.processPlaceholder("nickname", nickname).getMessage().split("\\|"))); .processPlaceholder("nickname", nickname).getMessage().split("\\|")));
} }
lorehook.add(""); loreHook.add("");
lorehook.add(plugin.getLocale().getMessage("interface.furnace.remotelist").getMessage()); loreHook.add(this.plugin.getLocale().getMessage("interface.furnace.remotelist").getMessage());
for (UUID uuid : furnace.getAccessList()) { for (UUID uuid : furnace.getAccessList()) {
OfflinePlayer remotePlayer = Bukkit.getOfflinePlayer(uuid); OfflinePlayer remotePlayer = Bukkit.getOfflinePlayer(uuid);
lorehook.add(Methods.formatText("&6" + remotePlayer.getName())); loreHook.add(TextUtils.formatText("&6" + remotePlayer.getName()));
} }
return lorehook; return loreHook;
} }
} }

View File

@ -21,7 +21,6 @@ import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class GUIRemoteAccess extends CustomizableGui { public class GUIRemoteAccess extends CustomizableGui {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
private final Furnace furnace; private final Furnace furnace;
private final Player player; private final Player player;
@ -52,59 +51,61 @@ public class GUIRemoteAccess extends CustomizableGui {
mirrorFill("mirrorfill_4", 1, 0, true, true, glass2); mirrorFill("mirrorfill_4", 1, 0, true, true, glass2);
mirrorFill("mirrorfill_5", 0, 1, true, true, glass2); mirrorFill("mirrorfill_5", 0, 1, true, true, glass2);
pages = (int) Math.max(1, Math.ceil(furnace.getAccessList().size() / ((double) 28))); this.pages = (int) Math.max(1, Math.ceil(this.furnace.getAccessList().size() / ((double) 28)));
setNextPage(5, 7, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, plugin.getLocale().getMessage("general.nametag.next").getMessage())); setNextPage(5, 7, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, this.plugin.getLocale().getMessage("general.nametag.next").getMessage()));
setPrevPage(5, 1, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, plugin.getLocale().getMessage("general.nametag.back").getMessage())); setPrevPage(5, 1, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, this.plugin.getLocale().getMessage("general.nametag.back").getMessage()));
setOnPage((event) -> showPage()); setOnPage((event) -> showPage());
setButton("exit", 8, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR, setButton("exit", 8, GuiUtils.createButtonItem(CompatibleMaterial.OAK_DOOR,
plugin.getLocale().getMessage("general.nametag.exit").getMessage()), (event) -> player.closeInventory()); this.plugin.getLocale().getMessage("general.nametag.exit").getMessage()), (event) -> this.player.closeInventory());
setButton("addplayer", 4, GuiUtils.createButtonItem(CompatibleMaterial.EMERALD, setButton("addplayer", 4, GuiUtils.createButtonItem(CompatibleMaterial.EMERALD,
plugin.getLocale().getMessage("interface.remoteaccess.addplayertitle").getMessage()), (event) -> { this.plugin.getLocale().getMessage("interface.remoteaccess.addplayertitle").getMessage()), (event) -> {
plugin.getLocale().getMessage("event.remote.enterplayer").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.remote.enterplayer").sendPrefixedMessage(this.player);
ChatPrompt.showPrompt(plugin, player, chat -> { ChatPrompt.showPrompt(this.plugin, this.player, chat -> {
Player toAdd = Bukkit.getPlayer(chat.getMessage()); Player toAdd = Bukkit.getPlayer(chat.getMessage());
if (toAdd == null) { if (toAdd == null) {
plugin.getLocale().getMessage("event.remote.invalidplayer").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.remote.invalidplayer").sendPrefixedMessage(this.player);
return; return;
} }
if (furnace.getAccessList().contains(toAdd.getUniqueId())) { if (this.furnace.getAccessList().contains(toAdd.getUniqueId())) {
plugin.getLocale().getMessage("event.remote.playeralreadyadded").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.remote.playeralreadyadded").sendPrefixedMessage(this.player);
return; return;
} }
furnace.addToAccessList(toAdd); this.furnace.addToAccessList(toAdd);
plugin.getDataManager().createAccessPlayer(furnace, toAdd.getUniqueId()); this.plugin.getDataManager().createAccessPlayer(this.furnace, toAdd.getUniqueId());
plugin.getLocale().getMessage("event.remote.playeradded").sendPrefixedMessage(player); this.plugin.getLocale().getMessage("event.remote.playeradded").sendPrefixedMessage(this.player);
}).setOnClose(() -> guiManager.showGUI(player, new GUIRemoteAccess(plugin, furnace, player))); }).setOnClose(() -> this.guiManager.showGUI(this.player, new GUIRemoteAccess(this.plugin, this.furnace, this.player)));
}); });
List<UUID> entries = furnace.getAccessList().stream().skip((page - 1) * 28).limit(28).collect(Collectors.toList()); List<UUID> entries = this.furnace.getAccessList().stream().skip((this.page - 1) * 28).limit(28).collect(Collectors.toList());
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> { Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
int num = 11; int num = 11;
for (UUID entry : entries) { for (UUID entry : entries) {
if (num == 16 || num == 36) if (num == 16 || num == 36) {
num = num + 2; num = num + 2;
}
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(entry); OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(entry);
ItemStack itemStack = GuiUtils.createButtonItem(CompatibleMaterial.PLAYER_HEAD, TextUtils.formatText("&6" + offlinePlayer.getName()), ItemStack itemStack = GuiUtils.createButtonItem(CompatibleMaterial.PLAYER_HEAD, TextUtils.formatText("&6" + offlinePlayer.getName()),
plugin.getLocale().getMessage("interface.remoteaccess.playerinfo") this.plugin.getLocale().getMessage("interface.remoteaccess.playerinfo")
.getMessage().split("\\|")); .getMessage().split("\\|"));
SkullMeta meta = (SkullMeta)itemStack.getItemMeta(); SkullMeta meta = (SkullMeta) itemStack.getItemMeta();
if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) if (ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13)) {
meta.setOwningPlayer(offlinePlayer); meta.setOwningPlayer(offlinePlayer);
else } else {
meta.setOwner(offlinePlayer.getName()); meta.setOwner(offlinePlayer.getName());
}
itemStack.setItemMeta(meta); itemStack.setItemMeta(meta);
setButton(num, itemStack, event -> { setButton(num, itemStack, event -> {
furnace.removeFromAccessList(entry); this.furnace.removeFromAccessList(entry);
plugin.getDataManager().deleteAccessPlayer(furnace, entry); this.plugin.getDataManager().deleteAccessPlayer(this.furnace, entry);
guiManager.showGUI(player, new GUIRemoteAccess(plugin, furnace, player)); this.guiManager.showGUI(this.player, new GUIRemoteAccess(this.plugin, this.furnace, this.player));
}); });
num++; num++;
} }

View File

@ -1,34 +1,31 @@
package com.songoda.epicfurnaces.handlers; package com.songoda.epicfurnaces.handlers;
import com.songoda.core.configuration.Config; import com.songoda.core.configuration.Config;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
/**
* Created by songoda on 2/25/2017.
*/
public class BlacklistHandler { public class BlacklistHandler {
private final Config blackConfig;
private final Config blackConfig = new Config(EpicFurnaces.getInstance(), "blacklist.yml"); public BlacklistHandler(Plugin plugin) {
this.blackConfig = new Config(plugin, "blacklist.yml");
public BlacklistHandler() {
loadBlacklistFile(); loadBlacklistFile();
} }
public boolean isBlacklisted(World world) { public boolean isBlacklisted(World world) {
List<String> list = blackConfig.getStringList("settings.blacklist"); List<String> list = this.blackConfig.getStringList("settings.blacklist");
final String checkWorld = world.getName(); final String checkWorld = world.getName();
return list.stream().anyMatch(w -> w.equalsIgnoreCase(checkWorld)); return list.stream().anyMatch(w -> w.equalsIgnoreCase(checkWorld));
} }
private void loadBlacklistFile() { private void loadBlacklistFile() {
blackConfig.addDefault("settings.blacklist", Arrays.asList("world2", "world3", "world4", "world5")); this.blackConfig.addDefault("settings.blacklist", Arrays.asList("world2", "world3", "world4", "world5"));
blackConfig.load(); this.blackConfig.load();
blackConfig.saveChanges(); this.blackConfig.saveChanges();
} }
public void reload() { public void reload() {

View File

@ -1,6 +1,5 @@
package com.songoda.epicfurnaces.listeners; package com.songoda.epicfurnaces.listeners;
import com.songoda.core.hooks.HologramManager;
import com.songoda.core.utils.PlayerUtils; import com.songoda.core.utils.PlayerUtils;
import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.furnace.Furnace; import com.songoda.epicfurnaces.furnace.Furnace;
@ -22,11 +21,7 @@ import org.bukkit.inventory.ItemStack;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
/**
* Created by songoda on 2/26/2017.
*/
public class BlockListeners implements Listener { public class BlockListeners implements Listener {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
public BlockListeners(EpicFurnaces plugin) { public BlockListeners(EpicFurnaces plugin) {
@ -37,15 +32,19 @@ public class BlockListeners implements Listener {
public void onSnowLand(BlockFormEvent event) { public void onSnowLand(BlockFormEvent event) {
Material material = event.getNewState().getType(); Material material = event.getNewState().getType();
if (material != Material.SNOW && material != Material.ICE) return; if (material != Material.SNOW && material != Material.ICE) {
return;
}
for (Furnace furnace : plugin.getFurnaceManager().getFurnaces(GameArea.of(event.getBlock().getLocation()))) { for (Furnace furnace : this.plugin.getFurnaceManager().getFurnaces(GameArea.of(event.getBlock().getLocation()))) {
List<Location> radius = furnace.getRadius(false); List<Location> radius = furnace.getRadius(false);
if (radius == null || ((org.bukkit.block.Furnace) furnace.getLocation().getBlock().getState()).getBurnTime() == 0) if (radius == null || ((org.bukkit.block.Furnace) furnace.getLocation().getBlock().getState()).getBurnTime() == 0) {
continue; continue;
}
for (Location location : radius) { for (Location location : radius) {
if (location.getX() != event.getNewState().getX() || location.getY() != event.getNewState().getY() || location.getZ() != event.getNewState().getZ()) if (location.getX() != event.getNewState().getX() || location.getY() != event.getNewState().getY() || location.getZ() != event.getNewState().getZ()) {
continue; continue;
}
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
@ -54,29 +53,31 @@ public class BlockListeners implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) { public void onBlockPlace(BlockPlaceEvent event) {
if (this.plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld())
if (plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld()) || !event.getBlock().getType().name().contains("FURNACE") && !event.getBlock().getType().name().contains("SMOKER")) {
|| !event.getBlock().getType().name().contains("FURNACE") && !event.getBlock().getType().name().contains("SMOKER"))
return; return;
}
ItemStack item = event.getItemInHand(); ItemStack item = event.getItemInHand();
Player player = event.getPlayer(); Player player = event.getPlayer();
if (!plugin.isLeveledFurnace(item) && Settings.ALLOW_NORMAL_FURNACES.getBoolean()) { if (!this.plugin.isLeveledFurnace(item) && Settings.ALLOW_NORMAL_FURNACES.getBoolean()) {
return; return;
} }
if (Settings.USE_LIMIT_PERMISSION.getBoolean()) { if (Settings.USE_LIMIT_PERMISSION.getBoolean()) {
int amount = 0; int amount = 0;
for (Furnace furnace : plugin.getFurnaceManager().getFurnaces().values()) { for (Furnace furnace : this.plugin.getFurnaceManager().getFurnaces().values()) {
if (furnace.getPlacedBy() == null || !furnace.getPlacedBy().equals(player.getUniqueId())) continue; if (furnace.getPlacedBy() == null || !furnace.getPlacedBy().equals(player.getUniqueId())) {
continue;
}
amount++; amount++;
} }
int limit = PlayerUtils.getNumberFromPermission(player, "epicfurnaces.limit", -1); int limit = PlayerUtils.getNumberFromPermission(player, "epicfurnaces.limit", -1);
if (limit != -1 && amount >= limit) { if (limit != -1 && amount >= limit) {
event.setCancelled(true); event.setCancelled(true);
plugin.getLocale().getMessage("event.limit.hit") this.plugin.getLocale().getMessage("event.limit.hit")
.processPlaceholder("limit", limit).sendPrefixedMessage(player); .processPlaceholder("limit", limit).sendPrefixedMessage(player);
return; return;
} }
@ -84,17 +85,17 @@ public class BlockListeners implements Listener {
Location location = event.getBlock().getLocation(); Location location = event.getBlock().getLocation();
Furnace furnace = event.getItemInHand().getItemMeta().hasDisplayName() && plugin.getFurnaceLevel(item) != 1 Furnace furnace = event.getItemInHand().getItemMeta().hasDisplayName() && this.plugin.getFurnaceLevel(item) != 1
? new FurnaceBuilder(location) ? new FurnaceBuilder(location)
.setLevel(plugin.getLevelManager().getLevel(plugin.getFurnaceLevel(item))) .setLevel(this.plugin.getLevelManager().getLevel(this.plugin.getFurnaceLevel(item)))
.setUses(plugin.getFurnaceUses(item)) .setUses(this.plugin.getFurnaceUses(item))
.setPlacedBy(event.getPlayer().getUniqueId()).build() .setPlacedBy(event.getPlayer().getUniqueId()).build()
: new FurnaceBuilder(location).setPlacedBy(event.getPlayer().getUniqueId()).build(); : new FurnaceBuilder(location).setPlacedBy(event.getPlayer().getUniqueId()).build();
plugin.getDataManager().createFurnace(furnace); this.plugin.getDataManager().createFurnace(furnace);
plugin.getFurnaceManager().addFurnace(furnace); this.plugin.getFurnaceManager().addFurnace(furnace);
plugin.updateHolograms(Collections.singleton(furnace)); this.plugin.updateHolograms(Collections.singleton(furnace));
} }
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@ -104,32 +105,33 @@ public class BlockListeners implements Listener {
} }
Block block = event.getBlock(); Block block = event.getBlock();
if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER") if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")
|| plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld())) || this.plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld())) {
return; return;
}
Furnace furnace = plugin.getFurnaceManager().getFurnace(block); Furnace furnace = this.plugin.getFurnaceManager().getFurnace(block);
if (furnace == null) { if (furnace == null) {
return; return;
} }
int level = plugin.getFurnaceManager().getFurnace(block).getLevel().getLevel(); int level = this.plugin.getFurnaceManager().getFurnace(block).getLevel().getLevel();
plugin.clearHologram(furnace); this.plugin.clearHologram(furnace);
if (level != 0) { if (level != 0) {
event.setCancelled(true); event.setCancelled(true);
ItemStack item = plugin.createLeveledFurnace(block.getType().name().contains("BURNING") ? Material.FURNACE ItemStack item = this.plugin.createLeveledFurnace(block.getType().name().contains("BURNING") ? Material.FURNACE
: block.getType(), level, furnace.getUses()); : block.getType(), level, furnace.getUses());
// By cancelling the event we destroy any chance of items dropping form the furnace. This fixes the problem. // By canceling the event, we destroy any chance of items dropping from the furnace. This fixes the problem.
//furnace.dropItems(); No need to drop items. dropItemNaturally() will drop the items inside the furnance //furnace.dropItems(); No need to drop items. dropItemNaturally() will drop the items inside the furnace
event.getBlock().setType(Material.AIR); event.getBlock().setType(Material.AIR);
event.getBlock().getLocation().getWorld().dropItemNaturally(event.getBlock().getLocation(), item); event.getBlock().getLocation().getWorld().dropItemNaturally(event.getBlock().getLocation(), item);
} }
plugin.getFurnaceManager().removeFurnace(block.getLocation()); this.plugin.getFurnaceManager().removeFurnace(block.getLocation());
plugin.getDataManager().deleteFurnace(furnace); this.plugin.getDataManager().deleteFurnace(furnace);
} }
} }

View File

@ -9,11 +9,7 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityExplodeEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class EntityListeners implements Listener { public class EntityListeners implements Listener {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
private final FurnaceManager furnaceManager; private final FurnaceManager furnaceManager;
@ -25,11 +21,14 @@ public class EntityListeners implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onBlow(EntityExplodeEvent event) { public void onBlow(EntityExplodeEvent event) {
for (Block block : event.blockList()) { for (Block block : event.blockList()) {
Furnace furnace = furnaceManager.getFurnace(block); Furnace furnace = this.furnaceManager.getFurnace(block);
if (furnace == null) continue; if (furnace == null) {
furnaceManager.removeFurnace(block.getLocation()); continue;
plugin.getDataManager().deleteFurnace(furnace); }
plugin.clearHologram(furnace);
this.furnaceManager.removeFurnace(block.getLocation());
this.plugin.getDataManager().deleteFurnace(furnace);
this.plugin.clearHologram(furnace);
} }
} }
} }

View File

@ -9,11 +9,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.inventory.FurnaceBurnEvent; import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent; import org.bukkit.event.inventory.FurnaceSmeltEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class FurnaceListeners implements Listener { public class FurnaceListeners implements Listener {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
public FurnaceListeners(EpicFurnaces plugin) { public FurnaceListeners(EpicFurnaces plugin) {
@ -23,26 +19,29 @@ public class FurnaceListeners implements Listener {
@EventHandler @EventHandler
public void onCook(FurnaceSmeltEvent event) { public void onCook(FurnaceSmeltEvent event) {
Block block = event.getBlock(); Block block = event.getBlock();
if ((event.getBlock().isBlockPowered() && plugin.getConfig().getBoolean("Main.Redstone Deactivates Furnaces")) || event.getResult() == null) { if ((event.getBlock().isBlockPowered() && this.plugin.getConfig().getBoolean("Main.Redstone Deactivates Furnaces")) || event.getResult() == null) {
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
Furnace furnace = plugin.getFurnaceManager().getFurnace(block.getLocation()); Furnace furnace = this.plugin.getFurnaceManager().getFurnace(block.getLocation());
if (furnace != null) if (furnace != null) {
furnace.plus(event); furnace.plus(event);
}
} }
@EventHandler @EventHandler
public void onFuel(FurnaceBurnEvent event) { public void onFuel(FurnaceBurnEvent event) {
Furnace furnace = plugin.getFurnaceManager().getFurnace(event.getBlock().getLocation()); Furnace furnace = this.plugin.getFurnaceManager().getFurnace(event.getBlock().getLocation());
if (furnace == null) { if (furnace == null) {
return; return;
} }
Level level = furnace.getLevel(); Level level = furnace.getLevel();
if (level.getFuelDuration() != 0) return; if (level.getFuelDuration() != 0) {
return;
}
int num = level.getFuelDuration(); int num = level.getFuelDuration();
int per = (event.getBurnTime() / 100) * num; int per = (event.getBurnTime() / 100) * num;

View File

@ -17,11 +17,7 @@ import org.bukkit.event.Listener;
import org.bukkit.event.block.Action; import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerInteractEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class InteractListeners implements Listener { public class InteractListeners implements Listener {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
private final GuiManager guiManager; private final GuiManager guiManager;
@ -33,9 +29,11 @@ public class InteractListeners implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onClick(PlayerInteractEvent event) { public void onClick(PlayerInteractEvent event) {
final Block block = event.getClickedBlock(); final Block block = event.getClickedBlock();
if (block == null) return; if (block == null) {
return;
}
if (plugin.getBlacklistHandler().isBlacklisted(block.getWorld())) { if (this.plugin.getBlacklistHandler().isBlacklisted(block.getWorld())) {
return; return;
} }
Player player = event.getPlayer(); Player player = event.getPlayer();
@ -50,11 +48,13 @@ public class InteractListeners implements Listener {
if (Bukkit.getPluginManager().isPluginEnabled("FabledSkyBlock")) { if (Bukkit.getPluginManager().isPluginEnabled("FabledSkyBlock")) {
SkyBlock skyBlock = SkyBlock.getInstance(); SkyBlock skyBlock = SkyBlock.getInstance();
if (skyBlock.getWorldManager().isIslandWorld(event.getPlayer().getWorld())) if (skyBlock.getWorldManager().isIslandWorld(event.getPlayer().getWorld())) {
if (!skyBlock.getPermissionManager().hasPermission(event.getPlayer(), if (!skyBlock.getPermissionManager().hasPermission(event.getPlayer(),
skyBlock.getIslandManager().getIslandAtLocation(event.getClickedBlock().getLocation()), skyBlock.getIslandManager().getIslandAtLocation(event.getClickedBlock().getLocation()),
"EpicFurnaces")) "EpicFurnaces")) {
return; return;
}
}
} }
//EpicHoppers compatibility //EpicHoppers compatibility
@ -75,6 +75,6 @@ public class InteractListeners implements Listener {
event.setCancelled(true); event.setCancelled(true);
furnace.overview(guiManager, player); furnace.overview(this.guiManager, player);
} }
} }

View File

@ -11,11 +11,7 @@ import org.bukkit.event.inventory.InventoryMoveItemEvent;
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 2/26/2017.
*/
public class InventoryListeners implements Listener { public class InventoryListeners implements Listener {
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
public InventoryListeners(EpicFurnaces plugin) { public InventoryListeners(EpicFurnaces plugin) {
@ -30,25 +26,25 @@ public class InventoryListeners implements Listener {
|| event.getDestination().getItem(0).getAmount() != 1) { || event.getDestination().getItem(0).getAmount() != 1) {
return; return;
} }
Furnace furnace = plugin.getFurnaceManager().getFurnace(((org.bukkit.block.Furnace) Furnace furnace = this.plugin.getFurnaceManager().getFurnace(((org.bukkit.block.Furnace) event.getDestination().getHolder()).getLocation());
event.getDestination().getHolder()).getLocation()); if (furnace != null) {
if (furnace != null)
furnace.updateCook(); furnace.updateCook();
}
} }
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent event) { public void onInventoryClick(InventoryClickEvent event) {
if (event.getSlot() != 64537) { if (event.getSlot() == 64537 ||
if (event.getInventory().getType() == InventoryType.ANVIL) { event.getInventory().getType() != InventoryType.ANVIL ||
if (event.getAction() != InventoryAction.NOTHING) { event.getAction() == InventoryAction.NOTHING ||
if (event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) { event.getCurrentItem() == null ||
ItemStack item = event.getCurrentItem(); event.getCurrentItem().getType() == Material.AIR) {
if (item.getType().name().contains("FURNACE") && !item.getType().name().contains("SMOKER")) { return;
event.setCancelled(true); }
}
} ItemStack item = event.getCurrentItem();
} if (item.getType().name().contains("FURNACE") && !item.getType().name().contains("SMOKER")) {
} event.setCancelled(true);
} }
} }
} }

View File

@ -8,124 +8,123 @@ import com.songoda.core.hooks.HologramManager;
import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.EpicFurnaces;
public class Settings { public class Settings {
static final Config CONFIG = EpicFurnaces.getPlugin(EpicFurnaces.class).getCoreConfig();
static final Config config = EpicFurnaces.getInstance().getCoreConfig(); public static final ConfigSetting UPGRADE_BY_SMELTING = new ConfigSetting(CONFIG, "Main.Upgrade By Smelting Materials", true);
public static final ConfigSetting UPGRADE_BY_SMELTING = new ConfigSetting(config, "Main.Upgrade By Smelting Materials", true); 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 furnaces with economy?"); "Should you be able to upgrade furnaces 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 furnaces with experience?"); "Should you be able to upgrade furnaces with experience?");
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 FURNACE_AREA = new ConfigSetting(config, "Main.Furnace Area", 1024, public static final ConfigSetting FURNACE_AREA = new ConfigSetting(CONFIG, "Main.Furnace Area", 1024,
"This controls how big a furnace ticking area is.", "This controls how big a furnace ticking area is.",
"Higher size means decreased performance, but less chances of overheat", "Higher size means decreased performance, but less chances of overheat",
"missing a spot. Lower size means better performance, but overheat", "missing a spot. Lower size means better performance, but overheat",
"might leave a few spots. Minimum value is 16. To disable, just set", "might leave a few spots. Minimum value is 16. To disable, just set",
"this to a very high value, such as your worldborder size."); "this to a very high value, such as your worldborder size.");
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 FURNACE_ITEM = new ConfigSetting(config, "Main.Remember Furnace Item Levels", true, public static final ConfigSetting FURNACE_ITEM = new ConfigSetting(CONFIG, "Main.Remember Furnace Item Levels", true,
"Should furnace levels be remembered when broken?"); "Should furnace levels be remembered when broken?");
public static final ConfigSetting HOLOGRAM_PLUGIN = new ConfigSetting(config, "Main.Hologram", public static final ConfigSetting HOLOGRAM_PLUGIN = new ConfigSetting(CONFIG, "Main.Hologram",
HologramManager.getHolograms() == null ? "HolographicDisplays" : HologramManager.getHolograms().getName(), HologramManager.getHolograms() == null ? "HolographicDisplays" : HologramManager.getHolograms().getName(),
"Which hologram plugin should be used?", "Which hologram plugin should be used?",
"You can choose from \"" + String.join(", ", HologramManager.getManager().getRegisteredPlugins()) + "\"."); "You can choose from \"" + String.join(", ", HologramManager.getManager().getRegisteredPlugins()) + "\".");
public static final ConfigSetting HOLOGRAMS = new ConfigSetting(config, "Main.Furnaces Have Holograms", true); public static final ConfigSetting HOLOGRAMS = new ConfigSetting(CONFIG, "Main.Furnaces Have Holograms", true);
public static final ConfigSetting REDSTONE_DEACTIVATES = new ConfigSetting(config, "Main.Redstone Deactivates Furnaces", true); public static final ConfigSetting REDSTONE_DEACTIVATES = new ConfigSetting(CONFIG, "Main.Redstone Deactivates Furnaces", true);
public static final ConfigSetting CUSTOM_RECIPES = new ConfigSetting(config, "Main.Use Custom Recipes", true); public static final ConfigSetting CUSTOM_RECIPES = new ConfigSetting(CONFIG, "Main.Use Custom Recipes", true);
public static final ConfigSetting NO_REWARDS_FROM_RECIPES = new ConfigSetting(config, "Main.No Rewards From Custom Recipes", true); public static final ConfigSetting NO_REWARDS_FROM_RECIPES = new ConfigSetting(CONFIG, "Main.No Rewards From Custom Recipes", true);
public static final ConfigSetting ALLOW_NORMAL_FURNACES = new ConfigSetting(config, "Main.Allow Normal Furnaces", false, public static final ConfigSetting ALLOW_NORMAL_FURNACES = new ConfigSetting(CONFIG, "Main.Allow Normal Furnaces", false,
"Should normal furnaces not be converted into", "Should normal furnaces not be converted into",
"Epic Furnaces?"); "Epic Furnaces?");
public static final ConfigSetting USE_LIMIT_PERMISSION = new ConfigSetting(config, "Main.Use Limit Permission", true, public static final ConfigSetting USE_LIMIT_PERMISSION = new ConfigSetting(CONFIG, "Main.Use Limit Permission", true,
"Should we use the epicfurnaces.limit.<amount>", "Should we use the epicfurnaces.limit.<amount>",
"permission? This will limit the amount of Epic Furnaces", "permission? This will limit the amount of Epic Furnaces",
"a player can place."); "a player can place.");
public static final ConfigSetting PARTICLE_TYPE = new ConfigSetting(config, "Main.Upgrade Particle Type", "SPELL_WITCH", public static final ConfigSetting PARTICLE_TYPE = new ConfigSetting(CONFIG, "Main.Upgrade Particle Type", "SPELL_WITCH",
"The type of particle shown when a furnace is upgraded."); "The type of particle shown when a furnace is upgraded.");
public static final ConfigSetting REMOTE = new ConfigSetting(config, "Main.Access Furnaces Remotely", true); public static final ConfigSetting REMOTE = new ConfigSetting(CONFIG, "Main.Access Furnaces Remotely", true);
public static final ConfigSetting TICK_SPEED = new ConfigSetting(config, "Main.Furnace Tick Speed", 10); public static final ConfigSetting TICK_SPEED = new ConfigSetting(CONFIG, "Main.Furnace Tick Speed", 10);
public static final ConfigSetting OVERHEAT_PARTICLES = new ConfigSetting(config, "Main.Overheat Particles", true); public static final ConfigSetting OVERHEAT_PARTICLES = new ConfigSetting(CONFIG, "Main.Overheat Particles", true);
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: \"" + String.join("\", \"", EconomyManager.getManager().getRegisteredPlugins()) + "\"."); "Supported plugins you have installed: \"" + String.join("\", \"", EconomyManager.getManager().getRegisteredPlugins()) + "\".");
public static final ConfigSetting REWARD_ICON = new ConfigSetting(config, "Interfaces.Reward Icon", "GOLDEN_APPLE"); public static final ConfigSetting REWARD_ICON = new ConfigSetting(CONFIG, "Interfaces.Reward Icon", "GOLDEN_APPLE");
public static final ConfigSetting PERFORMANCE_ICON = new ConfigSetting(config, "Interfaces.Performance Icon", "REDSTONE"); public static final ConfigSetting PERFORMANCE_ICON = new ConfigSetting(CONFIG, "Interfaces.Performance Icon", "REDSTONE");
public static final ConfigSetting FUEL_SHARE_ICON = new ConfigSetting(config, "Interfaces.FuelShare Icon", "COAL_BLOCK"); public static final ConfigSetting FUEL_SHARE_ICON = new ConfigSetting(CONFIG, "Interfaces.FuelShare Icon", "COAL_BLOCK");
public static final ConfigSetting FUEL_DURATION_ICON = new ConfigSetting(config, "Interfaces.FuelDuration Icon", "COAL"); public static final ConfigSetting FUEL_DURATION_ICON = new ConfigSetting(CONFIG, "Interfaces.FuelDuration Icon", "COAL");
public static final ConfigSetting OVERHEAT_ICON = new ConfigSetting(config, "Interfaces.Overheat Icon", "FIRE_CHARGE"); public static final ConfigSetting OVERHEAT_ICON = new ConfigSetting(CONFIG, "Interfaces.Overheat Icon", "FIRE_CHARGE");
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

@ -14,11 +14,9 @@ import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public abstract class Storage { public abstract class Storage {
protected final EpicFurnaces plugin; protected final EpicFurnaces plugin;
protected final Config dataFile; protected final Config dataFile;
public Storage(EpicFurnaces plugin) { public Storage(EpicFurnaces plugin) {
this.plugin = plugin; this.plugin = plugin;
this.dataFile = new Config(plugin, "data.yml"); this.dataFile = new Config(plugin, "data.yml");
@ -72,5 +70,4 @@ public abstract class Storage {
public abstract void makeBackup(); public abstract void makeBackup();
public abstract void closeConnection(); public abstract void closeConnection();
} }

View File

@ -7,7 +7,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class StorageItem { public class StorageItem {
private final Object object; private final Object object;
private String key = null; private String key = null;
@ -40,38 +39,56 @@ public class StorageItem {
} }
public String getKey() { public String getKey() {
return key; return this.key;
} }
public String asString() { public String asString() {
if (object == null) return null; if (this.object == null) {
return (String) object; return null;
}
return (String) this.object;
} }
public boolean asBoolean() { public boolean asBoolean() {
if (object == null) return false; if (this.object == null) {
if (object instanceof Integer) return (Integer) object == 1; return false;
return (boolean) object; }
if (this.object instanceof Integer) {
return (Integer) this.object == 1;
}
return (boolean) this.object;
} }
public int asInt() { public int asInt() {
if (object == null) return 0; if (this.object == null) {
return (int) object; return 0;
}
return (int) this.object;
} }
public Object asObject() { public Object asObject() {
if (object == null) return null; if (this.object == null) {
if (object instanceof Boolean) return (Boolean) object ? 1 : 0; return null;
return object; }
if (this.object instanceof Boolean) {
return (Boolean) this.object ? 1 : 0;
}
return this.object;
} }
public List<String> asStringList() { public List<String> asStringList() {
if (object instanceof ArrayList) return new ArrayList<>(); if (this.object instanceof ArrayList) {
return new ArrayList<>();
}
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
if (object == null) return list; if (this.object == null) {
String[] stack = ((String) object).split(";"); return list;
}
String[] stack = ((String) this.object).split(";");
for (String item : stack) { for (String item : stack) {
if (item.equals("")) continue; if (item.equals("")) {
continue;
}
list.add(item); list.add(item);
} }
return list; return list;

View File

@ -14,15 +14,17 @@ public class StorageRow {
} }
public String getKey() { public String getKey() {
return key; return this.key;
} }
public Map<String, StorageItem> getItems() { public Map<String, StorageItem> getItems() {
return Collections.unmodifiableMap(items); return Collections.unmodifiableMap(this.items);
} }
public StorageItem get(String key) { public StorageItem get(String key) {
if (!items.containsKey(key) || items.get(key).asObject().toString().equals("")) return new StorageItem(null); if (!this.items.containsKey(key) || this.items.get(key).asObject().toString().equals("")) {
return items.get(key); return new StorageItem(null);
}
return this.items.get(key);
} }
} }

View File

@ -13,7 +13,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class StorageYaml extends Storage { public class StorageYaml extends Storage {
private final Map<String, Object> toSave = new HashMap<>(); private final Map<String, Object> toSave = new HashMap<>();
private Map<String, Object> lastSave = null; private Map<String, Object> lastSave = null;
@ -23,23 +22,25 @@ public class StorageYaml extends Storage {
@Override @Override
public boolean containsGroup(String group) { public boolean containsGroup(String group) {
return dataFile.contains("data." + group); return this.dataFile.contains("data." + group);
} }
@Override @Override
public List<StorageRow> getRowsByGroup(String group) { public List<StorageRow> getRowsByGroup(String group) {
List<StorageRow> rows = new ArrayList<>(); List<StorageRow> rows = new ArrayList<>();
ConfigurationSection currentSection = dataFile.getConfigurationSection("data." + group); ConfigurationSection currentSection = this.dataFile.getConfigurationSection("data." + group);
for (String key : currentSection.getKeys(false)) { for (String key : currentSection.getKeys(false)) {
Map<String, StorageItem> items = new HashMap<>(); Map<String, StorageItem> items = new HashMap<>();
ConfigurationSection currentSection2 = dataFile.getConfigurationSection("data." + group + "." + key); ConfigurationSection currentSection2 = this.dataFile.getConfigurationSection("data." + group + "." + key);
for (String key2 : currentSection2.getKeys(false)) { for (String key2 : currentSection2.getKeys(false)) {
String path = "data." + group + "." + key + "." + key2; String path = "data." + group + "." + key + "." + key2;
items.put(key2, new StorageItem(dataFile.get(path) instanceof MemorySection items.put(key2, new StorageItem(this.dataFile.get(path) instanceof MemorySection
? convertToInLineList(path) : dataFile.get(path))); ? convertToInLineList(path) : this.dataFile.get(path)));
}
if (items.isEmpty()) {
continue;
} }
if (items.isEmpty()) continue;
StorageRow row = new StorageRow(key, items); StorageRow row = new StorageRow(key, items);
rows.add(row); rows.add(row);
} }
@ -48,8 +49,8 @@ public class StorageYaml extends Storage {
private String convertToInLineList(String path) { private String convertToInLineList(String path) {
StringBuilder converted = new StringBuilder(); StringBuilder converted = new StringBuilder();
for (String key : dataFile.getConfigurationSection(path).getKeys(false)) { for (String key : this.dataFile.getConfigurationSection(path).getKeys(false)) {
converted.append(key).append(":").append(dataFile.getInt(path + "." + key)).append(";"); converted.append(key).append(":").append(this.dataFile.getInt(path + "." + key)).append(";");
} }
return converted.toString(); return converted.toString();
} }
@ -57,51 +58,56 @@ public class StorageYaml extends Storage {
@Override @Override
public void prepareSaveItem(String group, StorageItem... items) { public void prepareSaveItem(String group, StorageItem... items) {
for (StorageItem item : items) { for (StorageItem item : items) {
if (item == null || item.asObject() == null) continue; if (item == null || item.asObject() == null) {
toSave.put("data." + group + "." + items[0].asString() + "." + item.getKey(), item.asObject()); continue;
}
this.toSave.put("data." + group + "." + items[0].asString() + "." + item.getKey(), item.asObject());
} }
} }
@Override @Override
public void doSave() { public void doSave() {
this.updateData(plugin); this.updateData(this.plugin);
if (lastSave == null) if (this.lastSave == null) {
lastSave = new HashMap<>(toSave); this.lastSave = new HashMap<>(this.toSave);
}
if (toSave.isEmpty()) return; if (this.toSave.isEmpty()) {
Map<String, Object> nextSave = new HashMap<>(toSave); return;
}
Map<String, Object> nextSave = new HashMap<>(this.toSave);
this.makeBackup(); this.makeBackup();
this.save(); this.save();
toSave.clear(); this.toSave.clear();
lastSave.clear(); this.lastSave.clear();
lastSave.putAll(nextSave); this.lastSave.putAll(nextSave);
} }
@Override @Override
public void save() { public void save() {
try { try {
for (Map.Entry<String, Object> entry : lastSave.entrySet()) { for (Map.Entry<String, Object> entry : this.lastSave.entrySet()) {
if (toSave.containsKey(entry.getKey())) { if (this.toSave.containsKey(entry.getKey())) {
Object newValue = toSave.get(entry.getKey()); Object newValue = this.toSave.get(entry.getKey());
if (!entry.getValue().equals(newValue)) { if (!entry.getValue().equals(newValue)) {
dataFile.set(entry.getKey(), newValue); this.dataFile.set(entry.getKey(), newValue);
} }
toSave.remove(entry.getKey()); this.toSave.remove(entry.getKey());
} else { } else {
dataFile.set(entry.getKey(), null); this.dataFile.set(entry.getKey(), null);
} }
} }
for (Map.Entry<String, Object> entry : toSave.entrySet()) { for (Map.Entry<String, Object> entry : this.toSave.entrySet()) {
dataFile.set(entry.getKey(), entry.getValue()); this.dataFile.set(entry.getKey(), entry.getValue());
} }
dataFile.save(); this.dataFile.save();
} catch (NullPointerException e) { } catch (NullPointerException ex) {
e.printStackTrace(); ex.printStackTrace();
} }
} }
@ -111,7 +117,6 @@ public class StorageYaml extends Storage {
@Override @Override
public void closeConnection() { public void closeConnection() {
dataFile.save(); this.dataFile.save();
} }
} }

View File

@ -15,7 +15,6 @@ import java.util.HashSet;
import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.ThreadLocalRandom;
public class FurnaceTask extends BukkitRunnable { public class FurnaceTask extends BukkitRunnable {
private static FurnaceTask instance; private static FurnaceTask instance;
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
@ -37,15 +36,15 @@ public class FurnaceTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
doParticles = Settings.OVERHEAT_PARTICLES.getBoolean(); this.doParticles = Settings.OVERHEAT_PARTICLES.getBoolean();
plugin.getFurnaceManager().getFurnaces().values().stream() this.plugin.getFurnaceManager().getFurnaces().values().stream()
.filter(Furnace::isInLoadedChunk) .filter(Furnace::isInLoadedChunk)
.forEach(furnace -> { .forEach(furnace -> {
Location location = furnace.getLocation(); Location location = furnace.getLocation();
BlockState state = location.getBlock().getState(); BlockState state = location.getBlock().getState();
if (!(state instanceof org.bukkit.block.Furnace)) { if (!(state instanceof org.bukkit.block.Furnace)) {
toRemove.add(location); this.toRemove.add(location);
} else if (((org.bukkit.block.Furnace) state).getBurnTime() != 0) { } else if (((org.bukkit.block.Furnace) state).getBurnTime() != 0) {
if (furnace.getLevel().getOverheat() != 0) { if (furnace.getLevel().getOverheat() != 0) {
overheat(furnace); overheat(furnace);
@ -55,9 +54,9 @@ public class FurnaceTask extends BukkitRunnable {
} }
} }
}); });
if (!toRemove.isEmpty()) { if (!this.toRemove.isEmpty()) {
toRemove.forEach(l -> plugin.getFurnaceManager().removeFurnace(l)); this.toRemove.forEach(location -> this.plugin.getFurnaceManager().removeFurnace(location));
toRemove.clear(); this.toRemove.clear();
} }
} }
@ -69,21 +68,24 @@ public class FurnaceTask extends BukkitRunnable {
for (Location location : furnace.getRadius(true)) { for (Location location : furnace.getRadius(true)) {
int random = ThreadLocalRandom.current().nextInt(0, 10); int random = ThreadLocalRandom.current().nextInt(0, 10);
if (random != 1) {
if (random != 1) continue; continue;
}
Block block = location.getBlock(); Block block = location.getBlock();
if (block.getType() == Material.AIR || block.getRelative(BlockFace.UP).getType() != Material.AIR) {
if (block.getType() == Material.AIR || block.getRelative(BlockFace.UP).getType() != Material.AIR) continue;
if (block.getType() == Material.SNOW)
block.setType(Material.AIR);
else if (block.getType() == Material.ICE || block.getType() == Material.PACKED_ICE)
block.setType(Material.WATER);
else
continue; continue;
}
if (doParticles) { if (block.getType() == Material.SNOW) {
block.setType(Material.AIR);
} else if (block.getType() == Material.ICE || block.getType() == Material.PACKED_ICE) {
block.setType(Material.WATER);
} else {
continue;
}
if (this.doParticles) {
float xx = (float) (0 + (Math.random() * .75)); float xx = (float) (0 + (Math.random() * .75));
float yy = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 1));
float zz = (float) (0 + (Math.random() * .75)); float zz = (float) (0 + (Math.random() * .75));
@ -101,20 +103,25 @@ public class FurnaceTask extends BukkitRunnable {
for (Location location : furnace.getRadius(false)) { for (Location location : furnace.getRadius(false)) {
int random = ThreadLocalRandom.current().nextInt(0, 10); int random = ThreadLocalRandom.current().nextInt(0, 10);
if (random != 1) continue; if (random != 1) {
continue;
}
Block block = location.getBlock(); Block block = location.getBlock();
if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")) continue; if (!block.getType().name().contains("FURNACE") && !block.getType().name().contains("SMOKER")) {
Furnace furnace1 = plugin.getFurnaceManager().getFurnace(block); continue;
if (furnace == furnace1) continue; }
Furnace furnace1 = this.plugin.getFurnaceManager().getFurnace(block);
if (furnace == furnace1) {
continue;
}
org.bukkit.block.Furnace furnaceBlock = ((org.bukkit.block.Furnace) block.getState()); org.bukkit.block.Furnace furnaceBlock = ((org.bukkit.block.Furnace) block.getState());
if (furnaceBlock.getBurnTime() == 0) { if (furnaceBlock.getBurnTime() == 0) {
furnaceBlock.setBurnTime((short) 100); furnaceBlock.setBurnTime((short) 100);
furnaceBlock.update(); furnaceBlock.update();
if (doParticles) { if (this.doParticles) {
float xx = (float) (0 + (Math.random() * .75)); float xx = (float) (0 + (Math.random() * .75));
float yy = (float) (0 + (Math.random() * 1)); float yy = (float) (0 + (Math.random() * 1));
float zz = (float) (0 + (Math.random() * .75)); float zz = (float) (0 + (Math.random() * .75));

View File

@ -5,7 +5,6 @@ import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
public class HologramTask extends BukkitRunnable { public class HologramTask extends BukkitRunnable {
private static HologramTask instance; private static HologramTask instance;
private final EpicFurnaces plugin; private final EpicFurnaces plugin;
@ -25,8 +24,10 @@ public class HologramTask extends BukkitRunnable {
@Override @Override
public void run() { public void run() {
if (!HologramManager.getManager().isEnabled()) return; if (!HologramManager.getManager().isEnabled()) {
return;
}
plugin.updateHolograms(plugin.getFurnaceManager().getFurnaces().values()); this.plugin.updateHolograms(this.plugin.getFurnaceManager().getFurnaces().values());
} }
} }

View File

@ -4,7 +4,6 @@ package com.songoda.epicfurnaces.utils;
* Represents a cost type when making a purchase from EpicFurnaces * Represents a cost type when making a purchase from EpicFurnaces
*/ */
public enum CostType { public enum CostType {
/** /**
* A purchase made with an economy balance (generally an implementation of Vault) * A purchase made with an economy balance (generally an implementation of Vault)
*/ */
@ -14,5 +13,4 @@ public enum CostType {
* A purchase made with a player's experience levels * A purchase made with a player's experience levels
*/ */
EXPERIENCE EXPERIENCE
} }

View File

@ -7,8 +7,7 @@ import org.bukkit.World;
import java.util.Objects; import java.util.Objects;
public class GameArea { public class GameArea {
private static final int SIZE = Math.max(16, Settings.FURNACE_AREA.getInt());
private static final int size = Math.max(16, Settings.FURNACE_AREA.getInt());
private final String world; private final String world;
private final int x; private final int x;
@ -21,21 +20,24 @@ public class GameArea {
} }
public static GameArea of(Location location) { public static GameArea of(Location location) {
return new GameArea(location.getWorld(), location.getBlockX() / size, location.getBlockZ() / size); return new GameArea(location.getWorld(), location.getBlockX() / SIZE, location.getBlockZ() / SIZE);
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(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;
}
GameArea gameArea = (GameArea) o; GameArea gameArea = (GameArea) o;
return x == gameArea.x && return this.x == gameArea.x && this.y == gameArea.y && this.world.equals(gameArea.world);
y == gameArea.y &&
world.equals(gameArea.world);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(world, x, y); return Objects.hash(this.world, this.x, this.y);
} }
} }

View File

@ -1,6 +1,6 @@
package com.songoda.epicfurnaces.utils; package com.songoda.epicfurnaces.utils;
import com.songoda.core.compatibility.ServerVersion; import com.songoda.core.utils.TextUtils;
import com.songoda.epicfurnaces.EpicFurnaces; import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
@ -12,13 +12,8 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Created by songoda on 2/25/2017.
*/
public class Methods { public class Methods {
public static String cleanString(String typ) { public static String cleanString(String typ) {
String type = typ.replaceAll("_", " "); String type = typ.replaceAll("_", " ");
type = ChatColor.stripColor(type.substring(0, 1).toUpperCase() + type.toLowerCase().substring(1)); type = ChatColor.stripColor(type.substring(0, 1).toUpperCase() + type.toLowerCase().substring(1));
@ -26,11 +21,13 @@ public class Methods {
} }
public static String formatName(int level) { public static String formatName(int level) {
String name = EpicFurnaces.getInstance().getLocale().getMessage("general.nametag.nameformat") String name = EpicFurnaces.getPlugin(EpicFurnaces.class)
.processPlaceholder("level", level).getMessage(); .getLocale()
.getMessage("general.nametag.nameformat")
.processPlaceholder("level", level)
.getMessage();
return TextUtils.formatText(name);
return formatText(name);
} }
/** /**
@ -40,8 +37,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) if (location == null) {
return ""; return "";
}
String w = location.getWorld().getName(); String w = location.getWorld().getName();
double x = location.getBlockX(); double x = location.getBlockX();
double y = location.getBlockY(); double y = location.getBlockY();
@ -52,7 +50,7 @@ public class Methods {
return str; return str;
} }
private static final Map<String, Location> serializeCache = new HashMap<>(); private static final Map<String, Location> SERIALIZE_CACHE = new HashMap<>();
/** /**
* Deserializes a location from the string. * Deserializes a location from the string.
@ -61,121 +59,27 @@ public class Methods {
* @return The location that was serialized in the string. * @return The location that was serialized in the string.
*/ */
public static Location unserializeLocation(String str) { public static Location unserializeLocation(String str) {
if (str == null || str.equals("")) if (str == null || str.equals("")) {
return null; return null;
if (serializeCache.containsKey(str)) { }
return serializeCache.get(str).clone(); if (SERIALIZE_CACHE.containsKey(str)) {
return SERIALIZE_CACHE.get(str).clone();
} }
String cacheKey = str; String cacheKey = str;
str = str.replace("y:", ":").replace("z:", ":").replace("w:", "").replace("x:", ":").replace("/", "."); str = str.replace("y:", ":")
.replace("z:", ":")
.replace("w:", "")
.replace("x:", ":")
.replace("/", ".");
List<String> args = Arrays.asList(str.split("\\s*:\\s*")); List<String> args = Arrays.asList(str.split("\\s*:\\s*"));
World world = Bukkit.getWorld(args.get(0)); World world = Bukkit.getWorld(args.get(0));
double x = Double.parseDouble(args.get(1)), y = Double.parseDouble(args.get(2)), z = Double.parseDouble(args.get(3)); double x = Double.parseDouble(args.get(1));
double y = Double.parseDouble(args.get(2));
double z = Double.parseDouble(args.get(3));
Location location = new Location(world, x, y, z, 0, 0); Location location = new Location(world, x, y, z, 0, 0);
serializeCache.put(cacheKey, location.clone()); SERIALIZE_CACHE.put(cacheKey, location.clone());
return location; return location;
} }
public static String convertToInvisibleString(String s) {
if (s == null || s.equals(""))
return "";
StringBuilder hidden = new StringBuilder();
for (char c : s.toCharArray()) hidden.append(ChatColor.COLOR_CHAR + "").append(c);
return hidden.toString();
}
public static String formatText(String text) {
if (text == null || text.equals(""))
return "";
return formatText(text, false);
}
public static String formatText(String text, boolean cap) {
if (text == null || text.equals(""))
return "";
if (cap)
text = text.substring(0, 1).toUpperCase() + text.substring(1);
return ChatColor.translateAlternateColorCodes('&', text);
}
public static boolean isInt(String number) {
if (number == null || number.equals(""))
return false;
try {
Integer.parseInt(number);
} catch (NumberFormatException e) {
return false;
}
return true;
}
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;
}
return 0;
}
public static String formatEconomy(double amt) {
DecimalFormat formatter = new DecimalFormat("#,###.00");
return formatter.format(amt);
}
public static String formatTitle(String text) {
if (text == null || text.equals(""))
return "";
if (!ServerVersion.isServerVersionAtLeast(ServerVersion.V1_9)) {
if (text.length() > 31)
text = text.substring(0, 29) + "...";
}
text = formatText(text);
return text;
}
} }