From 65b789e201b5c9133248d1faf192696c7bddac3d Mon Sep 17 00:00:00 2001 From: Driftay Date: Mon, 2 Oct 2023 04:14:25 -0400 Subject: [PATCH] Added a initialization method for Addon Initiation to avoid heavy lifting on constructor initiation. Faction Addon: - Refactored Entirety of Configuration Handling - Added New Configuration Manager w/Loading Capabilities From Jar File - Refactored All Constructor Behavior to Avoid Heavy Lifting Loads. - Implemented Friendly Name Addon Behavior To Allow For User Friendly Implementation Of Addons Demonstrated Proper Immutability Via FAuditMenu, FactionLogs, FLogManager, FLogType, and LogTimer Implemented Method Separation For Better Readability in FAuditMenu, FactionLogs, FLogManager, FLogType, and LogTimer Refactored FAuditMenu, FactionLogs, FLogManager, FLogType, and LogTimer for Better Readability and Structure for Future Recode Improved Readability in BrigadierManager Implemented Method Separation In CmdDisband Fixed Issue With F List, Asyncrounous Task Causing List To Make Faction List Not In Proper Order. Added Configuration In FCommand Parsed NO_BALANCE Placeholder. Recoded Entirety Of FactionData Management System. Removed Macro Detection For SaberGUI Registry Added Method Separation For Better Readability In AsyncPlayerMap and FlightEnhance Fixed Issue With Slot Initiation For F Upgrade Not Registering Disabled Ones Fixed Issue With BannerManager Initiation Nulling On Disable Fixed Issue With Armor Swap CoreX Module. --- .../massivecraft/factions/FactionsPlugin.java | 12 +- .../factions/addon/AddonManager.java | 1 + .../factions/addon/FactionsAddon.java | 90 ++++++++++-- .../factions/cmd/BrigadierManager.java | 116 ++++++++------- .../massivecraft/factions/cmd/CmdDisband.java | 91 ++++++------ .../massivecraft/factions/cmd/CmdList.java | 126 ++++++++-------- .../massivecraft/factions/cmd/FCommand.java | 2 +- .../factions/cmd/audit/FAuditMenu.java | 92 +++++++----- .../factions/cmd/audit/FLogManager.java | 139 +++++++++--------- .../factions/cmd/audit/FLogType.java | 20 ++- .../factions/cmd/audit/FactionLogs.java | 65 +++----- .../factions/cmd/audit/LogTimer.java | 60 ++++---- .../factions/data/FactionData.java | 35 +++-- .../data/helpers/FactionDataHelper.java | 109 ++++++-------- .../data/listener/FactionDataListener.java | 12 +- .../data/task/FactionDataDeploymentTask.java | 2 +- .../factions/listeners/SaberGUIListener.java | 11 -- .../massivecraft/factions/tag/FactionTag.java | 4 +- .../massivecraft/factions/tag/PlayerTag.java | 2 +- .../util/ClipPlaceholderAPIManager.java | 4 +- .../factions/util/flight/FlightEnhance.java | 42 ++++-- .../util/flight/stuct/AsyncPlayerMap.java | 44 ++++-- .../massivecraft/factions/zcore/MCommand.java | 2 +- .../factions/zcore/file/CustomFile.java | 131 +++++++---------- .../factions/zcore/file/impl/FileManager.java | 76 +++++----- .../frame/fupgrades/FactionUpgradeFrame.java | 2 +- .../zcore/util/ShutdownParameter.java | 2 +- .../massivecraft/factions/zcore/util/TL.java | 3 + .../factions/zcore/util/TagReplacer.java | 6 +- .../saberdev/corex/listeners/ArmorSwap.java | 35 ++--- 30 files changed, 684 insertions(+), 652 deletions(-) diff --git a/src/main/java/com/massivecraft/factions/FactionsPlugin.java b/src/main/java/com/massivecraft/factions/FactionsPlugin.java index 3aa2073ae..a2955797d 100755 --- a/src/main/java/com/massivecraft/factions/FactionsPlugin.java +++ b/src/main/java/com/massivecraft/factions/FactionsPlugin.java @@ -218,7 +218,7 @@ public void onEnable() { Bukkit.getScheduler().runTaskLater(this, () -> { //To Add Addon Commands Into "Tab Completion Format" - if(factionsAddonHashMap.size() > 0) { + if (factionsAddonHashMap.size() > 0) { FCmdRoot.instance.addVariableCommands(); FCmdRoot.instance.rebuild(); } @@ -299,6 +299,13 @@ public Gson getGson() { @Override public void onDisable() { + + if (bannerManager != null) { + bannerManager.onDisable(this); + } + + ShutdownParameter.initShutdown(this); + if (this.AutoLeaveTask != null) { getServer().getScheduler().cancelTask(this.AutoLeaveTask); this.AutoLeaveTask = null; @@ -307,9 +314,6 @@ public void onDisable() { TextUtil.AUDIENCES.close(); } - bannerManager.onDisable(this); - ShutdownParameter.initShutdown(this); - super.onDisable(); } diff --git a/src/main/java/com/massivecraft/factions/addon/AddonManager.java b/src/main/java/com/massivecraft/factions/addon/AddonManager.java index da2adc7c0..0b2c84f11 100644 --- a/src/main/java/com/massivecraft/factions/addon/AddonManager.java +++ b/src/main/java/com/massivecraft/factions/addon/AddonManager.java @@ -63,6 +63,7 @@ public void loadAddons() { constructor = addonMainClass.getConstructor(FactionsPlugin.class); factionsAddon = (FactionsAddon) constructor.newInstance(plugin); FactionsPlugin.getInstance().getFactionsAddonHashMap().put(factionsAddon.getAddonName(), factionsAddon); + factionsAddon.initializeAddon(); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); diff --git a/src/main/java/com/massivecraft/factions/addon/FactionsAddon.java b/src/main/java/com/massivecraft/factions/addon/FactionsAddon.java index e6a25151b..37c801de7 100644 --- a/src/main/java/com/massivecraft/factions/addon/FactionsAddon.java +++ b/src/main/java/com/massivecraft/factions/addon/FactionsAddon.java @@ -1,52 +1,61 @@ package com.massivecraft.factions.addon; import com.massivecraft.factions.FactionsPlugin; -import com.massivecraft.factions.cmd.FCmdRoot; import com.massivecraft.factions.cmd.FCommand; import com.massivecraft.factions.util.Logger; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; -import java.util.Collections; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashSet; import java.util.Set; -/** - * @author SavageLabs Team - */ - public abstract class FactionsAddon { private final String addonName; private final FactionsPlugin plugin; + private File configFile; + private FileConfiguration config; + public FactionsAddon(final FactionsPlugin plugin) { this.plugin = plugin; - this.addonName = getClass().getName(); - enableAddon(); + this.addonName = getFriendlyName(); } - private void enableAddon() { + public void initializeAddon() { + loadConfig(); onEnable(); registerListeners(); registerFCommands(); Logger.print("Addon: " + getAddonName() + " loaded successfully!", Logger.PrefixType.DEFAULT); } - public void disableAddon() { + public void terminateAddon() { unregisterListeners(); onDisable(); } - public abstract void onEnable(); + protected abstract void onEnable(); + + protected abstract void onDisable(); - public abstract void onDisable(); + protected abstract String getFriendlyName(); - public Set listenersToRegister() { - return Collections.emptySet(); + protected Set listenersToRegister() { + return new HashSet<>(); } - public Set fCommandsToRegister() { - return Collections.emptySet(); + protected Set fCommandsToRegister() { + return new HashSet<>(); } public String getAddonName() { @@ -78,4 +87,53 @@ private void registerFCommands() { } } } + + public void loadConfig() { + Path path = Paths.get(plugin.getDataFolder().toString(), "configuration/addons", getAddonName().toLowerCase() + ".yml"); + configFile = path.toFile(); + + if (!Files.exists(path)) { + try { + exportConfig("/" + getAddonName().toLowerCase() + ".yml"); + } catch (Exception e) { + Logger.print("Error transferring config for " + getAddonName() + ": " + e.getMessage(), Logger.PrefixType.FAILED); + e.printStackTrace(); + } + } + config = YamlConfiguration.loadConfiguration(configFile); + } + + private void exportConfig(String resourceName) throws Exception { + try (InputStream stream = this.getClass().getResourceAsStream(resourceName); + OutputStream resStreamOut = Files.newOutputStream(Paths.get(plugin.getDataFolder().toString(), "configuration/addons", resourceName.toLowerCase()))) { + + if (stream == null) { + throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file."); + } + + byte[] buffer = new byte[4096]; + int readBytes; + while ((readBytes = stream.read(buffer)) > 0) { + resStreamOut.write(buffer, 0, readBytes); + } + Logger.print(getAddonName() + " config file successfully transferred!", Logger.PrefixType.DEFAULT); + } + } + + public void saveConfig() { + if (config == null || configFile == null) return; + try { + getConfig().save(configFile); + } catch (IOException e) { + Logger.print("Error saving config for " + getAddonName() + ": " + e.getMessage(), Logger.PrefixType.FAILED); + e.printStackTrace(); + } + } + + public FileConfiguration getConfig() { + if (config == null) { + loadConfig(); + } + return config; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java b/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java index 0b922d0de..9bad91150 100644 --- a/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java +++ b/src/main/java/com/massivecraft/factions/cmd/BrigadierManager.java @@ -16,81 +16,85 @@ public class BrigadierManager { - /** - * @author FactionsUUID Team - Modified By CmdrKittens - */ - - public Commodore commodore; - public LiteralArgumentBuilder brigadier = LiteralArgumentBuilder.literal("factions"); + private final Commodore commodore; + private final LiteralArgumentBuilder brigadier; public BrigadierManager() { commodore = CommodoreProvider.getCommodore(FactionsPlugin.getInstance()); + brigadier = LiteralArgumentBuilder.literal("factions"); } public void build() { commodore.register(brigadier.build()); - // Add factions children to f alias + // Register 'f' alias with all children of 'factions' LiteralArgumentBuilder fLiteral = LiteralArgumentBuilder.literal("f"); - for (CommandNode node : brigadier.getArguments()) fLiteral.then(node); + for (CommandNode node : brigadier.getArguments()) { + + fLiteral.then(node); + } commodore.register(fLiteral.build()); } public void addSubCommand(FCommand subCommand) { - // Register brigadier to all command aliases for (String alias : subCommand.aliases) { LiteralArgumentBuilder literal = LiteralArgumentBuilder.literal(alias); if (subCommand.requirements.brigadier != null) { - // If the requirements explicitly provide a BrigadierProvider then use it - Class brigadierProvider = subCommand.requirements.brigadier; - try { - Constructor constructor = brigadierProvider.getDeclaredConstructor(); - brigadier.then(constructor.newInstance().get(literal)); - } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | - InvocationTargetException exception) { - exception.printStackTrace(); - } + registerUsingProvider(subCommand, literal); + } else { + registerGeneratedBrigadier(subCommand, literal); + } + } + } + + private void registerUsingProvider(FCommand subCommand, LiteralArgumentBuilder literal) { + Class brigadierProvider = subCommand.requirements.brigadier; + try { + Constructor constructor = brigadierProvider.getDeclaredConstructor(); + brigadier.then(constructor.newInstance().get(literal)); + } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | + InvocationTargetException exception) { + exception.printStackTrace(); + } + } + + private void registerGeneratedBrigadier(FCommand subCommand, LiteralArgumentBuilder literal) { + List> argsStack = generateArgsStack(subCommand); + + RequiredArgumentBuilder previous = null; + for (int i = argsStack.size() - 1; i >= 0; i--) { + if (previous == null) { + previous = argsStack.get(i); } else { - // Generate our own based on args - quite ugly - - // We create an orderly stack of all args, required and optional, format them differently - List> stack = new ArrayList<>(subCommand.requiredArgs.size() + subCommand.optionalArgs.size()); - for (String required : subCommand.requiredArgs) { - // Simply add the arg name as required - stack.add(RequiredArgumentBuilder.argument(required, StringArgumentType.word())); - } - - for (Map.Entry optionalEntry : subCommand.optionalArgs.entrySet()) { - RequiredArgumentBuilder optional; - - // Optional without default - if (optionalEntry.getKey().equalsIgnoreCase(optionalEntry.getValue())) { - optional = RequiredArgumentBuilder.argument(":" + optionalEntry.getKey(), StringArgumentType.word()); - // Optional with default, explain - } else { - optional = RequiredArgumentBuilder.argument(optionalEntry.getKey() + "|" + optionalEntry.getValue(), StringArgumentType.word()); - } - - stack.add(optional); - } - - // Reverse the stack and apply .then() - RequiredArgumentBuilder previous = null; - for (int i = stack.size() - 1; i >= 0; i--) { - if (previous == null) { - previous = stack.get(i); - } else { - previous = stack.get(i).then(previous); - } - } - - if (previous == null) { - brigadier.then(literal); - } else { - brigadier.then(literal.then(previous)); - } + previous = argsStack.get(i).then(previous); } } + + if (previous == null) { + brigadier.then(literal); + } else { + brigadier.then(literal.then(previous)); + } + } + + private List> generateArgsStack(FCommand subCommand) { + List> stack = new ArrayList<>(subCommand.requiredArgs.size() + subCommand.optionalArgs.size()); + + for (String required : subCommand.requiredArgs) { + stack.add(RequiredArgumentBuilder.argument(required, StringArgumentType.word())); + } + + for (Map.Entry optionalEntry : subCommand.optionalArgs.entrySet()) { + RequiredArgumentBuilder optional; + if (optionalEntry.getKey().equalsIgnoreCase(optionalEntry.getValue())) { + optional = RequiredArgumentBuilder.argument(":" + optionalEntry.getKey(), StringArgumentType.word()); + } else { + optional = RequiredArgumentBuilder.argument(optionalEntry.getKey() + "|" + optionalEntry.getValue(), StringArgumentType.word()); + } + stack.add(optional); + } + + return stack; } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java index 3890211b2..eddede51a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -22,8 +22,7 @@ public class CmdDisband extends FCommand { * @author FactionsUUID Team - Modified By CmdrKittens */ - private static HashMap disbandMap = new HashMap<>(); - + private final HashMap disbandMap; public CmdDisband() { super(); @@ -31,28 +30,21 @@ public CmdDisband() { this.optionalArgs.put("faction tag", "yours"); this.requirements = new CommandRequirements.Builder(Permission.DISBAND) .build(); + this.disbandMap = new HashMap<>(); } @Override public void perform(CommandContext context) { - long time; - // The faction, default to your own.. but null if console sender. Faction faction = context.argAsFaction(0, context.fPlayer == null ? null : context.faction); if (faction == null) return; boolean isMyFaction = context.fPlayer != null && faction == context.faction; - if (!isMyFaction) { - if (!Permission.DISBAND_ANY.has(context.sender, true)) return; - } + if (!isMyFaction && !Permission.DISBAND_ANY.has(context.sender, true)) return; - - if (context.fPlayer != null && !context.fPlayer.isAdminBypassing()) { - Access access = faction.getAccess(context.fPlayer, PermissableAction.DISBAND); - if (context.fPlayer.getRole() != Role.LEADER && faction.getFPlayerLeader() != context.fPlayer && access != Access.ALLOW) { - context.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); - return; - } + if (context.fPlayer != null && !context.fPlayer.isAdminBypassing() && !hasDisbandPermission(context, faction)) { + context.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); + return; } if (!faction.isNormal()) { @@ -64,7 +56,6 @@ public void perform(CommandContext context) { return; } - // THis means they are a console command sender. if (context.player == null) { faction.disband(null, PlayerDisbandReason.PLUGIN); return; @@ -75,44 +66,56 @@ public void perform(CommandContext context) { return; } + if (!isConfirmingDisband(context)) { + promptDisbandConfirmation(context, faction); + return; + } - boolean access = context.fPlayer.getPlayer().hasMetadata("disband_confirm") && (time = context.fPlayer.getPlayer().getMetadata("disband_confirm").get(0).asLong()) != 0L && System.currentTimeMillis() - time <= TimeUnit.SECONDS.toMillis(3L); + broadcastDisband(context, faction); + faction.disband(context.player, PlayerDisbandReason.COMMAND); + Cooldown.setCooldown(context.fPlayer.getPlayer(), "disbandCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-disband")); + } - if (!access) { - if (Conf.useDisbandGUI && (!context.fPlayer.isAdminBypassing() || !context.player.isOp())) { - if (!disbandMap.containsKey(context.player.getUniqueId().toString())) { - new FDisbandFrame(context.player).openGUI(FactionsPlugin.getInstance()); - return; - } - } - } + private boolean hasDisbandPermission(CommandContext context, Faction faction) { + Access access = faction.getAccess(context.fPlayer, PermissableAction.DISBAND); + return context.fPlayer.getRole() == Role.LEADER || faction.getFPlayerLeader() == context.fPlayer || access == Access.ALLOW; + } + + private boolean isConfirmingDisband(CommandContext context) { + long time; + boolean access = context.fPlayer.getPlayer().hasMetadata("disband_confirm") + && (time = context.fPlayer.getPlayer().getMetadata("disband_confirm").get(0).asLong()) != 0L + && System.currentTimeMillis() - time <= TimeUnit.SECONDS.toMillis(3L); + return access || Conf.useDisbandGUI && (!context.fPlayer.isAdminBypassing() || !context.player.isOp()) && !disbandMap.containsKey(context.player.getUniqueId().toString()); + } - // check for tnt before disbanding. + private void promptDisbandConfirmation(CommandContext context, Faction faction) { if (!disbandMap.containsKey(context.player.getUniqueId().toString()) && faction.getTnt() > 0) { context.msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", String.valueOf(faction.getTnt()))); disbandMap.put(context.player.getUniqueId().toString(), faction.getId()); Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.getInstance(), () -> disbandMap.remove(context.player.getUniqueId().toString()), 200L); - } else if (faction.getId().equals(disbandMap.get(context.player.getUniqueId().toString())) || faction.getTnt() == 0) { - if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast", true)) { - - String yours_message = TL.COMMAND_DISBAND_BROADCAST_YOURS.toString() - .replace("{claims}", String.valueOf(faction.getAllClaims().size())); - String notyours_message = TL.COMMAND_DISBAND_BROADCAST_NOTYOURS.toString() - .replace("{claims}", String.valueOf(faction.getAllClaims().size())); - - for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { - String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(follower); - if (follower.getFaction() == faction) { - follower.msg(yours_message, amountString); - } else { - follower.msg(notyours_message, amountString, faction.getTag(follower)); - } + } else if (!disbandMap.containsKey(context.player.getUniqueId().toString())) { + new FDisbandFrame(context.player).openGUI(FactionsPlugin.getInstance()); + } + } + + private void broadcastDisband(CommandContext context, Faction faction) { + if (FactionsPlugin.getInstance().getConfig().getBoolean("faction-disband-broadcast", true)) { + String yours_message = TL.COMMAND_DISBAND_BROADCAST_YOURS.toString().replace("{claims}", String.valueOf(faction.getAllClaims().size())); + String notyours_message = TL.COMMAND_DISBAND_BROADCAST_NOTYOURS.toString().replace("{claims}", String.valueOf(faction.getAllClaims().size())); + String amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.describeTo(null); + if (yours_message.contains("{player}") || notyours_message.contains("{player}")) { + amountString = context.sender instanceof ConsoleCommandSender ? TL.GENERIC_SERVERADMIN.toString() : context.fPlayer.getName(); + } + for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { + if (follower.getFaction() == faction) { + follower.msg(yours_message, amountString); + } else { + follower.msg(notyours_message, amountString, faction.getTag(follower)); } - } else { - context.player.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); } - faction.disband(context.player, PlayerDisbandReason.COMMAND); - Cooldown.setCooldown(context.fPlayer.getPlayer(), "disbandCooldown", FactionsPlugin.getInstance().getConfig().getInt("fcooldowns.f-disband")); + } else { + context.player.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdList.java b/src/main/java/com/massivecraft/factions/cmd/CmdList.java index 0a8590139..112d5d1d7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdList.java @@ -19,7 +19,7 @@ public class CmdList extends FCommand { * @author FactionsUUID Team - Modified By CmdrKittens */ - private String[] defaults = new String[3]; + private final String[] defaults = new String[3]; public CmdList() { super(); @@ -40,79 +40,77 @@ public CmdList() { @Override public void perform(CommandContext context) { - FactionsPlugin.getInstance().getServer().getScheduler().runTaskAsynchronously(FactionsPlugin.instance, () -> { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!context.payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) - return; + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!context.payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) + return; - List factionList = Factions.getInstance().getAllNormalFactions(); + List factionList = Factions.getInstance().getAllNormalFactions(); - // remove exempt factions - if (context.fPlayer != null && context.fPlayer.getPlayer() != null && !context.fPlayer.getPlayer().hasPermission("factions.show.bypassexempt")) { - List exemptFactions = FactionsPlugin.getInstance().getConfig().getStringList("show-exempt"); + // remove exempt factions + if (context.fPlayer != null && context.fPlayer.getPlayer() != null && !context.fPlayer.getPlayer().hasPermission("factions.show.bypassexempt")) { + List exemptFactions = FactionsPlugin.getInstance().getConfig().getStringList("show-exempt"); - factionList.removeIf(next -> exemptFactions.contains(next.getTag())); - } + factionList.removeIf(next -> exemptFactions.contains(next.getTag())); + } - // Sort by total followers first - factionList.sort((f1, f2) -> { - int f1Size = f1.getFPlayers().size(); - int f2Size = f2.getFPlayers().size(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); - - // Then sort by how many members are online now - factionList.sort((f1, f2) -> { - int f1Size = f1.getFPlayersWhereOnline(true).size(); - int f2Size = f2.getFPlayersWhereOnline(true).size(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); - - ArrayList lines = new ArrayList<>(); - - factionList.add(0, Factions.getInstance().getWilderness()); - - final int pageheight = 9; - int pagenumber = context.argAsInt(0, 1); - int pagecount = (factionList.size() / pageheight) + 1; - if (pagenumber > pagecount) { - pagenumber = pagecount; - } else if (pagenumber < 1) { - pagenumber = 1; - } - int start = (pagenumber - 1) * pageheight; - int end = start + pageheight; - if (end > factionList.size()) { - end = factionList.size(); + // Sort by total followers first + factionList.sort((f1, f2) -> { + int f1Size = f1.getFPlayers().size(); + int f2Size = f2.getFPlayers().size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; } + return 0; + }); - - String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]); - assert header != null; - header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); - lines.add(TextUtil.parse(header)); - - for (Faction faction : factionList.subList(start, end)) { - if (faction.isWilderness()) { - lines.add(TextUtil.parse(TagUtil.parsePlain(faction, FactionsPlugin.getInstance().getConfig().getString("list.factionless", defaults[1])))); - continue; - } - lines.add(TextUtil.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2])))); + // Then sort by how many members are online now + factionList.sort((f1, f2) -> { + int f1Size = f1.getFPlayersWhereOnline(true).size(); + int f2Size = f2.getFPlayersWhereOnline(true).size(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; } - context.sendMessage(lines); + return 0; }); + + ArrayList lines = new ArrayList<>(); + + factionList.add(0, Factions.getInstance().getWilderness()); + + final int pageheight = 9; + int pagenumber = context.argAsInt(0, 1); + int pagecount = (factionList.size() / pageheight) + 1; + if (pagenumber > pagecount) { + pagenumber = pagecount; + } else if (pagenumber < 1) { + pagenumber = 1; + } + int start = (pagenumber - 1) * pageheight; + int end = start + pageheight; + if (end > factionList.size()) { + end = factionList.size(); + } + + + String header = FactionsPlugin.getInstance().getConfig().getString("list.header", defaults[0]); + assert header != null; + header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); + lines.add(TextUtil.parse(header)); + + for (Faction faction : factionList.subList(start, end)) { + if (faction.isWilderness()) { + lines.add(TextUtil.parse(TagUtil.parsePlain(faction, FactionsPlugin.getInstance().getConfig().getString("list.factionless", defaults[1])))); + continue; + } + lines.add(TextUtil.parse(TagUtil.parsePlain(faction, context.fPlayer, FactionsPlugin.getInstance().getConfig().getString("list.entry", defaults[2])))); + } + context.sendMessage(lines); } @Override diff --git a/src/main/java/com/massivecraft/factions/cmd/FCommand.java b/src/main/java/com/massivecraft/factions/cmd/FCommand.java index 96470f642..ab08eaccf 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCommand.java @@ -158,7 +158,7 @@ public List getToolTips(Faction faction) { public String replaceFPlayerTags(String s, FPlayer player) { if (s.contains("{balance}")) { - String balance = Econ.isSetup() ? Econ.getFriendlyBalance(player) : "no balance"; + String balance = Econ.isSetup() ? Econ.getFriendlyBalance(player) : TL.NO_BALANCE_PLACEHOLDER_PARSED.toString(); s = TextUtil.replace(s, "{balance}", balance); } if (s.contains("{lastSeen}")) { diff --git a/src/main/java/com/massivecraft/factions/cmd/audit/FAuditMenu.java b/src/main/java/com/massivecraft/factions/cmd/audit/FAuditMenu.java index 5274d9708..131bfb8a6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/audit/FAuditMenu.java +++ b/src/main/java/com/massivecraft/factions/cmd/audit/FAuditMenu.java @@ -15,64 +15,86 @@ import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.ClickType; +import org.bukkit.inventory.ItemStack; +import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class FAuditMenu extends GUIMenu { + private final Player player; - private boolean showTimestamps = true; private final Faction faction; + private boolean showTimestamps = true; public FAuditMenu(Player player, Faction faction) { super("Faction Logs", 18); - this.faction = faction; this.player = player; + this.faction = faction; } + @Override public void drawItems() { + FactionLogs logs = FactionsPlugin.instance.getFlogManager().getFactionLogMap().get(faction.getId()); + if (logs == null) logs = new FactionLogs(); + for (FLogType type : FLogType.values()) { if (type.getSlot() == -1) continue; + if (type != FLogType.F_TNT || FactionsPlugin.getInstance().getConfig().getBoolean("f-points.Enabled")) { - FactionLogs logs = FactionsPlugin.instance.getFlogManager().getFactionLogMap().get(faction.getId()); - if (logs == null) logs = new FactionLogs(); LinkedList recentLogs = logs.getMostRecentLogs().get(type); - if (recentLogs == null) recentLogs = Lists.newLinkedList(); - List lore = Lists.newArrayList("", CC.GreenB + "Recent Logs " + CC.Green + "(" + CC.GreenB + recentLogs.size() + CC.Green + ")"); - int added = 0; - Iterator backwars = recentLogs.descendingIterator(); - int logsPerPage = 20; - while (backwars.hasNext()) { - FactionLogs.FactionLog log = backwars.next(); - if (added >= logsPerPage) break; - String length = log.getLogLine(type, showTimestamps); - lore.add(" " + CC.Yellow + length); - ++added; - } - int logSize = recentLogs.size(); - int logsLeft = logSize - logsPerPage; - if (logsLeft > 0) lore.add(CC.YellowB + logsLeft + CC.Yellow + " more logs..."); - lore.add(""); - if (logsLeft > 0) lore.add(CC.Yellow + "Left-Click " + CC.Gray + "to view more logs"); - lore.add(CC.Yellow + "Right-Click " + CC.Gray + "to toggle timestamps"); - setItem(type.getSlot(), (new ClickableItemStack((new ItemBuilder(type.getMaterial())).name(type.getDisplayName()).lore(lore).build())).setClickCallback((click) -> { - click.setCancelled(true); - if (click.getClick() == ClickType.RIGHT) { - showTimestamps = !showTimestamps; - drawItems(); - } else { - if (logsLeft <= 0) { - player.sendMessage(CC.Red + "No extra logs to load."); - return; - } - Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, () -> (new FAuditLogMenu(player, faction, type)).open(player)); - } - })); + if (recentLogs == null) recentLogs = new LinkedList<>(); + + List lore = buildLoreForItem(type, recentLogs); + setItem(type.getSlot(), buildClickableItem(type, lore)); } } } + private List buildLoreForItem(FLogType type, LinkedList recentLogs) { + List lore = new ArrayList<>(); + lore.add(""); + lore.add(CC.GreenB + "Recent Logs " + CC.Green + "(" + CC.GreenB + recentLogs.size() + CC.Green + ")"); + + int logsPerPage = 20; + Iterator backwards = recentLogs.descendingIterator(); + while (backwards.hasNext() && lore.size() < logsPerPage) { + String logLine = backwards.next().getLogLine(type, showTimestamps); + lore.add(" " + CC.Yellow + logLine); + } + + int logsLeft = recentLogs.size() - logsPerPage; + if (logsLeft > 0) { + lore.add(CC.YellowB + logsLeft + CC.Yellow + " more logs..."); + lore.add(""); + lore.add(CC.Yellow + "Left-Click " + CC.Gray + "to view more logs"); + } + lore.add(CC.Yellow + "Right-Click " + CC.Gray + "to toggle timestamps"); + + return lore; + } + + private ClickableItemStack buildClickableItem(FLogType type, List lore) { + ItemStack item = new ItemBuilder(type.getMaterial()).name(type.getDisplayName()).lore(lore).build(); + + return new ClickableItemStack(item).setClickCallback(click -> { + click.setCancelled(true); + if (click.getClick() == ClickType.RIGHT) { + showTimestamps = !showTimestamps; + drawItems(); + } else { + int logsLeft = lore.size() - 20; // 20 is the logsPerPage as used earlier + if (logsLeft <= 0) { + player.sendMessage(CC.Red + "No extra logs to load."); + return; + } + Bukkit.getScheduler().scheduleSyncDelayedTask(FactionsPlugin.instance, + () -> new FAuditLogMenu(player, faction, type).open(player)); + } + }); + } + static class FAuditLogMenu extends GUIMenu { private final Player player; private final Faction faction; diff --git a/src/main/java/com/massivecraft/factions/cmd/audit/FLogManager.java b/src/main/java/com/massivecraft/factions/cmd/audit/FLogManager.java index 13dfd6fa7..7dc8cb8e4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/audit/FLogManager.java +++ b/src/main/java/com/massivecraft/factions/cmd/audit/FLogManager.java @@ -12,97 +12,100 @@ import org.bukkit.Bukkit; import java.io.File; +import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; public class FLogManager { + private Map factionLogMap = new ConcurrentHashMap<>(); private File logFile; - private Type logToken = (new TypeToken>() { - }).getType(); + private Type logToken = (new TypeToken>() {}).getType(); private Map logTimers = new ConcurrentHashMap<>(); private boolean saving = false; - public FLogManager() { - } + public FLogManager() {} public void log(Faction faction, FLogType type, String... arguments) { - FactionLogs logs = factionLogMap.computeIfAbsent(faction.getId(), (n) -> new FactionLogs()); + FactionLogs logs = factionLogMap.computeIfAbsent(faction.getId(), n -> new FactionLogs()); logs.log(type, arguments); } public void loadLogs(FactionsPlugin plugin) { try { - logFile = new File(plugin.getDataFolder() + File.separator + "data", "factionLogs.json"); - if (!logFile.exists()) { - logFile.createNewFile(); - } + setupLogFile(plugin); + loadFactionLogData(); - factionLogMap = (Map) JSONUtils.fromJson(logFile, logToken); - if (factionLogMap == null) { - factionLogMap = new ConcurrentHashMap<>(); - } + factionLogMap.forEach(this::handleFactionLog); + } catch (Exception e) { + e.printStackTrace(); + } - factionLogMap.forEach((factionId, factionLogs) -> { + scheduleLogMaintenance(); + } - Faction faction = Factions.getInstance().getFactionById(factionId); - if (faction != null && faction.isNormal()) { - factionLogs.checkExpired(); - if (factionLogs.isEmpty()) { - factionLogMap.remove(factionId); - } + private void setupLogFile(FactionsPlugin plugin) throws IOException { + logFile = new File(plugin.getDataFolder() + File.separator + "data", "factionLogs.json"); + if (!logFile.exists()) { + logFile.createNewFile(); + } + } - } else { - Bukkit.getLogger().info("Removing dead faction logs for " + factionId + "!"); - factionLogMap.remove(factionId); - } - }); - } catch (Exception e) { - e.printStackTrace(); + private void loadFactionLogData() throws Exception { + factionLogMap = (Map) JSONUtils.fromJson(logFile, logToken); + if (factionLogMap == null) { + factionLogMap = new ConcurrentHashMap<>(); } + } + private void handleFactionLog(String factionId, FactionLogs factionLogs) { + Faction faction = Factions.getInstance().getFactionById(factionId); + + if (faction != null && faction.isNormal()) { + factionLogs.checkExpired(); + if (factionLogs.isEmpty()) { + factionLogMap.remove(factionId); + } + } else { + Bukkit.getLogger().info("Removing dead faction logs for " + factionId + "!"); + factionLogMap.remove(factionId); + } + } + + private void scheduleLogMaintenance() { Bukkit.getScheduler().scheduleSyncRepeatingTask(FactionsPlugin.instance, () -> { if (saving) { Bukkit.getLogger().info("Ignoring saveLogs scheduler due to saving == true!"); - } else { - logTimers.forEach((uuid, logTimer) -> { - if (logTimer != null && logTimer.getFactionId() != null) { - Faction faction = Factions.getInstance().getFactionById(logTimer.getFactionId()); - if (faction == null) { - logTimers.remove(uuid); - Bukkit.getLogger().info("Null faction for logs " + logTimer.getFactionId()); - } else { - if (logTimer.isEmpty()) { - logTimers.remove(uuid); - } - } - } else { - logTimers.remove(uuid); - } - }); + return; } + + logTimers.entrySet().removeIf(entry -> { + LogTimer logTimer = entry.getValue(); + + if (logTimer == null || logTimer.getFactionId() == null || Factions.getInstance().getFactionById(logTimer.getFactionId()) == null) { + Bukkit.getLogger().info("Null faction for logs " + logTimer.getFactionId()); + return true; + } + + return logTimer.isEmpty(); + }); }, 20L, 400L); } public void pushPendingLogs(LogTimer.TimerType type) { - Faction faction = null; - - for (Map.Entry uuidLogTimerEntry : getLogTimers().entrySet()) { - LogTimer logTimer = uuidLogTimerEntry.getValue(); - if (faction == null) { - faction = Factions.getInstance().getFactionById(logTimer.getFactionId()); - } + for (LogTimer logTimer : getLogTimers().values()) { + Faction faction = Factions.getInstance().getFactionById(logTimer.getFactionId()); + if (faction == null) continue; if (type != null) { Map timers = logTimer.get(type); - if (timers != null && faction != null) { + if (timers != null) { logTimer.pushLogs(faction, type); } - } else if (faction != null) { - Faction finalFaction = faction; - logTimer.keySet().forEach((timerType) -> logTimer.pushLogs(finalFaction, timerType)); + } else { + logTimer.keySet().forEach(timerType -> logTimer.pushLogs(faction, timerType)); logTimer.clear(); } } @@ -110,29 +113,23 @@ public void pushPendingLogs(LogTimer.TimerType type) { if (type == null) { getLogTimers().clear(); } - } public void saveLogs() { if (saving) { Bukkit.getLogger().info("Ignoring saveLogs due to saving==true!"); - } else { - saving = true; + return; + } - try { - pushPendingLogs(null); - } catch (Exception e) { - Bukkit.getLogger().info("error pushing pending logs: " + e.getMessage()); - e.printStackTrace(); - } - - try { - JSONUtils.saveJSONToFile(logFile, factionLogMap, logToken); - } catch (Exception e1) { - Bukkit.getLogger().info("ERROR SAVING JSON LOGS: " + e1.getMessage()); - e1.printStackTrace(); - } + saving = true; + try { + pushPendingLogs(null); + JSONUtils.saveJSONToFile(logFile, factionLogMap, logToken); + } catch (Exception e) { + Bukkit.getLogger().info("Error occurred: " + e.getMessage()); + e.printStackTrace(); + } finally { saving = false; } } @@ -144,4 +141,4 @@ public Map getFactionLogMap() { public Map getLogTimers() { return logTimers; } -} +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/audit/FLogType.java b/src/main/java/com/massivecraft/factions/cmd/audit/FLogType.java index ac1a2bb70..e4262cbeb 100644 --- a/src/main/java/com/massivecraft/factions/cmd/audit/FLogType.java +++ b/src/main/java/com/massivecraft/factions/cmd/audit/FLogType.java @@ -4,6 +4,7 @@ import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.util.CC; import org.bukkit.Material; +import org.bukkit.configuration.Configuration; /** * @author Saser @@ -24,16 +25,23 @@ public enum FLogType { RANK_EDIT("&e%s&7 set &e%s&7 to %s", 3), F_TNT("&e%s&7 %s &e%s", 3); - private String msg; - private int requiredArgs; + private final String msg; + private final int requiredArgs; + + // Cached for better performance + private static final Configuration CONFIG = FactionsPlugin.getInstance().getConfig(); FLogType(String msg, int requiredArgs) { this.msg = msg; this.requiredArgs = requiredArgs; } + private String getConfigString(String pathSuffix) { + return CONFIG.getString("faudit-gui." + pathSuffix + "." + name().toLowerCase()); + } + public String getDisplayName() { - return CC.translate(FactionsPlugin.getInstance().getConfig().getString("faudit-gui.names." + name().toLowerCase())); + return CC.translate(getConfigString("names")); } @Override @@ -42,11 +50,11 @@ public String toString() { } public int getSlot() { - return FactionsPlugin.getInstance().getConfig().getInt("faudit-gui.slots." + name().toLowerCase()); + return CONFIG.getInt("faudit-gui.slots." + name().toLowerCase()); } public Material getMaterial() { - return XMaterial.matchXMaterial(FactionsPlugin.getInstance().getConfig().getString("faudit-gui.materials." + name().toLowerCase())).get().parseMaterial(); + return XMaterial.matchXMaterial(getConfigString("materials")).get().parseMaterial(); } public String getMsg() { @@ -56,4 +64,4 @@ public String getMsg() { public int getRequiredArgs() { return this.requiredArgs; } -} +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/audit/FactionLogs.java b/src/main/java/com/massivecraft/factions/cmd/audit/FactionLogs.java index 5370e2596..2c960d296 100644 --- a/src/main/java/com/massivecraft/factions/cmd/audit/FactionLogs.java +++ b/src/main/java/com/massivecraft/factions/cmd/audit/FactionLogs.java @@ -4,38 +4,34 @@ * @author Saser */ -import com.google.common.collect.Lists; -import com.massivecraft.factions.util.CC; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import java.text.SimpleDateFormat; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; public class FactionLogs { - public static transient SimpleDateFormat format = new SimpleDateFormat("MM/dd hh:mmaa"); //MM/dd hh:mmaa - private Map> mostRecentLogs = new ConcurrentHashMap<>(); + + public static final SimpleDateFormat FORMAT = new SimpleDateFormat("MM/dd hh:mmaa"); + + private final Map> mostRecentLogs = new ConcurrentHashMap<>(); public FactionLogs() { } public void log(FLogType type, String... arguments) { if (type.getRequiredArgs() > arguments.length) { - Bukkit.getLogger().info("INVALID ARGUMENT COUNT MET: " + type.getRequiredArgs() + " REQUIRED: "); - Thread.dumpStack(); + Bukkit.getLogger().warning("Invalid argument count met. Required: " + type.getRequiredArgs()); + new Exception().printStackTrace(); } else { - LinkedList logs = mostRecentLogs.computeIfAbsent(type, (lists) -> new LinkedList<>()); - logs.add(new FactionLog(System.currentTimeMillis(), Lists.newArrayList(arguments))); + LinkedList logs = mostRecentLogs.computeIfAbsent(type, k -> new LinkedList<>()); + logs.add(new FactionLog(System.currentTimeMillis(), Arrays.asList(arguments))); int maxLog = type == FLogType.F_TNT ? 200 : 60; if (logs.size() > maxLog) { logs.pop(); } - } } @@ -45,32 +41,16 @@ public boolean isEmpty() { public void checkExpired() { long duration = TimeUnit.DAYS.toMillis(7L); - List toRemove = Lists.newArrayList(); + List toRemove = new LinkedList<>(); mostRecentLogs.forEach((logType, logs) -> { - if (logs == null) { + if (logs == null || (logType != FLogType.F_TNT && logs.isEmpty())) { toRemove.add(logType); - } else if (logType != FLogType.F_TNT) { - Iterator iter = logs.iterator(); - while (iter.hasNext()) { - try { - FactionLog log = iter.next(); - if (log == null || log.isExpired(duration)) { - iter.remove(); - } - } catch (Exception e) { - Bukkit.getLogger().info("ERROR TRYING TO GET next FACTION LOG: " + e.getMessage()); - try { - iter.remove(); - } catch (Exception e1) { - e1.printStackTrace(); - } - } - } - if (logs.isEmpty()) - toRemove.add(logType); + return; } + + logs.removeIf(log -> log == null || log.isExpired(duration)); }); - toRemove.forEach((rem) -> mostRecentLogs.remove(rem)); + toRemove.forEach(mostRecentLogs::remove); } public Map> getMostRecentLogs() { @@ -78,12 +58,12 @@ public Map> getMostRecentLogs() { } public static class FactionLog { - private long t; - private List a; + private final long t; + private final List a; public FactionLog(long t, List a) { this.t = t; - this.a = a; + this.a = a != null ? new ArrayList<>(a) : new ArrayList<>(); } public boolean isExpired(long duration) { @@ -94,12 +74,9 @@ public String getLogLine(FLogType type, boolean timestamp) { String[] args = a.toArray(new String[0]); String timeFormat = ""; if (timestamp) { - timeFormat = FactionLogs.format.format(t); - if (timeFormat.startsWith("0")) { - timeFormat = timeFormat.substring(1); - } + timeFormat = FORMAT.format(new Date(t)); } - return String.format(CC.translate(type.getMsg()), args) + (timestamp ? ChatColor.GRAY + " - " + timeFormat : ""); + return String.format(ChatColor.translateAlternateColorCodes('&', type.getMsg()), (Object[]) args) + (timestamp ? ChatColor.GRAY + " - " + timeFormat : ""); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/audit/LogTimer.java b/src/main/java/com/massivecraft/factions/cmd/audit/LogTimer.java index 146193c58..4b5b3970d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/audit/LogTimer.java +++ b/src/main/java/com/massivecraft/factions/cmd/audit/LogTimer.java @@ -16,8 +16,9 @@ import java.util.concurrent.atomic.AtomicInteger; public class LogTimer extends ConcurrentHashMap> { - private String factionId; - private String username; + + private final String factionId; + private final String username; public LogTimer(String username, String factionId) { this.username = username; @@ -25,35 +26,38 @@ public LogTimer(String username, String factionId) { } public Map getCurrentTimersOrCreate(LogTimer.TimerType type) { - return this.computeIfAbsent(type, (m) -> new ConcurrentHashMap<>()); + return this.computeIfAbsent(type, k -> new ConcurrentHashMap<>()); } public LogTimer.Timer attemptLog(LogTimer.TimerType type, LogTimer.TimerSubType subType, long increment) { - return this.getCurrentTimersOrCreate(type).computeIfAbsent(subType, (e) -> new Timer(System.currentTimeMillis(), 0L, null)).increment(increment); + return this.getCurrentTimersOrCreate(type) + .computeIfAbsent(subType, k -> new Timer(System.currentTimeMillis(), 0L, null)) + .increment(increment); } public void pushLogs(Faction faction, LogTimer.TimerType type) { - forEach((timerType, map) -> { - if (timerType == type) { - if (timerType == LogTimer.TimerType.SPAWNER_EDIT) { - map.forEach((subTimer, timer) -> { - Map entityCounts = new HashMap<>(); - Map currentCounts = (Map) timer.getExtraData(); - if (currentCounts != null) { - currentCounts.forEach((data, ints) -> { - EntityType types = EntityType.fromId(data.getData()); - if (types == null) { - //Bukkit.getLogger().info("Unable to find EntityType for " + data.getData() + " for " + subTimer + " for fac " + factionId + "!"); - } else { - entityCounts.computeIfAbsent(types, (e) -> new AtomicInteger(0)).addAndGet(ints.get()); - } - }); - entityCounts.forEach((entityType, count) -> FactionsPlugin.instance.getFlogManager().log(faction, FLogType.SPAWNER_EDIT, username, subTimer == TimerSubType.SPAWNER_BREAK ? "broke" : "placed", count.get() + "x", StringUtils.capitaliseAllWords(entityType.name().toLowerCase().replace("_", " ")))); - } - }); - } + Map specificTimer = get(type); + if (specificTimer == null || type != LogTimer.TimerType.SPAWNER_EDIT) return; + + specificTimer.forEach((subTimer, timer) -> { + Map entityCounts = new HashMap<>(); + Map currentCounts = (Map) timer.getExtraData(); + + if (currentCounts != null) { + currentCounts.forEach((data, ints) -> { + EntityType entityType = EntityType.fromId(data.getData()); + if (entityType != null) { + entityCounts.computeIfAbsent(entityType, k -> new AtomicInteger()) + .addAndGet(ints.get()); + } + }); + + entityCounts.forEach((entityType, count) -> + FactionsPlugin.instance.getFlogManager().log(faction, FLogType.SPAWNER_EDIT, username, subTimer == TimerSubType.SPAWNER_BREAK ? "broke" : "placed", count.get() + "x", StringUtils.capitaliseAllWords(entityType.name().toLowerCase().replace("_", " "))) + ); } }); + remove(type); } @@ -67,17 +71,11 @@ public String getUsername() { public enum TimerSubType { SPAWNER_BREAK, - SPAWNER_PLACE; - - TimerSubType() { - } + SPAWNER_PLACE } public enum TimerType { - SPAWNER_EDIT; - - TimerType() { - } + SPAWNER_EDIT } public class Timer { diff --git a/src/main/java/com/massivecraft/factions/data/FactionData.java b/src/main/java/com/massivecraft/factions/data/FactionData.java index b35c8e75d..d8812300a 100644 --- a/src/main/java/com/massivecraft/factions/data/FactionData.java +++ b/src/main/java/com/massivecraft/factions/data/FactionData.java @@ -18,6 +18,8 @@ */ public class FactionData { + private static final String FACTION_DATA_PATH = "/faction-data/"; + private final String factionID; private final String factionTag; private Map map; @@ -30,6 +32,15 @@ public FactionData(Faction faction) { this.saving = false; } + /** + * Generates the path for the faction file. + * + * @return The path as a string. + */ + private String getFactionFilePath() { + return FactionsPlugin.getInstance().getDataFolder() + FACTION_DATA_PATH + factionID + ".yml"; + } + public void addStoredValue(String key, Object value) { this.map.put(key, value); } @@ -39,9 +50,7 @@ public boolean isSaving() { } public YamlConfiguration getConfiguration() { - return YamlConfiguration - .loadConfiguration(new File(FactionsPlugin.getInstance().getDataFolder() - + "/faction-data/" + factionID + ".yml")); + return YamlConfiguration.loadConfiguration(new File(getFactionFilePath())); } public Object getStoredValue(String key) { @@ -80,10 +89,8 @@ public Object getValue(String key) { return this.map.computeIfAbsent(key, k -> getConfiguration().get(k)); } - public void deleteFactionData(Faction faction) { - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + this.factionID + ".yml"); + File file = new File(getFactionFilePath()); if(file.delete()) { Logger.print("Deleting faction-data for faction " + faction.getTag(), Logger.PrefixType.DEFAULT); @@ -97,15 +104,12 @@ public void save() { return; } this.saving = true; - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + this.factionID + ".yml"); + File file = new File(getFactionFilePath()); YamlConfiguration configuration = YamlConfiguration.loadConfiguration(file); Bukkit.getLogger().info("[FactionData] Saving " + this.factionTag + "'s Data to the disk"); - for (Map.Entry entry : map.entrySet()) { - String key = entry.getKey(); - Object value = entry.getValue(); - configuration.set(key, value); - } + + map.forEach(configuration::set); + try { configuration.save(file); } catch (IOException e) { @@ -115,10 +119,6 @@ public void save() { } } - @Deprecated - public void remove() { - FactionDataHelper.getData().remove(this); - } public String getFactionID() { return factionID; @@ -130,7 +130,6 @@ public String getFactionTag() { public void removeSafely() { this.save(); - this.remove(); } @Override diff --git a/src/main/java/com/massivecraft/factions/data/helpers/FactionDataHelper.java b/src/main/java/com/massivecraft/factions/data/helpers/FactionDataHelper.java index be0dd9b8f..9600cf459 100644 --- a/src/main/java/com/massivecraft/factions/data/helpers/FactionDataHelper.java +++ b/src/main/java/com/massivecraft/factions/data/helpers/FactionDataHelper.java @@ -11,10 +11,7 @@ import java.io.File; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; +import java.util.*; /** * @Author: Driftay @@ -22,55 +19,58 @@ */ public class FactionDataHelper { - private static List data; + private static final String FACTION_DATA_PATH = "/faction-data/"; + private static List data = new ArrayList<>(); + public static void init() { FactionsPlugin.getInstance().getServer().getPluginManager().registerEvents(new FactionDataListener(), FactionsPlugin.getInstance()); new FactionDataDeploymentTask().runTaskTimerAsynchronously(FactionsPlugin.getInstance(), 20, 20); - data = new ArrayList<>(); - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data"); - if (!file.exists()) { - file.mkdir(); + + File directory = getFactionDirectory(); + if (!directory.exists()) { + directory.mkdir(); } } public static void onDisable() { - for (int i = FactionDataHelper.data.size() - 1; i >= 0; i--) { - FactionData data = FactionDataHelper.data.get(i); - data.removeSafely(); + for (FactionData dataItem : data) { + dataItem.removeSafely(); } } - public FactionDataHelper(FactionData data) { - FactionDataHelper.data.add(data); + public static File getFactionFile(Faction faction) { + return new File(FactionsPlugin.getInstance().getDataFolder(), FACTION_DATA_PATH + faction.getId() + ".yml"); } + public static File getFactionDirectory() { + return new File(FactionsPlugin.getInstance().getDataFolder() + FACTION_DATA_PATH); + } - public static void createConfiguration(Faction faction) { - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + faction.getId() + ".yml"); - try { + public static void createConfiguration(Faction faction) throws IOException { + File file = getFactionFile(faction); + if (!file.exists()) { file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); } } - public static void setConfigValue(Faction faction, String key, Object value) { - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + faction.getId() + ".yml"); + public static void addFactionData(FactionData factionData) { + data.add(factionData); + } + + public static void removeFactionData(FactionData factionData) { + data.remove(factionData); + } + + public static void setConfigValue(Faction faction, String key, Object value) throws IOException { + File file = getFactionFile(faction); YamlConfiguration config = YamlConfiguration.loadConfiguration(file); config.set(key, value); - try { - config.save(file); - } catch (IOException e) { - e.printStackTrace(); - } + config.save(file); } public static YamlConfiguration getConfiguration(Faction faction) { - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + faction.getId() + ".yml"); + File file = getFactionFile(faction); if (!file.exists()) { return null; } @@ -78,54 +78,31 @@ public static YamlConfiguration getConfiguration(Faction faction) { } public static List getAllFactionFiles() { - List files = Lists.newArrayList(); - Collections.addAll(files, Objects.requireNonNull(new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/") - .listFiles())); - return files; + File directory = getFactionDirectory(); + File[] files = Objects.requireNonNull(directory.listFiles()); + return new ArrayList<>(Arrays.asList(files)); } - public static int removeDataFromFiles(String path) { + public static int removeDataFromFiles(String path) throws IOException { int count = 0; - for (File file : new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/") - .listFiles()) { + for (File file : Objects.requireNonNull(getFactionDirectory().listFiles())) { YamlConfiguration config = YamlConfiguration.loadConfiguration(file); config.set(path, null); - try { - config.save(file); - } catch (IOException e) { - e.printStackTrace(); - } + config.save(file); count++; } return count; } - public static File getFile(Faction faction) { - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + faction.getId() + ".yml"); - if (!file.exists()) { - return null; - } - return file; - } - public static boolean doesConfigurationExist(Faction faction) { - File file = new File(FactionsPlugin.getInstance().getDataFolder() + "/faction-data/" - + faction.getId() + ".yml"); - return file.exists(); - } - - public static List getData() { - return data; + return getFactionFile(faction).exists(); } public static FactionData findFactionData(String factionID) { - for (FactionData data : FactionDataHelper.data) { - if (data.getFactionID().equals(factionID)) { - return data; - } - } - return null; + return data.stream() + .filter(d -> d.getFactionID().equals(factionID)) + .findFirst() + .orElse(null); } public static FactionData findFactionData(Faction faction) { @@ -133,6 +110,6 @@ public static FactionData findFactionData(Faction faction) { } public static String getFactionIDFromFile(File file) { - return Factions.getInstance().getFactionById(file.getName().substring(0, file.getName().indexOf("."))).getId(); + return Factions.getInstance().getFactionById(file.getName().replace(".yml", "")).getId(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/data/listener/FactionDataListener.java b/src/main/java/com/massivecraft/factions/data/listener/FactionDataListener.java index 01c73f653..256e22423 100644 --- a/src/main/java/com/massivecraft/factions/data/listener/FactionDataListener.java +++ b/src/main/java/com/massivecraft/factions/data/listener/FactionDataListener.java @@ -11,6 +11,8 @@ import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; +import java.io.IOException; + /** * @Author: Driftay * @Date: 2/11/2022 4:50 PM @@ -23,11 +25,14 @@ public void onFPlayerCreate(FPlayerJoinEvent e) { if (e.getReason() == FPlayerJoinEvent.PlayerJoinReason.CREATE) { Bukkit.getScheduler().runTaskAsynchronously(FactionsPlugin.getInstance(), () -> { if (!FactionDataHelper.doesConfigurationExist(faction)) { - FactionDataHelper.createConfiguration(faction); + try { + FactionDataHelper.createConfiguration(faction); + } catch (IOException ex) { + throw new RuntimeException(ex); + } Bukkit.getLogger().info("[FactionData] Creating Faction Data for " + faction.getTag()); } - final FactionData data = new FactionData(faction); - new FactionDataHelper(data); + FactionDataHelper.addFactionData(new FactionData(faction)); }); } } @@ -42,7 +47,6 @@ public void onFactionDisband(FactionDisbandEvent e) { Bukkit.getScheduler().runTaskAsynchronously(FactionsPlugin.getInstance(), () -> { data.deleteFactionData(e.getFaction()); - data.remove(); }); } } diff --git a/src/main/java/com/massivecraft/factions/data/task/FactionDataDeploymentTask.java b/src/main/java/com/massivecraft/factions/data/task/FactionDataDeploymentTask.java index 3e84740de..4f178e99c 100644 --- a/src/main/java/com/massivecraft/factions/data/task/FactionDataDeploymentTask.java +++ b/src/main/java/com/massivecraft/factions/data/task/FactionDataDeploymentTask.java @@ -22,7 +22,7 @@ public void run() { if(cachedList.contains(faction)) continue; if(faction.isSystemFaction()) continue; final FactionData data = new FactionData(faction); - new FactionDataHelper(data); + FactionDataHelper.addFactionData(data); cachedList.add(faction); } } diff --git a/src/main/java/com/massivecraft/factions/listeners/SaberGUIListener.java b/src/main/java/com/massivecraft/factions/listeners/SaberGUIListener.java index 80e292635..218eff91f 100644 --- a/src/main/java/com/massivecraft/factions/listeners/SaberGUIListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/SaberGUIListener.java @@ -16,17 +16,6 @@ public class SaberGUIListener implements Listener { - @EventHandler(priority = EventPriority.HIGHEST) - public void onCommandWhilstInventoryIsOpen(PlayerCommandPreprocessEvent event) { - SaberGUI active = SaberGUI.getActiveGUI(event.getPlayer().getUniqueId()); - if (active != null) { - event.setCancelled(true); - event.setMessage("/null"); - active.close(); - event.getPlayer().sendMessage(TL.MACRO_DETECTED.toString()); - } - } - @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryClick(InventoryClickEvent event) { SaberGUI active = SaberGUI.getActiveGUI(event.getWhoClicked().getUniqueId()); diff --git a/src/main/java/com/massivecraft/factions/tag/FactionTag.java b/src/main/java/com/massivecraft/factions/tag/FactionTag.java index 8b6630e32..e3b0fdf25 100644 --- a/src/main/java/com/massivecraft/factions/tag/FactionTag.java +++ b/src/main/java/com/massivecraft/factions/tag/FactionTag.java @@ -63,9 +63,9 @@ public enum FactionTag implements Tag { LAND_REFUND("{land-refund}", (fac) -> Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("refund")), BANK_BALANCE("{faction-balance}", (fac) -> { if (Econ.shouldBeUsed()) { - return Conf.bankEnabled ? Econ.insertCommas(Econ.getFactionBalance(fac)) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); + return Conf.bankEnabled ? Econ.insertCommas(Econ.getFactionBalance(fac)) : Tag.isMinimalShow() ? null : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); } - return Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"); + return Tag.isMinimalShow() ? null : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); }), TNT_BALANCE("{tnt-balance}", (fac) -> { if (FactionsPlugin.instance.getConfig().getBoolean("ftnt.Enabled")) { diff --git a/src/main/java/com/massivecraft/factions/tag/PlayerTag.java b/src/main/java/com/massivecraft/factions/tag/PlayerTag.java index d5b77a4b3..df4d87ea6 100644 --- a/src/main/java/com/massivecraft/factions/tag/PlayerTag.java +++ b/src/main/java/com/massivecraft/factions/tag/PlayerTag.java @@ -29,7 +29,7 @@ public enum PlayerTag implements Tag { String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; return fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); }), - PLAYER_BALANCE("{balance}", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format("balance"))), + PLAYER_BALANCE("{balance}", (fp) -> Econ.isSetup() ? Econ.getFriendlyBalance(fp) : (Tag.isMinimalShow() ? null : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()))), PLAYER_POWER("{player-power}", (fp) -> String.valueOf(fp.getPowerRounded())), ROLE("{player-role}", FPlayer::getRolePrefix), PLAYER_MAXPOWER("{player-maxpower}", (fp) -> String.valueOf(fp.getPowerMaxRounded())), diff --git a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java index c8035be74..adfbec6d1 100644 --- a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java +++ b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java @@ -102,7 +102,7 @@ public String onPlaceholderRequest(Player player, String placeholder) { case "player_group": return FactionsPlugin.getInstance().getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fPlayer.getId()))); case "player_balance": - return Econ.isSetup() ? Econ.getFriendlyBalance(fPlayer) : TL.ECON_OFF.format("balance"); + return Econ.isSetup() ? Econ.getFriendlyBalance(fPlayer) : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); case "player_power": return String.valueOf(fPlayer.getPowerRounded()); case "player_maxpower": @@ -174,7 +174,7 @@ public String onPlaceholderRequest(Player player, String placeholder) { case "faction_land_refund": return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(faction.getLandRounded())) : TL.ECON_OFF.format("refund"); case "faction_bank_balance": - return Econ.shouldBeUsed() ? Econ.insertCommas(faction.getFactionBalance()) : TL.ECON_OFF.format("balance"); + return Econ.shouldBeUsed() ? Econ.insertCommas(faction.getFactionBalance()) : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); case "faction_allies": return String.valueOf(faction.getRelationCount(Relation.ALLY)); case "faction_discord": diff --git a/src/main/java/com/massivecraft/factions/util/flight/FlightEnhance.java b/src/main/java/com/massivecraft/factions/util/flight/FlightEnhance.java index 34116e0dd..10d26a3d1 100644 --- a/src/main/java/com/massivecraft/factions/util/flight/FlightEnhance.java +++ b/src/main/java/com/massivecraft/factions/util/flight/FlightEnhance.java @@ -6,6 +6,7 @@ import com.massivecraft.factions.FactionsPlugin; import com.massivecraft.factions.listeners.FactionsEntityListener; import org.bukkit.GameMode; +import org.bukkit.entity.Player; /** * SaberFactions - Developed by Driftay. @@ -17,27 +18,38 @@ public class FlightEnhance implements Runnable { @Override public void run() { for (FPlayer player : FPlayers.getInstance().getOnlinePlayers()) { - if (player.isAdminBypassing() - || player.getPlayer() == null - || player.getPlayer().isOp() - || player.getPlayer().getGameMode() == GameMode.CREATIVE - || player.getPlayer().getGameMode() == GameMode.SPECTATOR) continue; + if (shouldSkipPlayer(player)) continue; FLocation fLocation = FLocation.wrap(player.getPlayer().getLocation()); - player.checkIfNearbyEnemies(); if (!player.hasEnemiesNearby()) { - if (player.isFlying()) { - if (!player.canFlyAtLocation(fLocation)) { - player.setFlying(false, false); - } - } else if (player.canFlyAtLocation() - && FactionsPlugin.getInstance().getConfig().getBoolean("ffly.AutoEnable") - && !FactionsEntityListener.combatList.contains(player.getPlayer().getUniqueId())) { - player.setFlying(true); - } + handleFlightStatusForPlayer(player, fLocation); } } } + + private boolean shouldSkipPlayer(FPlayer player) { + Player p = player.getPlayer(); + + return player.isAdminBypassing() + || p == null + || p.isOp() + || p.getGameMode() == GameMode.CREATIVE + || p.getGameMode() == GameMode.SPECTATOR; + } + + private void handleFlightStatusForPlayer(FPlayer player, FLocation fLocation) { + if (player.isFlying() && !player.canFlyAtLocation(fLocation)) { + player.setFlying(false, false); + return; + } + + if (!player.isFlying() + && player.canFlyAtLocation() + && FactionsPlugin.getInstance().getConfig().getBoolean("ffly.AutoEnable") + && !FactionsEntityListener.combatList.contains(player.getPlayer().getUniqueId())) { + player.setFlying(true); + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/util/flight/stuct/AsyncPlayerMap.java b/src/main/java/com/massivecraft/factions/util/flight/stuct/AsyncPlayerMap.java index 92d478c17..4ad510283 100644 --- a/src/main/java/com/massivecraft/factions/util/flight/stuct/AsyncPlayerMap.java +++ b/src/main/java/com/massivecraft/factions/util/flight/stuct/AsyncPlayerMap.java @@ -7,6 +7,7 @@ import com.massivecraft.factions.util.TitleUtil; import org.bukkit.Bukkit; import org.bukkit.Location; +import org.bukkit.Server; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -23,33 +24,34 @@ * Creation Date: 10/27/2020 */ public class AsyncPlayerMap implements Runnable, Listener { - private volatile Map players = new ConcurrentHashMap<>(); - private volatile Map locations = new ConcurrentHashMap<>(); + + private final Map players = new ConcurrentHashMap<>(); + private final Map locations = new ConcurrentHashMap<>(); + private final Server server = Bukkit.getServer(); public AsyncPlayerMap(Plugin bukkitPlugin) { Bukkit.getPluginManager().registerEvents(this, bukkitPlugin); Bukkit.getScheduler().runTaskTimer(bukkitPlugin, this, 20L, 20L); } + @Override public void run() { - for (Player pl : Bukkit.getServer().getOnlinePlayers()) { - if (pl.hasMetadata("showFactionTitle")) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(pl); - Faction factionTo = Board.getInstance().getFactionAt(fPlayer.getLastStoodAt()); - TitleUtil.sendFactionChangeTitle(fPlayer, factionTo); - } - this.locations.put(pl.getName(), pl.getLocation()); + for (Player pl : server.getOnlinePlayers()) { + processPlayer(pl); + updateLocation(pl); } } - @EventHandler - public void onPlayerJoin(PlayerJoinEvent e) { - this.players.put(e.getPlayer().getName(), e.getPlayer()); + private void processPlayer(Player pl) { + if (pl.hasMetadata("showFactionTitle")) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(pl); + Faction factionTo = Board.getInstance().getFactionAt(fPlayer.getLastStoodAt()); + TitleUtil.sendFactionChangeTitle(fPlayer, factionTo); + } } - @EventHandler - public void onPlayerQuit(PlayerQuitEvent e) { - this.players.remove(e.getPlayer().getName()); + private void updateLocation(Player pl) { + this.locations.put(pl.getName(), pl.getLocation()); } public Map getPlayers() { @@ -59,4 +61,14 @@ public Map getPlayers() { public Map getLocations() { return this.locations; } -} + + @EventHandler + public void onPlayerJoin(PlayerJoinEvent e) { + this.players.put(e.getPlayer().getName(), e.getPlayer()); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent e) { + this.players.remove(e.getPlayer().getName()); + } +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/MCommand.java b/src/main/java/com/massivecraft/factions/zcore/MCommand.java index b4b3f0b54..ec3b66872 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MCommand.java +++ b/src/main/java/com/massivecraft/factions/zcore/MCommand.java @@ -299,7 +299,7 @@ public List getToolTips(Faction faction) { public String replaceFPlayerTags(String s, FPlayer player) { if (s.contains("{balance}")) { - String balance = Econ.isSetup() ? Econ.getFriendlyBalance(player) : "no balance"; + String balance = Econ.isSetup() ? Econ.getFriendlyBalance(player) : TL.NO_BALANCE_PLACEHOLDER_PARSED.toString(); s = s.replace("{balance}", balance); } if (s.contains("{lastSeen}")) { diff --git a/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java b/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java index f2a74f4aa..180ba0281 100644 --- a/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java +++ b/src/main/java/com/massivecraft/factions/zcore/file/CustomFile.java @@ -9,6 +9,7 @@ import java.io.InputStreamReader; import java.util.HashMap; import java.util.List; +import java.util.Map; /** * Factions - Developed by Driftay. @@ -19,7 +20,7 @@ public class CustomFile { private File file; private YamlConfiguration fileConfig; - private HashMap cachedObjects = new HashMap<>(); + private final HashMap cachedObjects = new HashMap<>(); public CustomFile(File file) { this.file = file; @@ -27,58 +28,53 @@ public CustomFile(File file) { } public void setup(boolean loadFromProject, String inFolder) { - if (!getFile().exists()) { + if (!file.exists()) { + FactionsPlugin pluginInstance = FactionsPlugin.getInstance(); + String resourcePath = inFolder.isEmpty() ? file.getName() : inFolder + "/" + file.getName(); + if (loadFromProject) { - if (!inFolder.equalsIgnoreCase("")) { - FactionsPlugin.getInstance().saveResource(inFolder + "/" + file.getName(), false); - } else { - FactionsPlugin.getInstance().saveResource(file.getName(), false); - } + pluginInstance.saveResource(resourcePath, false); } else { try { - getFile().createNewFile(); + file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } + loadFile(); + // Add default values for missing config options - InputStream resource; - if (!inFolder.equalsIgnoreCase("")) { - resource = FactionsPlugin.getInstance().getResource(inFolder + "/" + file.getName()); - } else { - resource = FactionsPlugin.getInstance().getResource(file.getName()); - } + InputStream resource = FactionsPlugin.getInstance().getResource(inFolder.isEmpty() ? file.getName() : inFolder + "/" + file.getName()); - if(resource == null) - return; - YamlConfiguration defaultConf = YamlConfiguration.loadConfiguration(new InputStreamReader(resource)); - getConfig().setDefaults(defaultConf); - getConfig().options().copyDefaults(true); - try { - getConfig().save(getFile()); - loadFile(); - } catch (IOException e) { - e.printStackTrace(); + if (resource != null) { + YamlConfiguration defaultConf = YamlConfiguration.loadConfiguration(new InputStreamReader(resource)); + fileConfig.setDefaults(defaultConf); + fileConfig.options().copyDefaults(true); + saveFile(); } } public void loadFile() { this.fileConfig = YamlConfiguration.loadConfiguration(file); - this.cachedObjects.clear(); // remove cached objects + this.cachedObjects.clear(); } public void saveFile() { try { - getConfig().save(file); + fileConfig.save(file); } catch (IOException e) { e.printStackTrace(); } } + public YamlConfiguration getConfig() { + return fileConfig; + } + public boolean containsKey(String key) { - return getCachedObjects().containsKey(key) || getConfig().contains(key); + return cachedObjects.containsKey(key) || fileConfig.contains(key); } public String fetchString(String key) { @@ -101,66 +97,43 @@ public boolean fetchBoolean(String key) { return (boolean) getObj(key, dataTypes.BOOLEAN); } - public Object getObj(String key, Enum data) { - //check for cache first - - if (getCachedObjects().containsKey(key)) { - return getCachedObjects().get(key); - } - - if (data.equals(dataTypes.STRING)) { - String d = getConfig().getString(key); - this.cachedObjects.put(key, d); - return d; - } - - if (data.equals(dataTypes.DOUBLE)) { - double d = getConfig().getDouble(key); - this.cachedObjects.put(key, d); - return d; - } + public Map fetchMap(String key) { + return (Map) getObj(key, dataTypes.MAP); + } - if (data.equals(dataTypes.INT)) { - int d = getConfig().getInt(key); - this.cachedObjects.put(key, d); - return d; - } - if (data.equals(dataTypes.BOOLEAN)) { - boolean d = getConfig().getBoolean(key); - this.cachedObjects.put(key, d); - return d; + private Object getObj(String key, dataTypes data) { + if (cachedObjects.containsKey(key)) { + return cachedObjects.get(key); } - if (data.equals(dataTypes.STRINGLIST)) { - List d = getConfig().getStringList(key); - this.cachedObjects.put(key, d); - return d; + Object result; + + switch (data) { + case STRING: + result = fileConfig.getString(key); + break; + case DOUBLE: + result = fileConfig.getDouble(key); + break; + case INT: + result = fileConfig.getInt(key); + break; + case BOOLEAN: + result = fileConfig.getBoolean(key); + break; + case STRINGLIST: + result = fileConfig.getStringList(key); + break; + default: + return null; } - return null; - } - - public HashMap getCachedObjects() { - return cachedObjects; - } - - public File getFile() { - return file; - } - - public void setFile(File file) { - this.file = file; - } - public void setFileConfig(YamlConfiguration fileConfig) { - this.fileConfig = fileConfig; - } - - public YamlConfiguration getConfig() { - return fileConfig; + cachedObjects.put(key, result); + return result; } public enum dataTypes { STRING, INT, DOUBLE, STRINGLIST, BOOLEAN, MAP } -} +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/file/impl/FileManager.java b/src/main/java/com/massivecraft/factions/zcore/file/impl/FileManager.java index 324b1ed1c..779598876 100644 --- a/src/main/java/com/massivecraft/factions/zcore/file/impl/FileManager.java +++ b/src/main/java/com/massivecraft/factions/zcore/file/impl/FileManager.java @@ -4,77 +4,75 @@ import com.massivecraft.factions.zcore.file.CustomFile; import java.io.File; +import java.util.HashMap; +import java.util.Map; -/** - * Factions - Developed by Driftay. - * All rights reserved 2020. - * Creation Date: 4/4/2020 - */ public class FileManager { - private CustomFile boosters = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "data" + File.separator + "boosters.yml")); - private CustomFile timers = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "data" + File.separator + "timers.yml")); - private CustomFile fperms = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "configuration" + File.separator + "fperms.yml")); - private CustomFile upgrades = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "configuration" + File.separator + "upgrades.yml")); - private CustomFile permissions = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "data" + File.separator + "permissions.yml")); - private CustomFile corex = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "corex" + File.separator + "corex.yml")); - private CustomFile missions = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "configuration" + File.separator + "missions.yml")); - private CustomFile banners = new CustomFile(new File(FactionsPlugin.getInstance().getDataFolder() + File.separator + "configuration" + File.separator + "banners.yml")); + private final Map customFiles = new HashMap<>(); + + public FileManager() { + addCustomFile("boosters", "data"); + addCustomFile("timers", "data"); + addCustomFile("permissions", "data"); + addCustomFile("corex", "corex"); + addCustomFile("fperms", "configuration"); + addCustomFile("upgrades", "configuration"); + addCustomFile("missions", "configuration"); + addCustomFile("banners", "configuration"); + } - public void setupFiles() { - boosters.setup(true, "data"); - timers.setup(true, "data"); - permissions.setup(true, "data"); - corex.setup(true, "corex"); - fperms.setup(true, "configuration"); - upgrades.setup(true, "configuration"); - missions.setup(true, "configuration"); - banners.setup(true, "configuration"); + private void addCustomFile(String filename, String folder) { + String filePath = FactionsPlugin.getInstance().getDataFolder() + File.separator + folder + File.separator + filename + ".yml"; + customFiles.put(filename, new CustomFile(new File(filePath))); } + public void setupFiles() { + customFiles.forEach((name, customFile) -> { + String folder = name.equals("corex") ? "corex" : (name.endsWith("s") ? "data" : "configuration"); + customFile.setup(true, folder); + }); + } public void loadCustomFiles() { - boosters.loadFile(); - timers.loadFile(); - permissions.loadFile(); - corex.loadFile(); - fperms.loadFile(); - upgrades.loadFile(); - missions.loadFile(); - banners.loadFile(); + customFiles.values().forEach(CustomFile::loadFile); } + public CustomFile getCustomFile(String name) { + return customFiles.get(name); + } + // Individual getters, for direct access public CustomFile getBanners() { - return banners; + return getCustomFile("banners"); } public CustomFile getUpgrades() { - return upgrades; + return getCustomFile("upgrades"); } public CustomFile getMissions() { - return missions; + return getCustomFile("missions"); } public CustomFile getFperms() { - return fperms; + return getCustomFile("fperms"); } public CustomFile getTimers() { - return timers; + return getCustomFile("timers"); } public CustomFile getBoosters() { - return boosters; + return getCustomFile("boosters"); } public CustomFile getCoreX() { - return corex; + return getCustomFile("corex"); } public CustomFile getPermissions() { - return permissions; + return getCustomFile("permissions"); } -} +} \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FactionUpgradeFrame.java b/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FactionUpgradeFrame.java index e362fd732..c1db59a32 100644 --- a/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FactionUpgradeFrame.java +++ b/src/main/java/com/massivecraft/factions/zcore/frame/fupgrades/FactionUpgradeFrame.java @@ -49,7 +49,7 @@ public void redraw() { for (Map.Entry upgrade : upgradeManager.getUpgrades().entrySet()) { String upgradeId = upgrade.getKey(); - if (upgradeManager.getSlot(upgradeId) <= -1) continue; + if (upgradeManager.getSlot(upgradeId) == -1) continue; int currentFactionLevel = faction.getUpgrade(upgradeId); int upgradeMaxLevel = upgrade.getValue(); diff --git a/src/main/java/com/massivecraft/factions/zcore/util/ShutdownParameter.java b/src/main/java/com/massivecraft/factions/zcore/util/ShutdownParameter.java index fe6b3a059..fd618293f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/ShutdownParameter.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/ShutdownParameter.java @@ -18,7 +18,7 @@ public static void initShutdown(FactionsPlugin plugin) { Conf.saveSync(); FactionsPlugin.getInstance().getTimerManager().saveTimerData(); for(FactionsAddon factionsAddon : FactionsPlugin.getInstance().getFactionsAddonHashMap().values()) { - factionsAddon.disableAddon(); + factionsAddon.terminateAddon(); Logger.print("Disabled " + factionsAddon.getAddonName() + " addon", Logger.PrefixType.DEFAULT); } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TL.java b/src/main/java/com/massivecraft/factions/zcore/util/TL.java index d1f7369e8..3fc9a1a4f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TL.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TL.java @@ -1231,6 +1231,8 @@ public enum TL { GRACE_DISABLED_PLACEHOLDER("Disabled"), MACRO_DETECTED("&c&l[!] &cNo sir!"), + NO_BALANCE_PLACEHOLDER_PARSED("no balance"), + ROLE_LIST("&eTry using &arecruit, normal, moderator, coleader"), @@ -1310,6 +1312,7 @@ public enum TL { ECON_OFF("no %s"), // no balance, no value, no refund, etc ECON_FORMAT("###,###.###"), + ECON_BALANCE_DESC("balance"), ECON_MONEYTRASFERREDFROM("%1$s was transferred from %2$s to %3$s."), ECON_PERSONGAVEMONEYTO("%1$s gave %2$s to %3$s."), ECON_PERSONTOOKMONEYFROM("%1$s took %2$s from %3$s."), diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java b/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java index d21ad4a57..78d5478a4 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java @@ -192,7 +192,7 @@ String getValue(Faction fac, FPlayer fp) { case PLAYER_GROUP: return FactionsPlugin.getInstance().getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))); case PLAYER_BALANCE: - return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance"); + return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); case PLAYER_POWER: return String.valueOf(fp.getPowerRounded()); case PLAYER_MAXPOWER: @@ -253,9 +253,9 @@ String getValue(Faction fac, FPlayer fp) { return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandRefund(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("refund"); case BANK_BALANCE: if (Econ.shouldBeUsed()) { - return Conf.bankEnabled ? Econ.insertCommas(Econ.getFactionBalance(fac)) : minimal ? null : TL.ECON_OFF.format("balance"); + return Conf.bankEnabled ? Econ.insertCommas(Econ.getFactionBalance(fac)) : minimal ? null : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); } - return minimal ? null : TL.ECON_OFF.format("balance"); + return minimal ? null : TL.ECON_OFF.format(TL.ECON_BALANCE_DESC.toString()); case ALLIES_COUNT: return String.valueOf(fac.getRelationCount(Relation.ALLY)); case ENEMIES_COUNT: diff --git a/src/main/java/org/saberdev/corex/listeners/ArmorSwap.java b/src/main/java/org/saberdev/corex/listeners/ArmorSwap.java index cd85c820f..ea5777b52 100644 --- a/src/main/java/org/saberdev/corex/listeners/ArmorSwap.java +++ b/src/main/java/org/saberdev/corex/listeners/ArmorSwap.java @@ -27,37 +27,32 @@ public boolean isArmor(Material material) { public void equipArmor(Player player, ItemStack item) { if(item == null || item.getType() == Material.AIR) return; + String name = item.getType().toString().toLowerCase(); PlayerInventory inv = player.getInventory(); + + ItemStack oldArmor = null; + if(name.contains("helmet")) { - ItemStack old = inv.getHelmet(); + oldArmor = inv.getHelmet(); inv.setHelmet(item); - inv.remove(item); - if(old != null && old.getType() != Material.AIR) { - inv.setItemInHand(old); - } } else if(name.contains("chestplate")) { - ItemStack old = inv.getChestplate(); + oldArmor = inv.getChestplate(); inv.setChestplate(item); - inv.remove(item); - if(old != null && old.getType() != Material.AIR) { - inv.setItemInHand(old); - } } else if(name.contains("leggings")) { - ItemStack old = inv.getLeggings(); + oldArmor = inv.getLeggings(); inv.setLeggings(item); - inv.remove(item); - if(old != null && old.getType() != Material.AIR) { - inv.setItemInHand(old); - } } else if(name.contains("boots")) { - ItemStack old = inv.getBoots(); + oldArmor = inv.getBoots(); inv.setBoots(item); - inv.remove(item); - if(old != null && old.getType() != Material.AIR) { - inv.setItemInHand(old); - } } + + if (oldArmor != null && oldArmor.getType() != Material.AIR) { + inv.setItemInHand(oldArmor); + } else { + inv.setItemInHand(new ItemStack(Material.AIR)); + } + player.updateInventory(); }