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.ProtectionManager;
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.BoostManager;
import com.songoda.epicfurnaces.commands.CommandBoost;
@ -65,8 +66,6 @@ import java.util.UUID;
import java.util.stream.Collectors;
public class EpicFurnaces extends SongodaPlugin {
private static EpicFurnaces INSTANCE;
private final Config furnaceRecipeFile = new Config(this, "Furnace Recipes.yml");
private final Config levelsFile = new Config(this, "levels.yml");
@ -81,13 +80,16 @@ public class EpicFurnaces extends SongodaPlugin {
private DatabaseConnector databaseConnector;
private DataManager dataManager;
/**
* @deprecated Use {@link #getPlugin(Class)} instead
*/
@Deprecated
public static EpicFurnaces getInstance() {
return INSTANCE;
return EpicFurnaces.getPlugin(EpicFurnaces.class);
}
@Override
public void onPluginLoad() {
INSTANCE = this;
}
@Override
@ -132,14 +134,14 @@ public class EpicFurnaces extends SongodaPlugin {
new CommandGive(this),
new CommandReload(this),
new CommandRemote(this),
new CommandSettings(this, guiManager)
new CommandSettings(this, this.guiManager)
);
loadLevelManager();
this.furnaceManager = new FurnaceManager();
this.boostManager = new BoostManager();
this.blacklistHandler = new BlacklistHandler();
this.boostManager = new BoostManager(this);
this.blacklistHandler = new BlacklistHandler(this);
// Database stuff.
try {
@ -165,7 +167,7 @@ public class EpicFurnaces extends SongodaPlugin {
this.dataManager = new DataManager(this.databaseConnector, this);
DataMigrationManager dataMigrationManager = new DataMigrationManager(this.databaseConnector, this.dataManager,
new _1_InitialMigration());
new _1_InitialMigration(this));
dataMigrationManager.runMigrations();
Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
@ -178,7 +180,7 @@ public class EpicFurnaces extends SongodaPlugin {
converted = true;
Storage storage = new StorageYaml(this);
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." +
"EpicFurnaces hasn't fully loaded yet, so make sure users don't" +
"interact with the plugin until the conversion process is complete.");
@ -186,20 +188,25 @@ public class EpicFurnaces extends SongodaPlugin {
List<Furnace> furnaces = new ArrayList<>();
for (StorageRow row : storage.getRowsByGroup("charged")) {
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();
UUID placedBy = placedByStr == null ? null : UUID.fromString(placedByStr);
List<String> list = row.get("accesslist").asStringList();
if (!list.isEmpty()) {
for (String uuid : new ArrayList<>(list))
for (String uuid : new ArrayList<>(list)) {
if (uuid.contains(":")) {
list = new ArrayList<>();
break;
}
}
}
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)
.setLevel(levelManager.getLevel(row.get("level").asInt()))
.setLevel(this.levelManager.getLevel(row.get("level").asInt()))
.setNickname(row.get("nickname").asString())
.setUses(row.get("uses").asInt())
.setToLevel(toLevel)
.setAccessList(usableList)
.setPlacedBy(placedBy).build());
}
dataManager.createFurnaces(furnaces);
this.dataManager.createFurnaces(furnaces);
}
// Adding in Boosts
if (storage.containsGroup("boosts")) {
for (StorageRow row : storage.getRowsByGroup("boosts")) {
if (row.get("uuid").asObject() == null)
if (row.get("uuid").asObject() == null) {
continue;
}
dataManager.createBoost(new BoostData(
this.dataManager.createBoost(new BoostData(
row.get("amount").asInt(),
Long.parseLong(row.getKey()),
UUID.fromString(row.get("uuid").asString())));
@ -237,9 +245,9 @@ public class EpicFurnaces extends SongodaPlugin {
}
final boolean finalConverted = converted;
dataManager.runAsync(() -> {
this.dataManager.runAsync(() -> {
if (finalConverted) {
console.sendMessage("[" + getDescription().getName() + "] " + ChatColor.GREEN + "Conversion complete :)");
this.console.sendMessage("[" + getDescription().getName() + "] " + ChatColor.GREEN + "Conversion complete :)");
}
this.dataManager.getFurnaces((furnaces) -> {
@ -249,18 +257,18 @@ public class EpicFurnaces extends SongodaPlugin {
});
});
setupRecipies();
setupRecipes();
// Start Tasks
FurnaceTask.startTask(this);
HologramTask.startTask(this);
// Register Listeners
guiManager.init();
this.guiManager.init();
PluginManager pluginManager = Bukkit.getPluginManager();
pluginManager.registerEvents(new BlockListeners(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 EntityListeners(this), this);
}
@ -279,7 +287,7 @@ public class EpicFurnaces extends SongodaPlugin {
@Override
public List<Config> getExtraConfig() {
return Collections.singletonList(levelsFile);
return Collections.singletonList(this.levelsFile);
}
public void clearHologram(Furnace furnace) {
@ -288,18 +296,24 @@ public class EpicFurnaces extends SongodaPlugin {
public void updateHolograms(Collection<Furnace> furnaces) {
// 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<>();
for (Furnace furnace : furnaces) {
// 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();
// 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);
@ -320,7 +334,7 @@ public class EpicFurnaces extends SongodaPlugin {
sb.append("&c=");
}
progress = Methods.formatText(sb.toString());
progress = TextUtils.formatText(sb.toString());
} else {
progress = getLocale().getMessage("general.hologram.outoffuel").getMessage();
}
@ -352,22 +366,23 @@ public class EpicFurnaces extends SongodaPlugin {
}
private void loadLevelManager() {
if (!levelsFile.getFile().exists())
if (!this.levelsFile.getFile().exists()) {
this.saveResource("levels.yml", false);
levelsFile.load();
}
this.levelsFile.load();
// Load an plugin of LevelManager
levelManager = new LevelManager();
// Load a plugin of LevelManager
this.levelManager = new LevelManager();
/*
* Register Levels into LevelManager from configuration.
*/
levelManager.clear();
for (String levelName : levelsFile.getKeys(false)) {
this.levelManager.clear();
for (String levelName : this.levelsFile.getKeys(false)) {
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");
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");
if (!config.exists()) {
saveResource("Furnace Recipes.yml", false);
}
furnaceRecipeFile.load();
this.furnaceRecipeFile.load();
if (Settings.CUSTOM_RECIPES.getBoolean()) {
ConfigurationSection cs = furnaceRecipeFile.getConfigurationSection("Recipes");
ConfigurationSection cs = this.furnaceRecipeFile.getConfigurationSection("Recipes");
for (String key : cs.getKeys(false)) {
Material item = Material.valueOf(key.toUpperCase());
Material result = Material.valueOf(furnaceRecipeFile.getString("Recipes." + key.toUpperCase() + ".result"));
int amount = furnaceRecipeFile.getInt("Recipes." + key.toUpperCase() + ".amount");
Material result = Material.valueOf(this.furnaceRecipeFile.getString("Recipes." + key.toUpperCase() + ".result"));
int amount = this.furnaceRecipeFile.getInt("Recipes." + key.toUpperCase() + ".amount");
getServer().addRecipe(new FurnaceRecipe(new ItemStack(result, amount), item));
}
@ -415,7 +430,7 @@ public class EpicFurnaces extends SongodaPlugin {
public boolean isLeveledFurnace(ItemStack 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) {
@ -423,7 +438,7 @@ public class EpicFurnaces extends SongodaPlugin {
if (Settings.FURNACE_ITEM.getBoolean()) {
ItemMeta itemmeta = item.getItemMeta();
itemmeta.setDisplayName(Methods.formatText(Methods.formatName(level)));
itemmeta.setDisplayName(TextUtils.formatText(Methods.formatName(level)));
item.setItemMeta(itemmeta);
}
@ -437,8 +452,9 @@ public class EpicFurnaces extends SongodaPlugin {
public int getFurnaceLevel(ItemStack item) {
NBTItem nbtItem = new NBTItem(item);
if (nbtItem.hasKey("level"))
if (nbtItem.hasTag("level")) {
return nbtItem.getInteger("level");
}
// Legacy trash.
if (item.getItemMeta().getDisplayName().contains(":")) {
@ -452,8 +468,9 @@ public class EpicFurnaces extends SongodaPlugin {
public int getFurnaceUses(ItemStack item) {
NBTItem nbtItem = new NBTItem(item);
if (nbtItem.hasKey("uses"))
if (nbtItem.hasTag("uses")) {
return nbtItem.getInteger("uses");
}
// Legacy trash.
if (item.getItemMeta().getDisplayName().contains(":")) {
@ -465,34 +482,34 @@ public class EpicFurnaces extends SongodaPlugin {
}
public Config getFurnaceRecipeFile() {
return furnaceRecipeFile;
return this.furnaceRecipeFile;
}
public CommandManager getCommandManager() {
return commandManager;
return this.commandManager;
}
public BoostManager getBoostManager() {
return boostManager;
return this.boostManager;
}
public BlacklistHandler getBlacklistHandler() {
return blacklistHandler;
return this.blacklistHandler;
}
public FurnaceManager getFurnaceManager() {
return furnaceManager;
return this.furnaceManager;
}
public LevelManager getLevelManager() {
return levelManager;
return this.levelManager;
}
public DatabaseConnector getDatabaseConnector() {
return databaseConnector;
return this.databaseConnector;
}
public DataManager getDataManager() {
return dataManager;
return this.dataManager;
}
}

View File

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

View File

@ -2,18 +2,27 @@ package com.songoda.epicfurnaces.boost;
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 {
private final EpicFurnaces plugin;
private final Set<BoostData> registeredBoosts = new HashSet<>();
public BoostManager(EpicFurnaces plugin) {
this.plugin = plugin;
}
public void addBoostToPlayer(BoostData data) {
this.registeredBoosts.add(data);
}
public void addBoosts(List<BoostData> boosts) {
registeredBoosts.addAll(boosts);
this.registeredBoosts.addAll(boosts);
}
public void removeBoostFromPlayer(BoostData data) {
@ -21,16 +30,19 @@ public class BoostManager {
}
public Set<BoostData> getBoosts() {
return Collections.unmodifiableSet(registeredBoosts);
return Collections.unmodifiableSet(this.registeredBoosts);
}
public BoostData getBoost(UUID player) {
if (player == null) return null;
for (BoostData boostData : registeredBoosts) {
if (player == null) {
return null;
}
for (BoostData boostData : this.registeredBoosts) {
if (boostData.getPlayer().toString().equals(player.toString())) {
if (System.currentTimeMillis() >= boostData.getEndTime()) {
removeBoostFromPlayer(boostData);
EpicFurnaces.getInstance().getDataManager().deleteBoost(boostData);
this.plugin.getDataManager().deleteBoost(boostData);
}
return boostData;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -10,7 +10,6 @@ import org.bukkit.entity.Player;
import java.util.List;
public class CommandSettings extends AbstractCommand {
private final EpicFurnaces plugin;
private final GuiManager guiManager;
@ -22,12 +21,12 @@ public class CommandSettings extends AbstractCommand {
@Override
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;
}
@Override
protected List<String> onTab(CommandSender commandSender, String... strings) {
protected List<String> onTab(CommandSender sender, String... args) {
return null;
}

View File

@ -5,9 +5,7 @@ import com.songoda.skyblock.permission.BasicPermission;
import com.songoda.skyblock.permission.PermissionType;
public class EpicFurnacesPermission extends BasicPermission {
public EpicFurnacesPermission() {
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.permission.BasicPermission;
import java.lang.reflect.InvocationTargetException;
public class FabledSkyBlockLoader {
public FabledSkyBlockLoader() {
SkyBlock.getInstance().getPermissionManager().registerPermission(new EpicFurnacesPermission());
try {
SkyBlock.getInstance().getPermissionManager().registerPermission(
(BasicPermission) Class.forName("com.songoda.epicfurnaces.compatibility.EpicFurnacesPermission").getDeclaredConstructor().newInstance());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
SkyBlock.getInstance().getPermissionManager().registerPermission((BasicPermission) Class.forName("com.songoda.epicfurnaces.compatibility.EpicFurnacesPermission").getDeclaredConstructor().newInstance());
} catch (ReflectiveOperationException ex) {
ex.printStackTrace();
}
}
}

View File

@ -9,14 +9,16 @@ import java.sql.SQLException;
import java.sql.Statement;
public class _1_InitialMigration extends DataMigration {
private final EpicFurnaces plugin;
public _1_InitialMigration() {
public _1_InitialMigration(EpicFurnaces plugin) {
super(1);
this.plugin = plugin;
}
@Override
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.
try (Statement statement = connection.createStatement()) {
@ -58,6 +60,5 @@ public class _1_InitialMigration extends DataMigration {
"end_time BIGINT NOT NULL " +
")");
}
}
}

View File

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

View File

@ -9,7 +9,6 @@ import java.util.Map;
import java.util.UUID;
public class FurnaceBuilder {
//Level level, String nickname, int uses, int tolevel, List<String> accessList, UUID placedBy
private final Furnace furnace;
@ -34,14 +33,16 @@ public class FurnaceBuilder {
}
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());
}
return this;
}
public FurnaceBuilder setAccessList(List<UUID> accessList) {
for (UUID uuid : accessList)
for (UUID uuid : accessList) {
this.furnace.addToAccessList(uuid);
}
return this;
}

View File

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

View File

@ -10,14 +10,19 @@ import java.util.List;
import java.util.Map;
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 List<String> description = new ArrayList<>();
private final 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) {
this.level = level;
@ -30,75 +35,90 @@ public class Level {
this.fuelShare = fuelShare;
this.materials = materials;
EpicFurnaces plugin = EpicFurnaces.getInstance();
EpicFurnaces plugin = EpicFurnaces.getPlugin(EpicFurnaces.class);
if (performance != 0)
description.add(plugin.getLocale().getMessage("interface.furnace.performance")
.processPlaceholder("amount", performance + "%").getMessage());
if (performance != 0) {
this.description.add(plugin.getLocale()
.getMessage("interface.furnace.performance")
.processPlaceholder("amount", performance + "%")
.getMessage());
}
if (reward != null)
description.add(plugin.getLocale().getMessage("interface.furnace.reward")
.processPlaceholder("amount", reward.split("%:")[0] + "%").getMessage());
if (reward != null) {
this.description.add(plugin.getLocale()
.getMessage("interface.furnace.reward")
.processPlaceholder("amount", reward.split("%:")[0] + "%")
.getMessage());
}
if (fuelDuration != 0)
description.add(plugin.getLocale().getMessage("interface.furnace.fuelduration")
.processPlaceholder("amount", fuelDuration + "%").getMessage());
if (fuelDuration != 0) {
this.description.add(plugin.getLocale()
.getMessage("interface.furnace.fuelduration")
.processPlaceholder("amount", fuelDuration + "%")
.getMessage());
}
if (fuelShare != 0)
description.add(plugin.getLocale().getMessage("interface.furnace.fuelshare")
.processPlaceholder("amount", fuelShare).getMessage());
if (fuelShare != 0) {
this.description.add(plugin.getLocale()
.getMessage("interface.furnace.fuelshare")
.processPlaceholder("amount", fuelShare)
.getMessage());
}
if (overheat != 0)
description.add(plugin.getLocale().getMessage("interface.furnace.overheat")
.processPlaceholder("amount", overheat).getMessage());
if (overheat != 0) {
this.description.add(plugin.getLocale()
.getMessage("interface.furnace.overheat")
.processPlaceholder("amount", overheat)
.getMessage());
}
}
public List<String> getDescription() {
return new ArrayList<>(description);
return new ArrayList<>(this.description);
}
public int getLevel() {
return level;
return this.level;
}
public int getPerformance() {
return performance;
return this.performance;
}
public String getReward() {
return reward;
return this.reward;
}
public int getOverheat() {
return overheat;
return this.overheat;
}
public int getFuelShare() {
return fuelShare;
return this.fuelShare;
}
public int getFuelDuration() {
return fuelDuration;
return this.fuelDuration;
}
public int getCostExperience() {
return costExperience;
return this.costExperience;
}
public int getCostEconomy() {
return costEconomy;
return this.costEconomy;
}
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;
public class LevelManager {
private final NavigableMap<Integer, Level> registeredLevels = new TreeMap<>();
public void addLevel(int level, int costExperiance, int costEconomy, int performance, String reward, int fuelDuration, int overheat, int fuelShare, Map<CompatibleMaterial, Integer> materials) {
registeredLevels.put(level, new Level(level, costExperiance, costEconomy, performance, reward, fuelDuration, overheat, fuelShare, materials));
public void addLevel(int level, int costExperience, 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));
}
public Level getLevel(int level) {
return registeredLevels.get(level);
return this.registeredLevels.get(level);
}
public Level getLowestLevel() {
return registeredLevels.firstEntry().getValue();
return this.registeredLevels.firstEntry().getValue();
}
public Level getHighestLevel() {
return registeredLevels.lastEntry().getValue();
return this.registeredLevels.lastEntry().getValue();
}
public boolean isLevel(int level) {
return registeredLevels.containsKey(level);
return this.registeredLevels.containsKey(level);
}
public Map<Integer, Level> getLevels() {
return Collections.unmodifiableMap(registeredLevels);
return Collections.unmodifiableMap(this.registeredLevels);
}
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.GuiUtils;
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.boost.BoostData;
import com.songoda.epicfurnaces.furnace.Furnace;
@ -24,7 +27,6 @@ import java.util.Map;
import java.util.UUID;
public class GUIOverview extends CustomizableGui {
private final EpicFurnaces plugin;
private final Furnace furnace;
private final Player player;
@ -42,7 +44,7 @@ public class GUIOverview extends CustomizableGui {
setTitle(Methods.formatName(furnace.getLevel().getLevel()));
runTask();
constructGUI();
this.setOnClose(action -> Bukkit.getScheduler().cancelTask(task));
this.setOnClose(action -> Bukkit.getScheduler().cancelTask(this.task));
}
private void constructGUI() {
@ -58,15 +60,15 @@ public class GUIOverview extends CustomizableGui {
mirrorFill("mirrorfill_4", 1, 0, false, true, glass2);
mirrorFill("mirrorfill_5", 1, 1, false, true, glass3);
Level level = furnace.getLevel();
Level nextLevel = plugin.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? plugin.getLevelManager().getLevel(level.getLevel() + 1) : null;
Level level = this.furnace.getLevel();
Level nextLevel = this.plugin.getLevelManager().getHighestLevel().getLevel() > level.getLevel() ? this.plugin.getLevelManager().getLevel(level.getLevel() + 1) : null;
// main furnace information icon
setItem("information",1, 4, GuiUtils.createButtonItem(
CompatibleMaterial.getMaterial(furnace.getLocation().getBlock().getType()),
plugin.getLocale().getMessage("interface.furnace.currentlevel")
setItem("information", 1, 4, GuiUtils.createButtonItem(
CompatibleMaterial.getMaterial(this.furnace.getLocation().getBlock().getType()),
this.plugin.getLocale().getMessage("interface.furnace.currentlevel")
.processPlaceholder("level", level.getLevel()).getMessage(),
getFurnaceDescription(furnace, level, nextLevel)));
getFurnaceDescription(this.furnace, level, nextLevel)));
// check how many info icons we have to show
int num = -1;
@ -89,142 +91,144 @@ public class GUIOverview extends CustomizableGui {
int current = 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),
plugin.getLocale().getMessage("interface.furnace.performancetitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.performanceinfo")
this.plugin.getLocale().getMessage("interface.furnace.performancetitle").getMessage(),
this.plugin.getLocale().getMessage("interface.furnace.performanceinfo")
.processPlaceholder("amount", level.getPerformance()).getMessage().split("\\|")));
}
if (level.getReward() != null) {
setItem("reward", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.REWARD_ICON.getMaterial(CompatibleMaterial.GOLDEN_APPLE),
plugin.getLocale().getMessage("interface.furnace.rewardtitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.rewardinfo")
this.plugin.getLocale().getMessage("interface.furnace.rewardtitle").getMessage(),
this.plugin.getLocale().getMessage("interface.furnace.rewardinfo")
.processPlaceholder("amount", level.getReward().split(":")[0].replace("%", ""))
.getMessage().split("\\|")));
}
if (level.getFuelDuration() != 0) {
setItem("fuel", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.FUEL_DURATION_ICON.getMaterial(CompatibleMaterial.COAL),
plugin.getLocale().getMessage("interface.furnace.fueldurationtitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.fueldurationinfo")
this.plugin.getLocale().getMessage("interface.furnace.fueldurationtitle").getMessage(),
this.plugin.getLocale().getMessage("interface.furnace.fueldurationinfo")
.processPlaceholder("amount", level.getFuelDuration())
.getMessage().split("\\|")));
}
if (level.getFuelShare() != 0) {
setItem("fuel_share", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.FUEL_SHARE_ICON.getMaterial(CompatibleMaterial.COAL_BLOCK),
plugin.getLocale().getMessage("interface.furnace.fuelsharetitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.fuelshareinfo")
this.plugin.getLocale().getMessage("interface.furnace.fuelsharetitle").getMessage(),
this.plugin.getLocale().getMessage("interface.furnace.fuelshareinfo")
.processPlaceholder("amount", level.getOverheat() * 3)
.getMessage().split("\\|")));
}
if (level.getOverheat() != 0) {
setItem("overheat", infoIconOrder[num][current++], GuiUtils.createButtonItem(
Settings.OVERHEAT_ICON.getMaterial(CompatibleMaterial.FIRE_CHARGE),
plugin.getLocale().getMessage("interface.furnace.overheattitle").getMessage(),
plugin.getLocale().getMessage("interface.furnace.overheatinfo")
this.plugin.getLocale().getMessage("interface.furnace.overheattitle").getMessage(),
this.plugin.getLocale().getMessage("interface.furnace.overheatinfo")
.processPlaceholder("amount", level.getOverheat() * 3)
.getMessage().split("\\|")));
}
// remote control
if (Settings.REMOTE.getBoolean() && player.hasPermission("EpicFurnaces.Remote")) {
if (Settings.REMOTE.getBoolean() && this.player.hasPermission("EpicFurnaces.Remote")) {
setButton("remote", 4, GuiUtils.createButtonItem(
CompatibleMaterial.TRIPWIRE_HOOK,
plugin.getLocale().getMessage("interface.furnace.remotefurnace").getMessage(),
getFurnaceRemoteLore(furnace)),
CompatibleMaterial.TRIPWIRE_HOOK,
this.plugin.getLocale().getMessage("interface.furnace.remotefurnace").getMessage(),
getFurnaceRemoteLore(this.furnace)),
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 -> {
for (Furnace other : plugin.getFurnaceManager().getFurnaces().values()) {
for (Furnace other : this.plugin.getFurnaceManager().getFurnaces().values()) {
if (other.getNickname() == null) {
continue;
}
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;
}
}
plugin.getDataManager().queueFurnaceForUpdate(furnace);
furnace.setNickname(promptEvent.getMessage());
plugin.getLocale().getMessage("event.remote.nicknamesuccess").sendPrefixedMessage(player);
}).setOnClose(() -> guiManager.showGUI(player, new GUIOverview(plugin, furnace, player)));
this.plugin.getDataManager().queueFurnaceForUpdate(this.furnace);
this.furnace.setNickname(promptEvent.getMessage());
this.plugin.getLocale().getMessage("event.remote.nicknamesuccess").sendPrefixedMessage(this.player);
}).setOnClose(() -> this.guiManager.showGUI(this.player, new GUIOverview(this.plugin, this.furnace, this.player)));
}).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()
&& level.getCostExperience() != -1
&& player.hasPermission("EpicFurnaces.Upgrade.XP")) {
&& this.player.hasPermission("EpicFurnaces.Upgrade.XP")) {
setButton("upgrade_xp", 1, 2, GuiUtils.createButtonItem(
Settings.XP_ICON.getMaterial(CompatibleMaterial.EXPERIENCE_BOTTLE),
plugin.getLocale().getMessage("interface.furnace.upgradewithxp").getMessage(),
nextLevel != null
? plugin.getLocale().getMessage("interface.furnace.upgradewithxplore")
.processPlaceholder("cost", nextLevel.getCostExperience()).getMessage()
: plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()),
Settings.XP_ICON.getMaterial(CompatibleMaterial.EXPERIENCE_BOTTLE),
this.plugin.getLocale().getMessage("interface.furnace.upgradewithxp").getMessage(),
nextLevel != null
? this.plugin.getLocale().getMessage("interface.furnace.upgradewithxplore")
.processPlaceholder("cost", nextLevel.getCostExperience()).getMessage()
: this.plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()),
(event) -> {
furnace.upgrade(player, CostType.EXPERIENCE);
furnace.overview(guiManager, player);
this.furnace.upgrade(this.player, CostType.EXPERIENCE);
this.furnace.overview(this.guiManager, this.player);
});
}
if (Settings.UPGRADE_WITH_ECONOMY.getBoolean()
&& level.getCostEconomy() != -1
&& player.hasPermission("EpicFurnaces.Upgrade.ECO")) {
&& this.player.hasPermission("EpicFurnaces.Upgrade.ECO")) {
setButton("upgrade_economy", 1, 6, GuiUtils.createButtonItem(
Settings.ECO_ICON.getMaterial(CompatibleMaterial.SUNFLOWER),
plugin.getLocale().getMessage("interface.furnace.upgradewitheconomy").getMessage(),
nextLevel != null
? plugin.getLocale().getMessage("interface.furnace.upgradewitheconomylore")
.processPlaceholder("cost", Methods.formatEconomy(nextLevel.getCostEconomy())).getMessage()
: plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()),
Settings.ECO_ICON.getMaterial(CompatibleMaterial.SUNFLOWER),
this.plugin.getLocale().getMessage("interface.furnace.upgradewitheconomy").getMessage(),
nextLevel != null
? this.plugin.getLocale().getMessage("interface.furnace.upgradewitheconomylore")
.processPlaceholder("cost", NumberUtils.formatNumber(nextLevel.getCostEconomy())).getMessage()
: this.plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage()),
(event) -> {
furnace.upgrade(player, CostType.ECONOMY);
furnace.overview(guiManager, player);
this.furnace.upgrade(this.player, CostType.ECONOMY);
this.furnace.overview(this.guiManager, this.player);
});
}
}
private void runTask() {
task = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
if (inventory.getViewers().size() != 0)
this.task = Bukkit.getScheduler().scheduleSyncRepeatingTask(this.plugin, () -> {
if (this.inventory.getViewers().size() != 0) {
this.constructGUI();
}
}, 5L, 5L);
}
List<String> getFurnaceDescription(Furnace furnace, Level level, Level nextLevel) {
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());
lore.addAll(level.getDescription());
lore.add("");
if (nextLevel == null) {
lore.add(plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage());
lore.add(this.plugin.getLocale().getMessage("interface.furnace.alreadymaxed").getMessage());
} else {
lore.add(plugin.getLocale().getMessage("interface.furnace.level")
lore.add(this.plugin.getLocale().getMessage("interface.furnace.level")
.processPlaceholder("level", nextLevel.getLevel()).getMessage());
lore.addAll(nextLevel.getDescription());
if (Settings.UPGRADE_BY_SMELTING.getBoolean()) {
lore.add(plugin.getLocale().getMessage("interface.furnace.itemsneeded").getMessage());
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.itemsneeded").getMessage());
for (Map.Entry<CompatibleMaterial, Integer> entry : level.getMaterials().entrySet()) {
lore.add(this.plugin.getLocale().getMessage("interface.furnace.neededitem")
.processPlaceholder("amount", entry.getValue() - furnace.getToLevel(entry.getKey()))
.processPlaceholder("type", Methods.cleanString(entry.getKey().name()))
.getMessage());
}
}
}
BoostData boostData = plugin.getBoostManager().getBoost(furnace.getPlacedBy());
BoostData boostData = this.plugin.getBoostManager().getBoost(furnace.getPlacedBy());
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("time", Methods.makeReadable(boostData.getEndTime() - System.currentTimeMillis()))
.processPlaceholder("time", TimeUtils.makeReadable(boostData.getEndTime() - System.currentTimeMillis()))
.getMessage().split("\\|")));
}
return lore;
@ -232,20 +236,20 @@ public class GUIOverview extends CustomizableGui {
List<String> getFurnaceRemoteLore(Furnace furnace) {
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("\\|")));
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("\\|")));
}
lorehook.add("");
lorehook.add(plugin.getLocale().getMessage("interface.furnace.remotelist").getMessage());
loreHook.add("");
loreHook.add(this.plugin.getLocale().getMessage("interface.furnace.remotelist").getMessage());
for (UUID uuid : furnace.getAccessList()) {
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;
public class GUIRemoteAccess extends CustomizableGui {
private final EpicFurnaces plugin;
private final Furnace furnace;
private final Player player;
@ -52,59 +51,61 @@ public class GUIRemoteAccess extends CustomizableGui {
mirrorFill("mirrorfill_4", 1, 0, 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()));
setPrevPage(5, 1, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, plugin.getLocale().getMessage("general.nametag.back").getMessage()));
setNextPage(5, 7, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, this.plugin.getLocale().getMessage("general.nametag.next").getMessage()));
setPrevPage(5, 1, GuiUtils.createButtonItem(CompatibleMaterial.ARROW, this.plugin.getLocale().getMessage("general.nametag.back").getMessage()));
setOnPage((event) -> showPage());
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,
plugin.getLocale().getMessage("interface.remoteaccess.addplayertitle").getMessage()), (event) -> {
plugin.getLocale().getMessage("event.remote.enterplayer").sendPrefixedMessage(player);
ChatPrompt.showPrompt(plugin, player, chat -> {
this.plugin.getLocale().getMessage("interface.remoteaccess.addplayertitle").getMessage()), (event) -> {
this.plugin.getLocale().getMessage("event.remote.enterplayer").sendPrefixedMessage(this.player);
ChatPrompt.showPrompt(this.plugin, this.player, chat -> {
Player toAdd = Bukkit.getPlayer(chat.getMessage());
if (toAdd == null) {
plugin.getLocale().getMessage("event.remote.invalidplayer").sendPrefixedMessage(player);
this.plugin.getLocale().getMessage("event.remote.invalidplayer").sendPrefixedMessage(this.player);
return;
}
if (furnace.getAccessList().contains(toAdd.getUniqueId())) {
plugin.getLocale().getMessage("event.remote.playeralreadyadded").sendPrefixedMessage(player);
if (this.furnace.getAccessList().contains(toAdd.getUniqueId())) {
this.plugin.getLocale().getMessage("event.remote.playeralreadyadded").sendPrefixedMessage(this.player);
return;
}
furnace.addToAccessList(toAdd);
plugin.getDataManager().createAccessPlayer(furnace, toAdd.getUniqueId());
plugin.getLocale().getMessage("event.remote.playeradded").sendPrefixedMessage(player);
}).setOnClose(() -> guiManager.showGUI(player, new GUIRemoteAccess(plugin, furnace, player)));
this.furnace.addToAccessList(toAdd);
this.plugin.getDataManager().createAccessPlayer(this.furnace, toAdd.getUniqueId());
this.plugin.getLocale().getMessage("event.remote.playeradded").sendPrefixedMessage(this.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());
Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
List<UUID> entries = this.furnace.getAccessList().stream().skip((this.page - 1) * 28).limit(28).collect(Collectors.toList());
Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
int num = 11;
for (UUID entry : entries) {
if (num == 16 || num == 36)
if (num == 16 || num == 36) {
num = num + 2;
}
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(entry);
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("\\|"));
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);
else
} else {
meta.setOwner(offlinePlayer.getName());
}
itemStack.setItemMeta(meta);
setButton(num, itemStack, event -> {
furnace.removeFromAccessList(entry);
plugin.getDataManager().deleteAccessPlayer(furnace, entry);
guiManager.showGUI(player, new GUIRemoteAccess(plugin, furnace, player));
this.furnace.removeFromAccessList(entry);
this.plugin.getDataManager().deleteAccessPlayer(this.furnace, entry);
this.guiManager.showGUI(this.player, new GUIRemoteAccess(this.plugin, this.furnace, this.player));
});
num++;
}

View File

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

View File

@ -1,6 +1,5 @@
package com.songoda.epicfurnaces.listeners;
import com.songoda.core.hooks.HologramManager;
import com.songoda.core.utils.PlayerUtils;
import com.songoda.epicfurnaces.EpicFurnaces;
import com.songoda.epicfurnaces.furnace.Furnace;
@ -22,11 +21,7 @@ import org.bukkit.inventory.ItemStack;
import java.util.Collections;
import java.util.List;
/**
* Created by songoda on 2/26/2017.
*/
public class BlockListeners implements Listener {
private final EpicFurnaces plugin;
public BlockListeners(EpicFurnaces plugin) {
@ -37,15 +32,19 @@ public class BlockListeners implements Listener {
public void onSnowLand(BlockFormEvent event) {
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);
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;
}
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;
}
event.setCancelled(true);
return;
}
@ -54,29 +53,31 @@ public class BlockListeners implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
if (plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld())
|| !event.getBlock().getType().name().contains("FURNACE") && !event.getBlock().getType().name().contains("SMOKER"))
if (this.plugin.getBlacklistHandler().isBlacklisted(event.getPlayer().getWorld())
|| !event.getBlock().getType().name().contains("FURNACE") && !event.getBlock().getType().name().contains("SMOKER")) {
return;
}
ItemStack item = event.getItemInHand();
Player player = event.getPlayer();
if (!plugin.isLeveledFurnace(item) && Settings.ALLOW_NORMAL_FURNACES.getBoolean()) {
if (!this.plugin.isLeveledFurnace(item) && Settings.ALLOW_NORMAL_FURNACES.getBoolean()) {
return;
}
if (Settings.USE_LIMIT_PERMISSION.getBoolean()) {
int amount = 0;
for (Furnace furnace : plugin.getFurnaceManager().getFurnaces().values()) {
if (furnace.getPlacedBy() == null || !furnace.getPlacedBy().equals(player.getUniqueId())) continue;
for (Furnace furnace : this.plugin.getFurnaceManager().getFurnaces().values()) {
if (furnace.getPlacedBy() == null || !furnace.getPlacedBy().equals(player.getUniqueId())) {
continue;
}
amount++;
}
int limit = PlayerUtils.getNumberFromPermission(player, "epicfurnaces.limit", -1);
if (limit != -1 && amount >= limit) {
event.setCancelled(true);
plugin.getLocale().getMessage("event.limit.hit")
this.plugin.getLocale().getMessage("event.limit.hit")
.processPlaceholder("limit", limit).sendPrefixedMessage(player);
return;
}
@ -84,17 +85,17 @@ public class BlockListeners implements Listener {
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)
.setLevel(plugin.getLevelManager().getLevel(plugin.getFurnaceLevel(item)))
.setUses(plugin.getFurnaceUses(item))
.setLevel(this.plugin.getLevelManager().getLevel(this.plugin.getFurnaceLevel(item)))
.setUses(this.plugin.getFurnaceUses(item))
.setPlacedBy(event.getPlayer().getUniqueId()).build()
: new FurnaceBuilder(location).setPlacedBy(event.getPlayer().getUniqueId()).build();
plugin.getDataManager().createFurnace(furnace);
plugin.getFurnaceManager().addFurnace(furnace);
this.plugin.getDataManager().createFurnace(furnace);
this.plugin.getFurnaceManager().addFurnace(furnace);
plugin.updateHolograms(Collections.singleton(furnace));
this.plugin.updateHolograms(Collections.singleton(furnace));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
@ -104,32 +105,33 @@ public class BlockListeners implements Listener {
}
Block block = event.getBlock();
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;
}
Furnace furnace = plugin.getFurnaceManager().getFurnace(block);
Furnace furnace = this.plugin.getFurnaceManager().getFurnace(block);
if (furnace == null) {
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) {
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());
// By cancelling the event we destroy any chance of items dropping form the furnace. This fixes the problem.
//furnace.dropItems(); No need to drop items. dropItemNaturally() will drop the items inside the furnance
// 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 furnace
event.getBlock().setType(Material.AIR);
event.getBlock().getLocation().getWorld().dropItemNaturally(event.getBlock().getLocation(), item);
}
plugin.getFurnaceManager().removeFurnace(block.getLocation());
plugin.getDataManager().deleteFurnace(furnace);
this.plugin.getFurnaceManager().removeFurnace(block.getLocation());
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.entity.EntityExplodeEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class EntityListeners implements Listener {
private final EpicFurnaces plugin;
private final FurnaceManager furnaceManager;
@ -25,11 +21,14 @@ public class EntityListeners implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onBlow(EntityExplodeEvent event) {
for (Block block : event.blockList()) {
Furnace furnace = furnaceManager.getFurnace(block);
if (furnace == null) continue;
furnaceManager.removeFurnace(block.getLocation());
plugin.getDataManager().deleteFurnace(furnace);
plugin.clearHologram(furnace);
Furnace furnace = this.furnaceManager.getFurnace(block);
if (furnace == null) {
continue;
}
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.FurnaceSmeltEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class FurnaceListeners implements Listener {
private final EpicFurnaces plugin;
public FurnaceListeners(EpicFurnaces plugin) {
@ -23,26 +19,29 @@ public class FurnaceListeners implements Listener {
@EventHandler
public void onCook(FurnaceSmeltEvent event) {
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);
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);
}
}
@EventHandler
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) {
return;
}
Level level = furnace.getLevel();
if (level.getFuelDuration() != 0) return;
if (level.getFuelDuration() != 0) {
return;
}
int num = level.getFuelDuration();
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.player.PlayerInteractEvent;
/**
* Created by songoda on 2/26/2017.
*/
public class InteractListeners implements Listener {
private final EpicFurnaces plugin;
private final GuiManager guiManager;
@ -33,9 +29,11 @@ public class InteractListeners implements Listener {
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onClick(PlayerInteractEvent event) {
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;
}
Player player = event.getPlayer();
@ -50,11 +48,13 @@ public class InteractListeners implements Listener {
if (Bukkit.getPluginManager().isPluginEnabled("FabledSkyBlock")) {
SkyBlock skyBlock = SkyBlock.getInstance();
if (skyBlock.getWorldManager().isIslandWorld(event.getPlayer().getWorld()))
if (skyBlock.getWorldManager().isIslandWorld(event.getPlayer().getWorld())) {
if (!skyBlock.getPermissionManager().hasPermission(event.getPlayer(),
skyBlock.getIslandManager().getIslandAtLocation(event.getClickedBlock().getLocation()),
"EpicFurnaces"))
"EpicFurnaces")) {
return;
}
}
}
//EpicHoppers compatibility
@ -75,6 +75,6 @@ public class InteractListeners implements Listener {
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.inventory.ItemStack;
/**
* Created by songoda on 2/26/2017.
*/
public class InventoryListeners implements Listener {
private final EpicFurnaces plugin;
public InventoryListeners(EpicFurnaces plugin) {
@ -30,25 +26,25 @@ public class InventoryListeners implements Listener {
|| event.getDestination().getItem(0).getAmount() != 1) {
return;
}
Furnace furnace = plugin.getFurnaceManager().getFurnace(((org.bukkit.block.Furnace)
event.getDestination().getHolder()).getLocation());
if (furnace != null)
Furnace furnace = this.plugin.getFurnaceManager().getFurnace(((org.bukkit.block.Furnace) event.getDestination().getHolder()).getLocation());
if (furnace != null) {
furnace.updateCook();
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
if (event.getSlot() != 64537) {
if (event.getInventory().getType() == InventoryType.ANVIL) {
if (event.getAction() != InventoryAction.NOTHING) {
if (event.getCurrentItem() != null && event.getCurrentItem().getType() != Material.AIR) {
ItemStack item = event.getCurrentItem();
if (item.getType().name().contains("FURNACE") && !item.getType().name().contains("SMOKER")) {
event.setCancelled(true);
}
}
}
}
if (event.getSlot() == 64537 ||
event.getInventory().getType() != InventoryType.ANVIL ||
event.getAction() == InventoryAction.NOTHING ||
event.getCurrentItem() == null ||
event.getCurrentItem().getType() == Material.AIR) {
return;
}
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;
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?");
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?");
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.",
"This is purely a safety function to prevent against unplanned crashes or",
"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.");
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.",
"Higher size means decreased performance, but less chances of overheat",
"missing a spot. Lower size means better performance, but overheat",
"might leave a few spots. Minimum value is 16. To disable, just set",
"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?");
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?");
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(),
"Which hologram plugin should be used?",
"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 NO_REWARDS_FROM_RECIPES = new ConfigSetting(config, "Main.No Rewards From 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 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",
"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>",
"permission? This will limit the amount of Epic Furnaces",
"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.");
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 OVERHEAT_PARTICLES = new ConfigSetting(config, "Main.Overheat Particles", true);
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 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?",
"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 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_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 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 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 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 XP_ICON = new ConfigSetting(config, "Interfaces.XP Icon", "EXPERIENCE_BOTTLE");
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 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_3 = new ConfigSetting(config, "Interfaces.Glass Type 3", "LIGHT_BLUE_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_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.",
"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_HOSTNAME = new ConfigSetting(config, "MySQL.Hostname", "localhost");
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_USERNAME = new ConfigSetting(config, "MySQL.Username", "user");
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_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_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_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_USERNAME = new ConfigSetting(CONFIG, "MySQL.Username", "user");
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_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
* called after EconomyManager load
*/
public static void setupConfig() {
config.load();
config.setAutoremove(true).setAutosave(true);
CONFIG.load();
CONFIG.setAutoremove(true).setAutosave(true);
// convert glass pane settings
int color;
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) {
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) {
config.set(GLASS_TYPE_3.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
CONFIG.set(GLASS_TYPE_3.getKey(), CompatibleMaterial.getGlassPaneColor(color).name());
}
// convert economy settings
if (config.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) {
config.set("Main.Economy", "Vault");
} else if (config.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) {
config.set("Main.Economy", "Reserve");
} else if (config.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("PlayerPoints")) {
config.set("Main.Economy", "PlayerPoints");
if (CONFIG.getBoolean("Economy.Use Vault Economy") && EconomyManager.getManager().isEnabled("Vault")) {
CONFIG.set("Main.Economy", "Vault");
} else if (CONFIG.getBoolean("Economy.Use Reserve Economy") && EconomyManager.getManager().isEnabled("Reserve")) {
CONFIG.set("Main.Economy", "Reserve");
} else if (CONFIG.getBoolean("Economy.Use Player Points Economy") && EconomyManager.getManager().isEnabled("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;
public abstract class Storage {
protected final EpicFurnaces plugin;
protected final Config dataFile;
public Storage(EpicFurnaces plugin) {
this.plugin = plugin;
this.dataFile = new Config(plugin, "data.yml");
@ -72,5 +70,4 @@ public abstract class Storage {
public abstract void makeBackup();
public abstract void closeConnection();
}

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,6 @@ import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.scheduler.BukkitRunnable;
public class HologramTask extends BukkitRunnable {
private static HologramTask instance;
private final EpicFurnaces plugin;
@ -25,8 +24,10 @@ public class HologramTask extends BukkitRunnable {
@Override
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
*/
public enum CostType {
/**
* 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
*/
EXPERIENCE
}

View File

@ -7,8 +7,7 @@ import org.bukkit.World;
import java.util.Objects;
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 int x;
@ -21,21 +20,24 @@ public class GameArea {
}
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
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
GameArea gameArea = (GameArea) o;
return x == gameArea.x &&
y == gameArea.y &&
world.equals(gameArea.world);
return this.x == gameArea.x && this.y == gameArea.y && this.world.equals(gameArea.world);
}
@Override
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;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicfurnaces.EpicFurnaces;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@ -12,13 +12,8 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Created by songoda on 2/25/2017.
*/
public class Methods {
public static String cleanString(String typ) {
String type = typ.replaceAll("_", " ");
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) {
String name = EpicFurnaces.getInstance().getLocale().getMessage("general.nametag.nameformat")
.processPlaceholder("level", level).getMessage();
String name = EpicFurnaces.getPlugin(EpicFurnaces.class)
.getLocale()
.getMessage("general.nametag.nameformat")
.processPlaceholder("level", level)
.getMessage();
return formatText(name);
return TextUtils.formatText(name);
}
/**
@ -40,8 +37,9 @@ public class Methods {
* @return The serialized data.
*/
public static String serializeLocation(Location location) {
if (location == null)
if (location == null) {
return "";
}
String w = location.getWorld().getName();
double x = location.getBlockX();
double y = location.getBlockY();
@ -52,7 +50,7 @@ public class Methods {
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.
@ -61,121 +59,27 @@ public class Methods {
* @return The location that was serialized in the string.
*/
public static Location unserializeLocation(String str) {
if (str == null || str.equals(""))
if (str == null || str.equals("")) {
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;
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*"));
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);
serializeCache.put(cacheKey, location.clone());
SERIALIZE_CACHE.put(cacheKey, location.clone());
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;
}
}