From c6512bf316631c7c330dafcb0cd0e590f1b68598 Mon Sep 17 00:00:00 2001 From: Liz3 Date: Sun, 3 Mar 2019 04:51:21 +0100 Subject: [PATCH] Fixed Indents on all files using the reformat option and optimized imports --- .../java/com/massivecraft/factions/Board.java | 104 +- .../java/com/massivecraft/factions/Conf.java | 851 +++-- .../com/massivecraft/factions/FLocation.java | 386 +- .../com/massivecraft/factions/FPlayer.java | 410 +-- .../com/massivecraft/factions/FPlayers.java | 82 +- .../com/massivecraft/factions/Faction.java | 351 +- .../com/massivecraft/factions/Factions.java | 110 +- .../massivecraft/factions/MassiveStats.java | 750 ++-- .../massivecraft/factions/SavageFactions.java | 1402 ++++---- .../massivecraft/factions/cmd/CmdAHome.java | 70 +- .../massivecraft/factions/cmd/CmdAdmin.java | 138 +- .../factions/cmd/CmdAnnounce.java | 58 +- .../factions/cmd/CmdAutoClaim.java | 72 +- .../factions/cmd/CmdAutoHelp.java | 96 +- .../com/massivecraft/factions/cmd/CmdBan.java | 132 +- .../massivecraft/factions/cmd/CmdBanlist.java | 90 +- .../massivecraft/factions/cmd/CmdBanner.java | 200 +- .../massivecraft/factions/cmd/CmdBoom.java | 68 +- .../massivecraft/factions/cmd/CmdBypass.java | 58 +- .../massivecraft/factions/cmd/CmdChat.java | 132 +- .../massivecraft/factions/cmd/CmdChatSpy.java | 54 +- .../factions/cmd/CmdCheckpoint.java | 108 +- .../massivecraft/factions/cmd/CmdChest.java | 62 +- .../massivecraft/factions/cmd/CmdClaim.java | 130 +- .../massivecraft/factions/cmd/CmdClaimAt.java | 50 +- .../factions/cmd/CmdClaimLine.java | 106 +- .../factions/cmd/CmdColeader.java | 130 +- .../massivecraft/factions/cmd/CmdConfig.java | 396 +-- .../massivecraft/factions/cmd/CmdConvert.java | 58 +- .../massivecraft/factions/cmd/CmdCoords.java | 50 +- .../massivecraft/factions/cmd/CmdCreate.java | 166 +- .../factions/cmd/CmdDeinvite.java | 94 +- .../factions/cmd/CmdDelFWarp.java | 62 +- .../massivecraft/factions/cmd/CmdDemote.java | 8 +- .../factions/cmd/CmdDescription.java | 78 +- .../massivecraft/factions/cmd/CmdDisband.java | 156 +- .../massivecraft/factions/cmd/CmdFWarp.java | 126 +- .../com/massivecraft/factions/cmd/CmdFly.java | 402 +-- .../massivecraft/factions/cmd/CmdFocus.java | 74 +- .../factions/cmd/CmdGetVault.java | 102 +- .../massivecraft/factions/cmd/CmdHelp.java | 360 +- .../massivecraft/factions/cmd/CmdHome.java | 206 +- .../massivecraft/factions/cmd/CmdInspect.java | 52 +- .../massivecraft/factions/cmd/CmdInvite.java | 130 +- .../massivecraft/factions/cmd/CmdJoin.java | 188 +- .../massivecraft/factions/cmd/CmdKick.java | 208 +- .../factions/cmd/CmdKillHolograms.java | 42 +- .../massivecraft/factions/cmd/CmdLeave.java | 42 +- .../massivecraft/factions/cmd/CmdList.java | 194 +- .../massivecraft/factions/cmd/CmdLock.java | 46 +- .../massivecraft/factions/cmd/CmdLogins.java | 40 +- .../factions/cmd/CmdLowPower.java | 50 +- .../com/massivecraft/factions/cmd/CmdMap.java | 92 +- .../factions/cmd/CmdMapHeight.java | 44 +- .../com/massivecraft/factions/cmd/CmdMod.java | 124 +- .../factions/cmd/CmdModifyPower.java | 66 +- .../massivecraft/factions/cmd/CmdMoney.java | 68 +- .../factions/cmd/CmdMoneyBalance.java | 66 +- .../factions/cmd/CmdMoneyDeposit.java | 58 +- .../factions/cmd/CmdMoneyTransferFf.java | 68 +- .../factions/cmd/CmdMoneyTransferFp.java | 66 +- .../factions/cmd/CmdMoneyTransferPf.java | 66 +- .../factions/cmd/CmdMoneyWithdraw.java | 66 +- .../massivecraft/factions/cmd/CmdNear.java | 70 +- .../massivecraft/factions/cmd/CmdOpen.java | 68 +- .../massivecraft/factions/cmd/CmdOwner.java | 148 +- .../factions/cmd/CmdOwnerList.java | 94 +- .../factions/cmd/CmdPaypalSee.java | 66 +- .../factions/cmd/CmdPaypalSet.java | 52 +- .../factions/cmd/CmdPeaceful.java | 82 +- .../massivecraft/factions/cmd/CmdPerm.java | 168 +- .../factions/cmd/CmdPermanent.java | 126 +- .../factions/cmd/CmdPermanentPower.java | 118 +- .../massivecraft/factions/cmd/CmdPower.java | 70 +- .../factions/cmd/CmdPowerBoost.java | 176 +- .../massivecraft/factions/cmd/CmdPromote.java | 10 +- .../factions/cmd/CmdRelationAlly.java | 8 +- .../factions/cmd/CmdRelationEnemy.java | 8 +- .../factions/cmd/CmdRelationNeutral.java | 8 +- .../factions/cmd/CmdRelationTruce.java | 8 +- .../massivecraft/factions/cmd/CmdReload.java | 60 +- .../massivecraft/factions/cmd/CmdRules.java | 138 +- .../com/massivecraft/factions/cmd/CmdSB.java | 44 +- .../factions/cmd/CmdSafeunclaimall.java | 70 +- .../massivecraft/factions/cmd/CmdSaveAll.java | 86 +- .../factions/cmd/CmdSeeChunk.java | 214 +- .../factions/cmd/CmdSetBanner.java | 42 +- .../factions/cmd/CmdSetDefaultRole.java | 60 +- .../factions/cmd/CmdSetFWarp.java | 106 +- .../factions/cmd/CmdSetMaxVaults.java | 64 +- .../massivecraft/factions/cmd/CmdSethome.java | 102 +- .../massivecraft/factions/cmd/CmdShow.java | 168 +- .../factions/cmd/CmdShowClaims.java | 70 +- .../factions/cmd/CmdShowInvites.java | 42 +- .../massivecraft/factions/cmd/CmdStatus.java | 50 +- .../massivecraft/factions/cmd/CmdStealth.java | 46 +- .../massivecraft/factions/cmd/CmdStuck.java | 160 +- .../com/massivecraft/factions/cmd/CmdTag.java | 118 +- .../massivecraft/factions/cmd/CmdTitle.java | 68 +- .../com/massivecraft/factions/cmd/CmdTnt.java | 306 +- .../massivecraft/factions/cmd/CmdTntFill.java | 432 +-- .../factions/cmd/CmdToggleAllianceChat.java | 54 +- .../com/massivecraft/factions/cmd/CmdTop.java | 296 +- .../factions/cmd/CmdTpBanner.java | 66 +- .../massivecraft/factions/cmd/CmdUnban.java | 74 +- .../massivecraft/factions/cmd/CmdUnclaim.java | 268 +- .../factions/cmd/CmdUnclaimall.java | 82 +- .../factions/cmd/CmdUpgrades.java | 52 +- .../massivecraft/factions/cmd/CmdVault.java | 102 +- .../massivecraft/factions/cmd/CmdVersion.java | 42 +- .../factions/cmd/CmdWarunclaimall.java | 68 +- .../massivecraft/factions/cmd/FCmdRoot.java | 458 +-- .../massivecraft/factions/cmd/FCommand.java | 652 ++-- .../factions/cmd/FPromoteCommand.java | 134 +- .../factions/cmd/FRelationCommand.java | 184 +- .../event/FPlayerEnteredFactionEvent.java | 52 +- .../factions/event/FPlayerJoinEvent.java | 50 +- .../factions/event/FPlayerLeaveEvent.java | 52 +- .../factions/event/FPlayerStoppedFlying.java | 32 +- .../factions/event/FactionCreateEvent.java | 58 +- .../factions/event/FactionDisbandEvent.java | 62 +- .../factions/event/FactionEvent.java | 40 +- .../factions/event/FactionPlayerEvent.java | 16 +- .../factions/event/FactionRelationEvent.java | 58 +- .../event/FactionRelationWishEvent.java | 54 +- .../factions/event/FactionRenameEvent.java | 84 +- .../factions/event/LandClaimEvent.java | 106 +- .../factions/event/LandUnclaimAllEvent.java | 84 +- .../factions/event/LandUnclaimEvent.java | 96 +- .../factions/event/PowerLossEvent.java | 118 +- .../factions/event/PowerRegenEvent.java | 24 +- .../factions/iface/EconomyParticipator.java | 6 +- .../factions/iface/RelationParticipator.java | 10 +- .../factions/integration/Econ.java | 686 ++-- .../factions/integration/Essentials.java | 48 +- .../factions/integration/Worldguard.java | 172 +- .../integration/dynmap/DynmapStyle.java | 164 +- .../integration/dynmap/EngineDynmap.java | 1492 ++++---- .../integration/dynmap/TempAreaMarker.java | 170 +- .../integration/dynmap/TempMarker.java | 100 +- .../integration/dynmap/TempMarkerSet.java | 72 +- .../listeners/FactionsBlockListener.java | 970 ++--- .../listeners/FactionsChatListener.java | 316 +- .../listeners/FactionsEntityListener.java | 1396 ++++---- .../listeners/FactionsExploitListener.java | 82 +- .../listeners/FactionsPlayerListener.java | 1960 +++++------ .../scoreboards/BufferedObjective.java | 242 +- .../factions/scoreboards/FScoreboard.java | 216 +- .../scoreboards/FSidebarProvider.java | 44 +- .../factions/scoreboards/FTeamWrapper.java | 350 +- .../scoreboards/sidebar/FDefaultSidebar.java | 48 +- .../scoreboards/sidebar/FInfoSidebar.java | 34 +- .../player/PlayerFactionExpression.java | 120 +- .../player/PlayerPowerExpression.java | 116 +- .../player/PlayerRoleExpression.java | 112 +- .../massivecraft/factions/struct/BanInfo.java | 66 +- .../factions/struct/ChatMode.java | 60 +- .../factions/struct/Permission.java | 250 +- .../factions/struct/Relation.java | 370 +- .../massivecraft/factions/struct/Role.java | 216 +- .../factions/util/AsciiCompass.java | 172 +- .../factions/util/AutoLeaveProcessTask.java | 132 +- .../factions/util/AutoLeaveTask.java | 32 +- .../util/ClipPlaceholderAPIManager.java | 272 +- .../factions/util/EnumTypeAdapter.java | 86 +- .../factions/util/FactionGUI.java | 4 +- .../factions/util/InventoryTypeAdapter.java | 22 +- .../factions/util/InventoryUtil.java | 130 +- .../factions/util/LazyLocation.java | 140 +- .../factions/util/LocationTypeAdapter.java | 60 +- .../util/MapFLocToStringSetTypeAdapter.java | 142 +- .../massivecraft/factions/util/MiscUtil.java | 176 +- .../factions/util/MultiversionMaterials.java | 1898 +++++----- .../factions/util/MyLocationTypeAdapter.java | 80 +- .../util/Particles/ParticleEffect.java | 3110 ++++++++--------- .../util/Particles/ReflectionUtils.java | 1078 +++--- .../util/PermissionsMapTypeAdapter.java | 138 +- .../factions/util/RelationUtil.java | 152 +- .../factions/util/SpiralTask.java | 296 +- .../massivecraft/factions/util/UtilFly.java | 168 +- .../factions/util/VisualizeUtil.java | 102 +- .../factions/util/WarmUpUtil.java | 62 +- .../massivecraft/factions/util/WarpGUI.java | 388 +- .../factions/zcore/CommandVisibility.java | 14 +- .../massivecraft/factions/zcore/MCommand.java | 918 ++--- .../massivecraft/factions/zcore/MPlugin.java | 516 +-- .../zcore/MPluginSecretPlayerListener.java | 52 +- .../factions/zcore/fperms/Access.java | 62 +- .../zcore/fperms/DefaultPermissions.java | 291 +- .../factions/zcore/fperms/Permissable.java | 6 +- .../zcore/fperms/PermissableAction.java | 276 +- .../fperms/gui/PermissableActionGUI.java | 472 +-- .../fperms/gui/PermissableRelationGUI.java | 286 +- .../zcore/fupgrades/CropUpgrades.java | 96 +- .../factions/zcore/fupgrades/EXPUpgrade.java | 62 +- .../zcore/fupgrades/FUpgradesGUI.java | 464 +-- .../zcore/fupgrades/SpawnerUpgrades.java | 50 +- .../factions/zcore/fupgrades/Upgrade.java | 18 +- .../factions/zcore/nbtapi/NBTCompound.java | 290 +- .../factions/zcore/nbtapi/NBTContainer.java | 42 +- .../factions/zcore/nbtapi/NBTEntity.java | 20 +- .../factions/zcore/nbtapi/NBTFile.java | 58 +- .../factions/zcore/nbtapi/NBTItem.java | 44 +- .../factions/zcore/nbtapi/NBTList.java | 210 +- .../zcore/nbtapi/NBTListCompound.java | 164 +- .../zcore/nbtapi/NBTReflectionUtil.java | 1798 +++++----- .../factions/zcore/nbtapi/NBTTileEntity.java | 20 +- .../factions/zcore/nbtapi/NBTType.java | 50 +- .../zcore/nbtapi/utils/GsonWrapper.java | 32 +- .../zcore/nbtapi/utils/MethodNames.java | 32 +- .../zcore/nbtapi/utils/MinecraftVersion.java | 90 +- .../factions/zcore/persist/MemoryBoard.java | 624 ++-- .../factions/zcore/persist/MemoryFPlayer.java | 2366 ++++++------- .../zcore/persist/MemoryFPlayers.java | 82 +- .../factions/zcore/persist/MemoryFaction.java | 2414 ++++++------- .../zcore/persist/MemoryFactions.java | 278 +- .../factions/zcore/persist/SaveTask.java | 34 +- .../zcore/persist/json/FactionsJSON.java | 64 +- .../zcore/persist/json/JSONBoard.java | 136 +- .../zcore/persist/json/JSONFPlayer.java | 26 +- .../zcore/persist/json/JSONFPlayers.java | 288 +- .../zcore/persist/json/JSONFaction.java | 16 +- .../zcore/persist/json/JSONFactions.java | 506 +-- .../factions/zcore/util/DiscUtil.java | 240 +- .../factions/zcore/util/PermUtil.java | 98 +- .../factions/zcore/util/Persist.java | 210 +- .../factions/zcore/util/SmokeUtil.java | 164 +- .../massivecraft/factions/zcore/util/TL.java | 2028 +++++------ .../factions/zcore/util/TagReplacer.java | 528 +-- .../factions/zcore/util/TagUtil.java | 468 +-- .../factions/zcore/util/TextUtil.java | 366 +- .../factions/zcore/util/UUIDFetcher.java | 140 +- 232 files changed, 26900 insertions(+), 26895 deletions(-) diff --git a/src/main/java/com/massivecraft/factions/Board.java b/src/main/java/com/massivecraft/factions/Board.java index 1857fab2..dbd7d8f4 100644 --- a/src/main/java/com/massivecraft/factions/Board.java +++ b/src/main/java/com/massivecraft/factions/Board.java @@ -9,82 +9,82 @@ import java.util.Set; public abstract class Board { - protected static Board instance = getBoardImpl(); + protected static Board instance = getBoardImpl(); - private static Board getBoardImpl() { - switch (Conf.backEnd) { - case JSON: - return new JSONBoard(); - } - return null; - } + private static Board getBoardImpl() { + switch (Conf.backEnd) { + case JSON: + return new JSONBoard(); + } + return null; + } - public static Board getInstance() { - return instance; - } + public static Board getInstance() { + return instance; + } - //----------------------------------------------// - // Get and Set - //----------------------------------------------// - public abstract String getIdAt(FLocation flocation); + //----------------------------------------------// + // Get and Set + //----------------------------------------------// + public abstract String getIdAt(FLocation flocation); - public abstract Faction getFactionAt(FLocation flocation); + public abstract Faction getFactionAt(FLocation flocation); - public abstract void setIdAt(String id, FLocation flocation); + public abstract void setIdAt(String id, FLocation flocation); - public abstract void setFactionAt(Faction faction, FLocation flocation); + public abstract void setFactionAt(Faction faction, FLocation flocation); - public abstract void removeAt(FLocation flocation); + public abstract void removeAt(FLocation flocation); - public abstract Set getAllClaims(String factionId); + public abstract Set getAllClaims(String factionId); - public abstract Set getAllClaims(Faction faction); + public abstract Set getAllClaims(Faction faction); - // not to be confused with claims, ownership referring to further member-specific ownership of a claim - public abstract void clearOwnershipAt(FLocation flocation); + // not to be confused with claims, ownership referring to further member-specific ownership of a claim + public abstract void clearOwnershipAt(FLocation flocation); - public abstract void unclaimAll(String factionId); + public abstract void unclaimAll(String factionId); - public abstract void unclaimAllInWorld(String factionId, World world); + public abstract void unclaimAllInWorld(String factionId, World world); - // Is this coord NOT completely surrounded by coords claimed by the same faction? - // Simpler: Is there any nearby coord with a faction other than the faction here? - public abstract boolean isBorderLocation(FLocation flocation); + // Is this coord NOT completely surrounded by coords claimed by the same faction? + // Simpler: Is there any nearby coord with a faction other than the faction here? + public abstract boolean isBorderLocation(FLocation flocation); - // Is this coord connected to any coord claimed by the specified faction? - public abstract boolean isConnectedLocation(FLocation flocation, Faction faction); + // Is this coord connected to any coord claimed by the specified faction? + public abstract boolean isConnectedLocation(FLocation flocation, Faction faction); - public abstract boolean hasFactionWithin(FLocation flocation, Faction faction, int radius); + public abstract boolean hasFactionWithin(FLocation flocation, Faction faction, int radius); - //----------------------------------------------// - // Cleaner. Remove orphaned foreign keys - //----------------------------------------------// + //----------------------------------------------// + // Cleaner. Remove orphaned foreign keys + //----------------------------------------------// - public abstract void clean(); + public abstract void clean(); - //----------------------------------------------// - // Coord count - //----------------------------------------------// + //----------------------------------------------// + // Coord count + //----------------------------------------------// - public abstract int getFactionCoordCount(String factionId); + public abstract int getFactionCoordCount(String factionId); - public abstract int getFactionCoordCount(Faction faction); + public abstract int getFactionCoordCount(Faction faction); - public abstract int getFactionCoordCountInWorld(Faction faction, String worldName); + public abstract int getFactionCoordCountInWorld(Faction faction, String worldName); - //----------------------------------------------// - // Map generation - //----------------------------------------------// + //----------------------------------------------// + // Map generation + //----------------------------------------------// - /* - * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction - * of decreasing z - */ - public abstract ArrayList getMap(FPlayer fPlayer, FLocation flocation, double inDegrees); + /* + * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction + * of decreasing z + */ + public abstract ArrayList getMap(FPlayer fPlayer, FLocation flocation, double inDegrees); - public abstract void forceSave(); + public abstract void forceSave(); - public abstract void forceSave(boolean sync); + public abstract void forceSave(boolean sync); - public abstract boolean load(); + public abstract boolean load(); } diff --git a/src/main/java/com/massivecraft/factions/Conf.java b/src/main/java/com/massivecraft/factions/Conf.java index 45082931..9a4989eb 100644 --- a/src/main/java/com/massivecraft/factions/Conf.java +++ b/src/main/java/com/massivecraft/factions/Conf.java @@ -4,7 +4,6 @@ import com.google.common.collect.ImmutableMap; import com.massivecraft.factions.integration.dynmap.DynmapStyle; import com.massivecraft.factions.util.MultiversionMaterials; import com.massivecraft.factions.zcore.fperms.DefaultPermissions; -import com.massivecraft.factions.zcore.fperms.PermissableAction; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.EntityType; @@ -13,454 +12,454 @@ import java.util.*; public class Conf { - // Region Style - public static final transient String DYNMAP_STYLE_LINE_COLOR = "#00FF00"; - public static final transient double DYNMAP_STYLE_LINE_OPACITY = 0.8D; - public static final transient int DYNMAP_STYLE_LINE_WEIGHT = 3; - public static final transient String DYNMAP_STYLE_FILL_COLOR = "#00FF00"; - public static final transient double DYNMAP_STYLE_FILL_OPACITY = 0.35D; - public static final transient String DYNMAP_STYLE_HOME_MARKER = "greenflag"; - public static final transient boolean DYNMAP_STYLE_BOOST = false; - public static List baseCommandAliases = new ArrayList<>(); - public static boolean allowNoSlashCommand = true; - public static Set allowedStealthFactions = new LinkedHashSet<>(); + // Region Style + public static final transient String DYNMAP_STYLE_LINE_COLOR = "#00FF00"; + public static final transient double DYNMAP_STYLE_LINE_OPACITY = 0.8D; + public static final transient int DYNMAP_STYLE_LINE_WEIGHT = 3; + public static final transient String DYNMAP_STYLE_FILL_COLOR = "#00FF00"; + public static final transient double DYNMAP_STYLE_FILL_OPACITY = 0.35D; + public static final transient String DYNMAP_STYLE_HOME_MARKER = "greenflag"; + public static final transient boolean DYNMAP_STYLE_BOOST = false; + public static List baseCommandAliases = new ArrayList<>(); + public static boolean allowNoSlashCommand = true; + public static Set allowedStealthFactions = new LinkedHashSet<>(); - // Colors - public static ChatColor colorMember = ChatColor.GREEN; - public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE; - public static ChatColor colorTruce = ChatColor.DARK_PURPLE; - public static ChatColor colorNeutral = ChatColor.WHITE; - public static ChatColor colorEnemy = ChatColor.RED; - public static ChatColor colorPeaceful = ChatColor.GOLD; - public static ChatColor colorWilderness = ChatColor.GRAY; - public static ChatColor colorSafezone = ChatColor.GOLD; - public static ChatColor colorWar = ChatColor.DARK_RED; - // Power - public static double powerPlayerMax = 10.0; - public static double powerPlayerMin = -10.0; - public static double powerPlayerStarting = 0.0; - public static double powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one power - public static double powerPerDeath = 4.0; // A death makes you lose 4 power - public static boolean powerRegenOffline = false; // does player power regenerate even while they're offline? - public static double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline - public static double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less - public static double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts) - public static String prefixLeader = "***"; - public static String prefixCoLeader = "**"; - public static String prefixMod = "*"; - public static String prefixRecruit = "-"; - public static String prefixNormal = "+"; - public static int factionTagLengthMin = 3; - public static int factionTagLengthMax = 10; - public static boolean factionTagForceUpperCase = false; - public static boolean newFactionsDefaultOpen = false; - // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit - public static int factionMemberLimit = 0; - // what faction ID to start new players in when they first join the server; default is 0, "no faction" - public static String newPlayerStartingFactionID = "0"; - public static boolean showMapFactionKey = true; - public static boolean showNeutralFactionsOnMap = true; - public static boolean showEnemyFactionsOnMap = true; - public static boolean showTrucesFactionsOnMap = true; - // Disallow joining/leaving/kicking while power is negative - public static boolean canLeaveWithNegativePower = true; - // Configuration for faction-only chat - public static boolean factionOnlyChat = true; - // Configuration on the Faction tag in chat messages. - public static boolean chatTagEnabled = true; - public static transient boolean chatTagHandledByAnotherPlugin = false; - public static boolean chatTagRelationColored = true; - public static String chatTagReplaceString = "[FACTION]"; - public static String chatTagInsertAfterString = ""; - public static String chatTagInsertBeforeString = ""; - public static int chatTagInsertIndex = 0; - public static boolean chatTagPadBefore = false; - public static boolean chatTagPadAfter = true; - public static String chatTagFormat = "%s" + ChatColor.WHITE; - public static String factionChatFormat = "%s:" + ChatColor.WHITE + " %s"; - public static String allianceChatFormat = ChatColor.LIGHT_PURPLE + "%s:" + ChatColor.WHITE + " %s"; - public static String truceChatFormat = ChatColor.DARK_PURPLE + "%s:" + ChatColor.WHITE + " %s"; - public static String modChatFormat = ChatColor.RED + "%s:" + ChatColor.WHITE + " %s"; - public static int stealthFlyCheckRadius = 32; - public static boolean noEnderpearlsInFly = false; - public static boolean broadcastDescriptionChanges = false; - public static boolean broadcastTagChanges = false; - public static double saveToFileEveryXMinutes = 30.0; - public static double autoLeaveAfterDaysOfInactivity = 10.0; - public static double autoLeaveRoutineRunsEveryXMinutes = 5.0; - public static int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick - public static boolean removePlayerDataWhenBanned = true; - public static boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. - public static boolean worldGuardChecking = false; - public static boolean worldGuardBuildPriority = false; - // server logging options - public static boolean logFactionCreate = true; - public static boolean logFactionDisband = true; - public static boolean logFactionJoin = true; - public static boolean logFactionKick = true; - public static boolean logFactionLeave = true; - public static boolean logLandClaims = true; - public static boolean logLandUnclaims = true; - public static boolean logMoneyTransactions = true; - public static boolean logPlayerCommands = true; - // prevent some potential exploits - public static boolean handleExploitObsidianGenerators = true; - public static boolean handleExploitEnderPearlClipping = true; - public static boolean handleExploitInteractionSpam = true; - public static boolean handleExploitTNTWaterlog = false; - public static boolean handleExploitLiquidFlow = false; - public static boolean homesEnabled = true; - public static boolean homesMustBeInClaimedTerritory = true; - public static boolean homesTeleportToOnDeath = true; - public static boolean homesRespawnFromNoPowerLossWorlds = true; - public static boolean homesTeleportCommandEnabled = true; - public static boolean homesTeleportCommandEssentialsIntegration = true; - public static boolean homesTeleportCommandSmokeEffectEnabled = true; - public static float homesTeleportCommandSmokeEffectThickness = 3f; - public static boolean homesTeleportAllowedFromEnemyTerritory = true; - public static boolean homesTeleportAllowedFromDifferentWorld = true; - public static double homesTeleportAllowedEnemyDistance = 32.0; - public static boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true; - public static boolean disablePVPBetweenNeutralFactions = false; - public static boolean disablePVPForFactionlessPlayers = false; - public static boolean enablePVPAgainstFactionlessInAttackersLand = false; - public static int noPVPDamageToOthersForXSecondsAfterLogin = 3; - public static boolean peacefulTerritoryDisablePVP = true; - public static boolean peacefulTerritoryDisableMonsters = false; - public static boolean peacefulTerritoryDisableBoom = false; - public static boolean peacefulMembersDisablePowerLoss = true; - public static boolean permanentFactionsDisableLeaderPromotion = false; - public static boolean claimsMustBeConnected = false; - public static boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true; - public static int claimsRequireMinFactionMembers = 1; - public static int claimedLandsMax = 0; - public static int lineClaimLimit = 5; - // if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit - public static int radiusClaimFailureLimit = 9; - public static double considerFactionsReallyOfflineAfterXMinutes = 0.0; - public static int actionDeniedPainAmount = 1; - // commands which will be prevented if the player is a member of a permanent faction - public static Set permanentFactionMemberDenyCommands = new LinkedHashSet<>(); - // commands which will be prevented when in claimed territory of another faction - public static Set territoryNeutralDenyCommands = new LinkedHashSet<>(); - public static Set territoryEnemyDenyCommands = new LinkedHashSet<>(); - public static Set territoryAllyDenyCommands = new LinkedHashSet<>(); - public static Set warzoneDenyCommands = new LinkedHashSet<>(); - public static Set wildernessDenyCommands = new LinkedHashSet<>(); - public static boolean territoryDenyBuild = true; - public static boolean territoryDenyBuildWhenOffline = true; - public static boolean territoryPainBuild = false; - public static boolean territoryPainBuildWhenOffline = false; - public static boolean territoryDenyUseage = true; - public static boolean territoryEnemyDenyBuild = true; - public static boolean territoryEnemyDenyBuildWhenOffline = true; - public static boolean territoryEnemyPainBuild = false; - public static boolean territoryEnemyPainBuildWhenOffline = false; - public static boolean territoryEnemyDenyUseage = true; - public static boolean territoryEnemyProtectMaterials = true; - public static boolean territoryAllyDenyBuild = true; - public static boolean territoryAllyDenyBuildWhenOffline = true; - public static boolean territoryAllyPainBuild = false; - public static boolean territoryAllyPainBuildWhenOffline = false; - public static boolean territoryAllyDenyUseage = true; - public static boolean territoryAllyProtectMaterials = true; - public static boolean territoryTruceDenyBuild = true; - public static boolean territoryTruceDenyBuildWhenOffline = true; - public static boolean territoryTrucePainBuild = false; - public static boolean territoryTrucePainBuildWhenOffline = false; - public static boolean territoryTruceDenyUseage = true; - public static boolean territoryTruceProtectMaterials = true; - public static boolean territoryBlockCreepers = false; - public static boolean territoryBlockCreepersWhenOffline = false; - public static boolean territoryBlockFireballs = false; - public static boolean territoryBlockFireballsWhenOffline = false; - public static boolean territoryBlockTNT = false; - public static boolean territoryBlockTNTWhenOffline = false; - public static boolean territoryDenyEndermanBlocks = true; - public static boolean territoryDenyEndermanBlocksWhenOffline = true; - public static boolean safeZoneDenyBuild = true; - public static boolean safeZoneDenyUseage = true; - public static boolean safeZoneBlockTNT = true; - public static boolean safeZonePreventAllDamageToPlayers = false; - public static boolean safeZoneDenyEndermanBlocks = true; - public static boolean warZoneDenyBuild = true; - public static boolean warZoneDenyUseage = true; - public static boolean warZoneBlockCreepers = false; - public static boolean warZoneBlockFireballs = false; - public static boolean warZoneBlockTNT = true; - public static boolean warZonePowerLoss = true; - public static boolean warZoneFriendlyFire = false; - public static boolean warZoneDenyEndermanBlocks = true; - public static boolean wildernessDenyBuild = false; - public static boolean wildernessDenyUseage = false; - public static boolean wildernessBlockCreepers = false; - public static boolean wildernessBlockFireballs = false; - public static boolean wildernessBlockTNT = false; - public static boolean wildernessPowerLoss = true; - public static boolean wildernessDenyEndermanBlocks = false; - // for claimed areas where further faction-member ownership can be defined - public static boolean ownedAreasEnabled = true; - public static int ownedAreasLimitPerFaction = 0; - public static boolean ownedAreasModeratorsCanSet = false; - public static boolean ownedAreaModeratorsBypass = true; - public static boolean ownedAreaDenyBuild = true; - public static boolean ownedAreaPainBuild = false; - public static boolean ownedAreaProtectMaterials = true; - public static boolean ownedAreaDenyUseage = true; - public static boolean ownedMessageOnBorder = true; - public static boolean ownedMessageInsideTerritory = true; - public static boolean ownedMessageByChunk = false; - public static boolean pistonProtectionThroughDenyBuild = true; - public static Set territoryProtectedMaterials = EnumSet.noneOf(Material.class); - public static Set territoryDenyUseageMaterials = EnumSet.noneOf(Material.class); - public static Set territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); - public static Set territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class); - public static transient Set safeZoneNerfedCreatureTypes = EnumSet.noneOf(EntityType.class); + // Colors + public static ChatColor colorMember = ChatColor.GREEN; + public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE; + public static ChatColor colorTruce = ChatColor.DARK_PURPLE; + public static ChatColor colorNeutral = ChatColor.WHITE; + public static ChatColor colorEnemy = ChatColor.RED; + public static ChatColor colorPeaceful = ChatColor.GOLD; + public static ChatColor colorWilderness = ChatColor.GRAY; + public static ChatColor colorSafezone = ChatColor.GOLD; + public static ChatColor colorWar = ChatColor.DARK_RED; + // Power + public static double powerPlayerMax = 10.0; + public static double powerPlayerMin = -10.0; + public static double powerPlayerStarting = 0.0; + public static double powerPerMinute = 0.2; // Default health rate... it takes 5 min to heal one power + public static double powerPerDeath = 4.0; // A death makes you lose 4 power + public static boolean powerRegenOffline = false; // does player power regenerate even while they're offline? + public static double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline + public static double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less + public static double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts) + public static String prefixLeader = "***"; + public static String prefixCoLeader = "**"; + public static String prefixMod = "*"; + public static String prefixRecruit = "-"; + public static String prefixNormal = "+"; + public static int factionTagLengthMin = 3; + public static int factionTagLengthMax = 10; + public static boolean factionTagForceUpperCase = false; + public static boolean newFactionsDefaultOpen = false; + // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit + public static int factionMemberLimit = 0; + // what faction ID to start new players in when they first join the server; default is 0, "no faction" + public static String newPlayerStartingFactionID = "0"; + public static boolean showMapFactionKey = true; + public static boolean showNeutralFactionsOnMap = true; + public static boolean showEnemyFactionsOnMap = true; + public static boolean showTrucesFactionsOnMap = true; + // Disallow joining/leaving/kicking while power is negative + public static boolean canLeaveWithNegativePower = true; + // Configuration for faction-only chat + public static boolean factionOnlyChat = true; + // Configuration on the Faction tag in chat messages. + public static boolean chatTagEnabled = true; + public static transient boolean chatTagHandledByAnotherPlugin = false; + public static boolean chatTagRelationColored = true; + public static String chatTagReplaceString = "[FACTION]"; + public static String chatTagInsertAfterString = ""; + public static String chatTagInsertBeforeString = ""; + public static int chatTagInsertIndex = 0; + public static boolean chatTagPadBefore = false; + public static boolean chatTagPadAfter = true; + public static String chatTagFormat = "%s" + ChatColor.WHITE; + public static String factionChatFormat = "%s:" + ChatColor.WHITE + " %s"; + public static String allianceChatFormat = ChatColor.LIGHT_PURPLE + "%s:" + ChatColor.WHITE + " %s"; + public static String truceChatFormat = ChatColor.DARK_PURPLE + "%s:" + ChatColor.WHITE + " %s"; + public static String modChatFormat = ChatColor.RED + "%s:" + ChatColor.WHITE + " %s"; + public static int stealthFlyCheckRadius = 32; + public static boolean noEnderpearlsInFly = false; + public static boolean broadcastDescriptionChanges = false; + public static boolean broadcastTagChanges = false; + public static double saveToFileEveryXMinutes = 30.0; + public static double autoLeaveAfterDaysOfInactivity = 10.0; + public static double autoLeaveRoutineRunsEveryXMinutes = 5.0; + public static int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick + public static boolean removePlayerDataWhenBanned = true; + public static boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. + public static boolean worldGuardChecking = false; + public static boolean worldGuardBuildPriority = false; + // server logging options + public static boolean logFactionCreate = true; + public static boolean logFactionDisband = true; + public static boolean logFactionJoin = true; + public static boolean logFactionKick = true; + public static boolean logFactionLeave = true; + public static boolean logLandClaims = true; + public static boolean logLandUnclaims = true; + public static boolean logMoneyTransactions = true; + public static boolean logPlayerCommands = true; + // prevent some potential exploits + public static boolean handleExploitObsidianGenerators = true; + public static boolean handleExploitEnderPearlClipping = true; + public static boolean handleExploitInteractionSpam = true; + public static boolean handleExploitTNTWaterlog = false; + public static boolean handleExploitLiquidFlow = false; + public static boolean homesEnabled = true; + public static boolean homesMustBeInClaimedTerritory = true; + public static boolean homesTeleportToOnDeath = true; + public static boolean homesRespawnFromNoPowerLossWorlds = true; + public static boolean homesTeleportCommandEnabled = true; + public static boolean homesTeleportCommandEssentialsIntegration = true; + public static boolean homesTeleportCommandSmokeEffectEnabled = true; + public static float homesTeleportCommandSmokeEffectThickness = 3f; + public static boolean homesTeleportAllowedFromEnemyTerritory = true; + public static boolean homesTeleportAllowedFromDifferentWorld = true; + public static double homesTeleportAllowedEnemyDistance = 32.0; + public static boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true; + public static boolean disablePVPBetweenNeutralFactions = false; + public static boolean disablePVPForFactionlessPlayers = false; + public static boolean enablePVPAgainstFactionlessInAttackersLand = false; + public static int noPVPDamageToOthersForXSecondsAfterLogin = 3; + public static boolean peacefulTerritoryDisablePVP = true; + public static boolean peacefulTerritoryDisableMonsters = false; + public static boolean peacefulTerritoryDisableBoom = false; + public static boolean peacefulMembersDisablePowerLoss = true; + public static boolean permanentFactionsDisableLeaderPromotion = false; + public static boolean claimsMustBeConnected = false; + public static boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true; + public static int claimsRequireMinFactionMembers = 1; + public static int claimedLandsMax = 0; + public static int lineClaimLimit = 5; + // if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit + public static int radiusClaimFailureLimit = 9; + public static double considerFactionsReallyOfflineAfterXMinutes = 0.0; + public static int actionDeniedPainAmount = 1; + // commands which will be prevented if the player is a member of a permanent faction + public static Set permanentFactionMemberDenyCommands = new LinkedHashSet<>(); + // commands which will be prevented when in claimed territory of another faction + public static Set territoryNeutralDenyCommands = new LinkedHashSet<>(); + public static Set territoryEnemyDenyCommands = new LinkedHashSet<>(); + public static Set territoryAllyDenyCommands = new LinkedHashSet<>(); + public static Set warzoneDenyCommands = new LinkedHashSet<>(); + public static Set wildernessDenyCommands = new LinkedHashSet<>(); + public static boolean territoryDenyBuild = true; + public static boolean territoryDenyBuildWhenOffline = true; + public static boolean territoryPainBuild = false; + public static boolean territoryPainBuildWhenOffline = false; + public static boolean territoryDenyUseage = true; + public static boolean territoryEnemyDenyBuild = true; + public static boolean territoryEnemyDenyBuildWhenOffline = true; + public static boolean territoryEnemyPainBuild = false; + public static boolean territoryEnemyPainBuildWhenOffline = false; + public static boolean territoryEnemyDenyUseage = true; + public static boolean territoryEnemyProtectMaterials = true; + public static boolean territoryAllyDenyBuild = true; + public static boolean territoryAllyDenyBuildWhenOffline = true; + public static boolean territoryAllyPainBuild = false; + public static boolean territoryAllyPainBuildWhenOffline = false; + public static boolean territoryAllyDenyUseage = true; + public static boolean territoryAllyProtectMaterials = true; + public static boolean territoryTruceDenyBuild = true; + public static boolean territoryTruceDenyBuildWhenOffline = true; + public static boolean territoryTrucePainBuild = false; + public static boolean territoryTrucePainBuildWhenOffline = false; + public static boolean territoryTruceDenyUseage = true; + public static boolean territoryTruceProtectMaterials = true; + public static boolean territoryBlockCreepers = false; + public static boolean territoryBlockCreepersWhenOffline = false; + public static boolean territoryBlockFireballs = false; + public static boolean territoryBlockFireballsWhenOffline = false; + public static boolean territoryBlockTNT = false; + public static boolean territoryBlockTNTWhenOffline = false; + public static boolean territoryDenyEndermanBlocks = true; + public static boolean territoryDenyEndermanBlocksWhenOffline = true; + public static boolean safeZoneDenyBuild = true; + public static boolean safeZoneDenyUseage = true; + public static boolean safeZoneBlockTNT = true; + public static boolean safeZonePreventAllDamageToPlayers = false; + public static boolean safeZoneDenyEndermanBlocks = true; + public static boolean warZoneDenyBuild = true; + public static boolean warZoneDenyUseage = true; + public static boolean warZoneBlockCreepers = false; + public static boolean warZoneBlockFireballs = false; + public static boolean warZoneBlockTNT = true; + public static boolean warZonePowerLoss = true; + public static boolean warZoneFriendlyFire = false; + public static boolean warZoneDenyEndermanBlocks = true; + public static boolean wildernessDenyBuild = false; + public static boolean wildernessDenyUseage = false; + public static boolean wildernessBlockCreepers = false; + public static boolean wildernessBlockFireballs = false; + public static boolean wildernessBlockTNT = false; + public static boolean wildernessPowerLoss = true; + public static boolean wildernessDenyEndermanBlocks = false; + // for claimed areas where further faction-member ownership can be defined + public static boolean ownedAreasEnabled = true; + public static int ownedAreasLimitPerFaction = 0; + public static boolean ownedAreasModeratorsCanSet = false; + public static boolean ownedAreaModeratorsBypass = true; + public static boolean ownedAreaDenyBuild = true; + public static boolean ownedAreaPainBuild = false; + public static boolean ownedAreaProtectMaterials = true; + public static boolean ownedAreaDenyUseage = true; + public static boolean ownedMessageOnBorder = true; + public static boolean ownedMessageInsideTerritory = true; + public static boolean ownedMessageByChunk = false; + public static boolean pistonProtectionThroughDenyBuild = true; + public static Set territoryProtectedMaterials = EnumSet.noneOf(Material.class); + public static Set territoryDenyUseageMaterials = EnumSet.noneOf(Material.class); + public static Set territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); + public static Set territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class); + public static transient Set safeZoneNerfedCreatureTypes = EnumSet.noneOf(EntityType.class); - // Economy settings - public static boolean econEnabled = false; - public static String econUniverseAccount = ""; - public static double econCostClaimWilderness = 30.0; - public static double econCostClaimFromFactionBonus = 30.0; - public static double econOverclaimRewardMultiplier = 0.0; - public static double econClaimAdditionalMultiplier = 0.5; - public static double econClaimRefundMultiplier = 0.7; - public static double econClaimUnconnectedFee = 0.0; - public static double econCostCreate = 100.0; - public static double econCostOwner = 15.0; - public static double econCostSethome = 30.0; - public static double econCostJoin = 0.0; - public static double econCostLeave = 0.0; - public static double econCostKick = 0.0; - public static double econCostInvite = 0.0; - public static double econCostHome = 0.0; - public static double econCostTag = 0.0; - public static double econCostDesc = 0.0; - public static double econCostTitle = 0.0; - public static double econCostList = 0.0; - public static double econCostMap = 0.0; - public static double econCostPower = 0.0; - public static double econCostShow = 0.0; + // Economy settings + public static boolean econEnabled = false; + public static String econUniverseAccount = ""; + public static double econCostClaimWilderness = 30.0; + public static double econCostClaimFromFactionBonus = 30.0; + public static double econOverclaimRewardMultiplier = 0.0; + public static double econClaimAdditionalMultiplier = 0.5; + public static double econClaimRefundMultiplier = 0.7; + public static double econClaimUnconnectedFee = 0.0; + public static double econCostCreate = 100.0; + public static double econCostOwner = 15.0; + public static double econCostSethome = 30.0; + public static double econCostJoin = 0.0; + public static double econCostLeave = 0.0; + public static double econCostKick = 0.0; + public static double econCostInvite = 0.0; + public static double econCostHome = 0.0; + public static double econCostTag = 0.0; + public static double econCostDesc = 0.0; + public static double econCostTitle = 0.0; + public static double econCostList = 0.0; + public static double econCostMap = 0.0; + public static double econCostPower = 0.0; + public static double econCostShow = 0.0; - // -------------------------------------------- // - // INTEGRATION: DYNMAP - // -------------------------------------------- // - public static double econCostStuck = 0.0; - public static double econCostOpen = 0.0; - public static double econCostAlly = 0.0; - public static double econCostTruce = 0.0; - public static double econCostEnemy = 0.0; - public static double econCostNeutral = 0.0; - public static double econCostNoBoom = 0.0; - // Should the dynmap intagration be used? - public static boolean dynmapUse = false; - // Name of the Factions layer - public static String dynmapLayerName = "Factions"; - // Should the layer be visible per default - public static boolean dynmapLayerVisible = true; - // Ordering priority in layer menu (low goes before high - default is 0) - public static int dynmapLayerPriority = 2; - // (optional) set minimum zoom level before layer is visible (0 = default, always visible) - public static int dynmapLayerMinimumZoom = 0; - // Format for popup - substitute values for macros - public static String dynmapDescription = - "
\n" - + "%name%
\n" - + "%description%
" - + "
\n" - + "Leader: %players.leader%
\n" - + "Admins: %players.admins.count%
\n" - + "Moderators: %players.moderators.count%
\n" - + "Members: %players.normals.count%
\n" - + "TOTAL: %players.count%
\n" - + "
\n" - + "Bank: %money%
\n" - + "
\n" - + "
"; - // Enable the %money% macro. Only do this if you know your economy manager is thread-safe. - public static boolean dynmapDescriptionMoney = false; - // Allow players in faction to see one another on Dynmap (only relevant if Dynmap has 'player-info-protected' enabled) - public static boolean dynmapVisibilityByFaction = true; - // Optional setting to limit which regions to show. - // If empty all regions are shown. - // Specify Faction either by name or UUID. - // To show all regions on a given world, add 'world:' to the list. - public static Set dynmapVisibleFactions = new HashSet<>(); - // Optional setting to hide specific Factions. - // Specify Faction either by name or UUID. - // To hide all regions on a given world, add 'world:' to the list. - public static Set dynmapHiddenFactions = new HashSet<>(); - public static DynmapStyle dynmapDefaultStyle = new DynmapStyle() - .setStrokeColor(DYNMAP_STYLE_LINE_COLOR) - .setLineOpacity(DYNMAP_STYLE_LINE_OPACITY) - .setLineWeight(DYNMAP_STYLE_LINE_WEIGHT) - .setFillColor(DYNMAP_STYLE_FILL_COLOR) - .setFillOpacity(DYNMAP_STYLE_FILL_OPACITY) - .setHomeMarker(DYNMAP_STYLE_HOME_MARKER) - .setBoost(DYNMAP_STYLE_BOOST); + // -------------------------------------------- // + // INTEGRATION: DYNMAP + // -------------------------------------------- // + public static double econCostStuck = 0.0; + public static double econCostOpen = 0.0; + public static double econCostAlly = 0.0; + public static double econCostTruce = 0.0; + public static double econCostEnemy = 0.0; + public static double econCostNeutral = 0.0; + public static double econCostNoBoom = 0.0; + // Should the dynmap intagration be used? + public static boolean dynmapUse = false; + // Name of the Factions layer + public static String dynmapLayerName = "Factions"; + // Should the layer be visible per default + public static boolean dynmapLayerVisible = true; + // Ordering priority in layer menu (low goes before high - default is 0) + public static int dynmapLayerPriority = 2; + // (optional) set minimum zoom level before layer is visible (0 = default, always visible) + public static int dynmapLayerMinimumZoom = 0; + // Format for popup - substitute values for macros + public static String dynmapDescription = + "
\n" + + "%name%
\n" + + "%description%
" + + "
\n" + + "Leader: %players.leader%
\n" + + "Admins: %players.admins.count%
\n" + + "Moderators: %players.moderators.count%
\n" + + "Members: %players.normals.count%
\n" + + "TOTAL: %players.count%
\n" + + "
\n" + + "Bank: %money%
\n" + + "
\n" + + "
"; + // Enable the %money% macro. Only do this if you know your economy manager is thread-safe. + public static boolean dynmapDescriptionMoney = false; + // Allow players in faction to see one another on Dynmap (only relevant if Dynmap has 'player-info-protected' enabled) + public static boolean dynmapVisibilityByFaction = true; + // Optional setting to limit which regions to show. + // If empty all regions are shown. + // Specify Faction either by name or UUID. + // To show all regions on a given world, add 'world:' to the list. + public static Set dynmapVisibleFactions = new HashSet<>(); + // Optional setting to hide specific Factions. + // Specify Faction either by name or UUID. + // To hide all regions on a given world, add 'world:' to the list. + public static Set dynmapHiddenFactions = new HashSet<>(); + public static DynmapStyle dynmapDefaultStyle = new DynmapStyle() + .setStrokeColor(DYNMAP_STYLE_LINE_COLOR) + .setLineOpacity(DYNMAP_STYLE_LINE_OPACITY) + .setLineWeight(DYNMAP_STYLE_LINE_WEIGHT) + .setFillColor(DYNMAP_STYLE_FILL_COLOR) + .setFillOpacity(DYNMAP_STYLE_FILL_OPACITY) + .setHomeMarker(DYNMAP_STYLE_HOME_MARKER) + .setBoost(DYNMAP_STYLE_BOOST); - // Optional per Faction style overrides. Any defined replace those in dynmapDefaultStyle. - // Specify Faction either by name or UUID. - public static Map dynmapFactionStyles = ImmutableMap.of( - "SafeZone", new DynmapStyle().setStrokeColor("#FF00FF").setFillColor("#FF00FF").setBoost(false), - "WarZone", new DynmapStyle().setStrokeColor("#FF0000").setFillColor("#FF0000").setBoost(false) - ); + // Optional per Faction style overrides. Any defined replace those in dynmapDefaultStyle. + // Specify Faction either by name or UUID. + public static Map dynmapFactionStyles = ImmutableMap.of( + "SafeZone", new DynmapStyle().setStrokeColor("#FF00FF").setFillColor("#FF00FF").setBoost(false), + "WarZone", new DynmapStyle().setStrokeColor("#FF0000").setFillColor("#FF0000").setBoost(false) + ); - //Faction banks, to pay for land claiming and other costs instead of individuals paying for them - public static boolean bankEnabled = true; - public static boolean bankMembersCanWithdraw = false; //Have to be at least moderator to withdraw or pay money to another faction - public static boolean bankFactionPaysCosts = true; //The faction pays for faction command costs, such as sethome - public static boolean bankFactionPaysLandCosts = true; //The faction pays for land claiming costs. + //Faction banks, to pay for land claiming and other costs instead of individuals paying for them + public static boolean bankEnabled = true; + public static boolean bankMembersCanWithdraw = false; //Have to be at least moderator to withdraw or pay money to another faction + public static boolean bankFactionPaysCosts = true; //The faction pays for faction command costs, such as sethome + public static boolean bankFactionPaysLandCosts = true; //The faction pays for land claiming costs. - // mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections - public static Set playersWhoBypassAllProtection = new LinkedHashSet<>(); + // mainly for other plugins/mods that use a fake player to take actions, which shouldn't be subject to our protections + public static Set playersWhoBypassAllProtection = new LinkedHashSet<>(); - public static Set worldsNoClaiming = new LinkedHashSet<>(); - public static Set worldsNoPowerLoss = new LinkedHashSet<>(); - public static Set worldsIgnorePvP = new LinkedHashSet<>(); - public static Set worldsNoWildernessProtection = new LinkedHashSet<>(); + public static Set worldsNoClaiming = new LinkedHashSet<>(); + public static Set worldsNoPowerLoss = new LinkedHashSet<>(); + public static Set worldsIgnorePvP = new LinkedHashSet<>(); + public static Set worldsNoWildernessProtection = new LinkedHashSet<>(); - // faction- - public static String vaultPrefix = "faction-%s"; - public static int defaultMaxVaults = 0; + // faction- + public static String vaultPrefix = "faction-%s"; + public static int defaultMaxVaults = 0; - public static Backend backEnd = Backend.JSON; + public static Backend backEnd = Backend.JSON; - // Taller and wider for "bigger f map" - public static int mapHeight = 17; - public static int mapWidth = 49; - public static transient char[] mapKeyChrs = "\\/#$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz?".toCharArray(); + // Taller and wider for "bigger f map" + public static int mapHeight = 17; + public static int mapWidth = 49; + public static transient char[] mapKeyChrs = "\\/#$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz?".toCharArray(); - // Default Options - public static boolean useCustomDefaultPermissions = false; - public static boolean usePermissionHints = false; - public static HashMap defaultFactionPermissions; - // Custom Ranks - //public static boolean enableCustomRanks = false; // We will disable it by default to avoid any migration error - //public static int maxCustomRanks = 2; // Setting this to -1 will allow unlimited custom ranks - // -------------------------------------------- // - // Persistance - // -------------------------------------------- // - private static transient Conf i = new Conf(); + // Default Options + public static boolean useCustomDefaultPermissions = false; + public static boolean usePermissionHints = false; + public static HashMap defaultFactionPermissions; + // Custom Ranks + //public static boolean enableCustomRanks = false; // We will disable it by default to avoid any migration error + //public static int maxCustomRanks = 2; // Setting this to -1 will allow unlimited custom ranks + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // + private static transient Conf i = new Conf(); - static { - baseCommandAliases.add("f"); + static { + baseCommandAliases.add("f"); - territoryEnemyDenyCommands.add("home"); - territoryEnemyDenyCommands.add("sethome"); - territoryEnemyDenyCommands.add("spawn"); - territoryEnemyDenyCommands.add("tpahere"); - territoryEnemyDenyCommands.add("tpaccept"); - territoryEnemyDenyCommands.add("tpa"); + territoryEnemyDenyCommands.add("home"); + territoryEnemyDenyCommands.add("sethome"); + territoryEnemyDenyCommands.add("spawn"); + territoryEnemyDenyCommands.add("tpahere"); + territoryEnemyDenyCommands.add("tpaccept"); + territoryEnemyDenyCommands.add("tpa"); - territoryProtectedMaterials.add(SavageFactions.plugin.WOODEN_DOOR); - territoryProtectedMaterials.add(SavageFactions.plugin.TRAP_DOOR); - territoryProtectedMaterials.add(SavageFactions.plugin.FENCE_GATE); - territoryProtectedMaterials.add(Material.DISPENSER); - territoryProtectedMaterials.add(Material.CHEST); - territoryProtectedMaterials.add(Material.FURNACE); - territoryProtectedMaterials.add(SavageFactions.plugin.BURNING_FURNACE); - territoryProtectedMaterials.add(SavageFactions.plugin.DIODE_BLOCK_OFF); - territoryProtectedMaterials.add(SavageFactions.plugin.DIODE_BLOCK_ON); - territoryProtectedMaterials.add(Material.JUKEBOX); - territoryProtectedMaterials.add(Material.BREWING_STAND); - territoryProtectedMaterials.add(SavageFactions.plugin.ENCHANTMENT_TABLE); - territoryProtectedMaterials.add(Material.CAULDRON); - territoryProtectedMaterials.add(SavageFactions.plugin.ENCHANTMENT_TABLE); - territoryProtectedMaterials.add(Material.BEACON); - territoryProtectedMaterials.add(Material.ANVIL); - territoryProtectedMaterials.add(Material.TRAPPED_CHEST); - territoryProtectedMaterials.add(Material.DROPPER); - territoryProtectedMaterials.add(Material.HOPPER); + territoryProtectedMaterials.add(SavageFactions.plugin.WOODEN_DOOR); + territoryProtectedMaterials.add(SavageFactions.plugin.TRAP_DOOR); + territoryProtectedMaterials.add(SavageFactions.plugin.FENCE_GATE); + territoryProtectedMaterials.add(Material.DISPENSER); + territoryProtectedMaterials.add(Material.CHEST); + territoryProtectedMaterials.add(Material.FURNACE); + territoryProtectedMaterials.add(SavageFactions.plugin.BURNING_FURNACE); + territoryProtectedMaterials.add(SavageFactions.plugin.DIODE_BLOCK_OFF); + territoryProtectedMaterials.add(SavageFactions.plugin.DIODE_BLOCK_ON); + territoryProtectedMaterials.add(Material.JUKEBOX); + territoryProtectedMaterials.add(Material.BREWING_STAND); + territoryProtectedMaterials.add(SavageFactions.plugin.ENCHANTMENT_TABLE); + territoryProtectedMaterials.add(Material.CAULDRON); + territoryProtectedMaterials.add(SavageFactions.plugin.ENCHANTMENT_TABLE); + territoryProtectedMaterials.add(Material.BEACON); + territoryProtectedMaterials.add(Material.ANVIL); + territoryProtectedMaterials.add(Material.TRAPPED_CHEST); + territoryProtectedMaterials.add(Material.DROPPER); + territoryProtectedMaterials.add(Material.HOPPER); - territoryDenyUseageMaterials.add(SavageFactions.plugin.FIREBALL); - territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterials.add(Material.BUCKET); - territoryDenyUseageMaterials.add(Material.WATER_BUCKET); - territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); - territoryDenyUseageMaterials.add(MultiversionMaterials.ACACIA_BUTTON.parseMaterial()); - territoryDenyUseageMaterials.add(MultiversionMaterials.BIRCH_BUTTON.parseMaterial()); - territoryDenyUseageMaterials.add(MultiversionMaterials.DARK_OAK_BUTTON.parseMaterial()); - territoryDenyUseageMaterials.add(MultiversionMaterials.JUNGLE_BUTTON.parseMaterial()); - territoryDenyUseageMaterials.add(MultiversionMaterials.OAK_BUTTON.parseMaterial()); - territoryDenyUseageMaterials.add(MultiversionMaterials.STONE_BUTTON.parseMaterial()); - if (!SavageFactions.plugin.mc17) { - territoryDenyUseageMaterials.add(Material.ARMOR_STAND); - } + territoryDenyUseageMaterials.add(SavageFactions.plugin.FIREBALL); + territoryDenyUseageMaterials.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterials.add(Material.BUCKET); + territoryDenyUseageMaterials.add(Material.WATER_BUCKET); + territoryDenyUseageMaterials.add(Material.LAVA_BUCKET); + territoryDenyUseageMaterials.add(MultiversionMaterials.ACACIA_BUTTON.parseMaterial()); + territoryDenyUseageMaterials.add(MultiversionMaterials.BIRCH_BUTTON.parseMaterial()); + territoryDenyUseageMaterials.add(MultiversionMaterials.DARK_OAK_BUTTON.parseMaterial()); + territoryDenyUseageMaterials.add(MultiversionMaterials.JUNGLE_BUTTON.parseMaterial()); + territoryDenyUseageMaterials.add(MultiversionMaterials.OAK_BUTTON.parseMaterial()); + territoryDenyUseageMaterials.add(MultiversionMaterials.STONE_BUTTON.parseMaterial()); + if (!SavageFactions.plugin.mc17) { + territoryDenyUseageMaterials.add(Material.ARMOR_STAND); + } - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.WOODEN_DOOR); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.TRAP_DOOR); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.FENCE_GATE); - territoryProtectedMaterialsWhenOffline.add(Material.DISPENSER); - territoryProtectedMaterialsWhenOffline.add(Material.CHEST); - territoryProtectedMaterialsWhenOffline.add(Material.FURNACE); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.BURNING_FURNACE); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.DIODE_BLOCK_OFF); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.DIODE_BLOCK_OFF); - territoryProtectedMaterialsWhenOffline.add(Material.JUKEBOX); - territoryProtectedMaterialsWhenOffline.add(Material.BREWING_STAND); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.ENCHANTMENT_TABLE); - territoryProtectedMaterialsWhenOffline.add(Material.CAULDRON); - territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.SOIL); - territoryProtectedMaterialsWhenOffline.add(Material.BEACON); - territoryProtectedMaterialsWhenOffline.add(Material.ANVIL); - territoryProtectedMaterialsWhenOffline.add(Material.TRAPPED_CHEST); - territoryProtectedMaterialsWhenOffline.add(Material.DROPPER); - territoryProtectedMaterialsWhenOffline.add(Material.HOPPER); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.WOODEN_DOOR); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.TRAP_DOOR); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.FENCE_GATE); + territoryProtectedMaterialsWhenOffline.add(Material.DISPENSER); + territoryProtectedMaterialsWhenOffline.add(Material.CHEST); + territoryProtectedMaterialsWhenOffline.add(Material.FURNACE); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.BURNING_FURNACE); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.DIODE_BLOCK_OFF); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.DIODE_BLOCK_OFF); + territoryProtectedMaterialsWhenOffline.add(Material.JUKEBOX); + territoryProtectedMaterialsWhenOffline.add(Material.BREWING_STAND); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.ENCHANTMENT_TABLE); + territoryProtectedMaterialsWhenOffline.add(Material.CAULDRON); + territoryProtectedMaterialsWhenOffline.add(SavageFactions.plugin.SOIL); + territoryProtectedMaterialsWhenOffline.add(Material.BEACON); + territoryProtectedMaterialsWhenOffline.add(Material.ANVIL); + territoryProtectedMaterialsWhenOffline.add(Material.TRAPPED_CHEST); + territoryProtectedMaterialsWhenOffline.add(Material.DROPPER); + territoryProtectedMaterialsWhenOffline.add(Material.HOPPER); - territoryDenyUseageMaterialsWhenOffline.add(SavageFactions.plugin.FIREBALL); - territoryDenyUseageMaterialsWhenOffline.add(Material.FLINT_AND_STEEL); - territoryDenyUseageMaterialsWhenOffline.add(Material.BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); - territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.ACACIA_BUTTON.parseMaterial()); - territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.BIRCH_BUTTON.parseMaterial()); - territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.DARK_OAK_BUTTON.parseMaterial()); - territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.JUNGLE_BUTTON.parseMaterial()); - territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.OAK_BUTTON.parseMaterial()); - territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.STONE_BUTTON.parseMaterial()); - if (!SavageFactions.plugin.mc17) { - territoryDenyUseageMaterialsWhenOffline.add(Material.ARMOR_STAND); - } - safeZoneNerfedCreatureTypes.add(EntityType.BLAZE); - safeZoneNerfedCreatureTypes.add(EntityType.CAVE_SPIDER); - safeZoneNerfedCreatureTypes.add(EntityType.CREEPER); - safeZoneNerfedCreatureTypes.add(EntityType.ENDER_DRAGON); - safeZoneNerfedCreatureTypes.add(EntityType.ENDERMAN); - safeZoneNerfedCreatureTypes.add(EntityType.GHAST); - safeZoneNerfedCreatureTypes.add(EntityType.MAGMA_CUBE); - safeZoneNerfedCreatureTypes.add(EntityType.PIG_ZOMBIE); - safeZoneNerfedCreatureTypes.add(EntityType.SILVERFISH); - safeZoneNerfedCreatureTypes.add(EntityType.SKELETON); - safeZoneNerfedCreatureTypes.add(EntityType.SPIDER); - safeZoneNerfedCreatureTypes.add(EntityType.SLIME); - safeZoneNerfedCreatureTypes.add(EntityType.WITCH); - safeZoneNerfedCreatureTypes.add(EntityType.WITHER); - safeZoneNerfedCreatureTypes.add(EntityType.ZOMBIE); - // Is this called lazy load? - defaultFactionPermissions.put("LEADER", new DefaultPermissions(true)); - defaultFactionPermissions.put("COLEADER", new DefaultPermissions(true)); - defaultFactionPermissions.put("MODERATOR", new DefaultPermissions(true)); - defaultFactionPermissions.put("MEMBER", new DefaultPermissions(false)); - defaultFactionPermissions.put("RECRUIT", new DefaultPermissions(false)); - } + territoryDenyUseageMaterialsWhenOffline.add(SavageFactions.plugin.FIREBALL); + territoryDenyUseageMaterialsWhenOffline.add(Material.FLINT_AND_STEEL); + territoryDenyUseageMaterialsWhenOffline.add(Material.BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(Material.WATER_BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(Material.LAVA_BUCKET); + territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.ACACIA_BUTTON.parseMaterial()); + territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.BIRCH_BUTTON.parseMaterial()); + territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.DARK_OAK_BUTTON.parseMaterial()); + territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.JUNGLE_BUTTON.parseMaterial()); + territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.OAK_BUTTON.parseMaterial()); + territoryDenyUseageMaterialsWhenOffline.add(MultiversionMaterials.STONE_BUTTON.parseMaterial()); + if (!SavageFactions.plugin.mc17) { + territoryDenyUseageMaterialsWhenOffline.add(Material.ARMOR_STAND); + } + safeZoneNerfedCreatureTypes.add(EntityType.BLAZE); + safeZoneNerfedCreatureTypes.add(EntityType.CAVE_SPIDER); + safeZoneNerfedCreatureTypes.add(EntityType.CREEPER); + safeZoneNerfedCreatureTypes.add(EntityType.ENDER_DRAGON); + safeZoneNerfedCreatureTypes.add(EntityType.ENDERMAN); + safeZoneNerfedCreatureTypes.add(EntityType.GHAST); + safeZoneNerfedCreatureTypes.add(EntityType.MAGMA_CUBE); + safeZoneNerfedCreatureTypes.add(EntityType.PIG_ZOMBIE); + safeZoneNerfedCreatureTypes.add(EntityType.SILVERFISH); + safeZoneNerfedCreatureTypes.add(EntityType.SKELETON); + safeZoneNerfedCreatureTypes.add(EntityType.SPIDER); + safeZoneNerfedCreatureTypes.add(EntityType.SLIME); + safeZoneNerfedCreatureTypes.add(EntityType.WITCH); + safeZoneNerfedCreatureTypes.add(EntityType.WITHER); + safeZoneNerfedCreatureTypes.add(EntityType.ZOMBIE); + // Is this called lazy load? + defaultFactionPermissions.put("LEADER", new DefaultPermissions(true)); + defaultFactionPermissions.put("COLEADER", new DefaultPermissions(true)); + defaultFactionPermissions.put("MODERATOR", new DefaultPermissions(true)); + defaultFactionPermissions.put("MEMBER", new DefaultPermissions(false)); + defaultFactionPermissions.put("RECRUIT", new DefaultPermissions(false)); + } - public static void load() { - SavageFactions.plugin.persist.loadOrSaveDefault(i, Conf.class, "conf"); - } + public static void load() { + SavageFactions.plugin.persist.loadOrSaveDefault(i, Conf.class, "conf"); + } - public static void save() { - SavageFactions.plugin.persist.save(i); - } + public static void save() { + SavageFactions.plugin.persist.save(i); + } - public enum Backend { - JSON, - //MYSQL, TODO add MySQL storage - ; - } + public enum Backend { + JSON, + //MYSQL, TODO add MySQL storage + ; + } } diff --git a/src/main/java/com/massivecraft/factions/FLocation.java b/src/main/java/com/massivecraft/factions/FLocation.java index 1c684ce0..0f9c71fd 100644 --- a/src/main/java/com/massivecraft/factions/FLocation.java +++ b/src/main/java/com/massivecraft/factions/FLocation.java @@ -11,247 +11,247 @@ import java.util.LinkedHashSet; import java.util.Set; public class FLocation implements Serializable { - private static final long serialVersionUID = -8292915234027387983L; - private static final boolean worldBorderSupport; + private static final long serialVersionUID = -8292915234027387983L; + private static final boolean worldBorderSupport; - static { - boolean worldBorderClassPresent = false; - try { - Class.forName("org.bukkit.WorldBorder"); - worldBorderClassPresent = true; - } catch (ClassNotFoundException ignored) { - } + static { + boolean worldBorderClassPresent = false; + try { + Class.forName("org.bukkit.WorldBorder"); + worldBorderClassPresent = true; + } catch (ClassNotFoundException ignored) { + } - worldBorderSupport = worldBorderClassPresent; - } + worldBorderSupport = worldBorderClassPresent; + } - private String worldName = "world"; - private int x = 0; - private int z = 0; + private String worldName = "world"; + private int x = 0; + private int z = 0; - //----------------------------------------------// - // Constructors - //----------------------------------------------// + //----------------------------------------------// + // Constructors + //----------------------------------------------// - public FLocation() { + public FLocation() { - } + } - public FLocation(String worldName, int x, int z) { - this.worldName = worldName; - this.x = x; - this.z = z; - } + public FLocation(String worldName, int x, int z) { + this.worldName = worldName; + this.x = x; + this.z = z; + } - public FLocation(Location location) { - this(location.getWorld().getName(), blockToChunk(location.getBlockX()), blockToChunk(location.getBlockZ())); - } + public FLocation(Location location) { + this(location.getWorld().getName(), blockToChunk(location.getBlockX()), blockToChunk(location.getBlockZ())); + } - public FLocation(Player player) { - this(player.getLocation()); - } + public FLocation(Player player) { + this(player.getLocation()); + } - public FLocation(FPlayer fplayer) { - this(fplayer.getPlayer()); - } + public FLocation(FPlayer fplayer) { + this(fplayer.getPlayer()); + } - public FLocation(Block block) { - this(block.getLocation()); - } + public FLocation(Block block) { + this(block.getLocation()); + } - //----------------------------------------------// - // Getters and Setters - //----------------------------------------------// + //----------------------------------------------// + // Getters and Setters + //----------------------------------------------// - public static FLocation fromString(String string) { - int index = string.indexOf(","); - int start = 1; - String worldName = string.substring(start, index); - start = index + 1; - index = string.indexOf(",", start); - int x = Integer.valueOf(string.substring(start, index)); - int y = Integer.valueOf(string.substring(index + 1, string.length() - 1)); - return new FLocation(worldName, x, y); - } + public static FLocation fromString(String string) { + int index = string.indexOf(","); + int start = 1; + String worldName = string.substring(start, index); + start = index + 1; + index = string.indexOf(",", start); + int x = Integer.valueOf(string.substring(start, index)); + int y = Integer.valueOf(string.substring(index + 1, string.length() - 1)); + return new FLocation(worldName, x, y); + } - // bit-shifting is used because it's much faster than standard division and multiplication - public static int blockToChunk(int blockVal) { // 1 chunk is 16x16 blocks - return blockVal >> 4; // ">> 4" == "/ 16" - } + // bit-shifting is used because it's much faster than standard division and multiplication + public static int blockToChunk(int blockVal) { // 1 chunk is 16x16 blocks + return blockVal >> 4; // ">> 4" == "/ 16" + } - public static int blockToRegion(int blockVal) { // 1 region is 512x512 blocks - return blockVal >> 9; // ">> 9" == "/ 512" - } + public static int blockToRegion(int blockVal) { // 1 region is 512x512 blocks + return blockVal >> 9; // ">> 9" == "/ 512" + } - public static int chunkToRegion(int chunkVal) { // 1 region is 32x32 chunks - return chunkVal >> 5; // ">> 5" == "/ 32" - } + public static int chunkToRegion(int chunkVal) { // 1 region is 32x32 chunks + return chunkVal >> 5; // ">> 5" == "/ 32" + } - public static int chunkToBlock(int chunkVal) { - return chunkVal << 4; // "<< 4" == "* 16" - } + public static int chunkToBlock(int chunkVal) { + return chunkVal << 4; // "<< 4" == "* 16" + } - public static int regionToBlock(int regionVal) { - return regionVal << 9; // "<< 9" == "* 512" - } + public static int regionToBlock(int regionVal) { + return regionVal << 9; // "<< 9" == "* 512" + } - public static int regionToChunk(int regionVal) { - return regionVal << 5; // "<< 5" == "* 32" - } + public static int regionToChunk(int regionVal) { + return regionVal << 5; // "<< 5" == "* 32" + } - public static HashSet getArea(FLocation from, FLocation to) { - HashSet ret = new HashSet<>(); + public static HashSet getArea(FLocation from, FLocation to) { + HashSet ret = new HashSet<>(); - for (long x : MiscUtil.range(from.getX(), to.getX())) { - for (long z : MiscUtil.range(from.getZ(), to.getZ())) { - ret.add(new FLocation(from.getWorldName(), (int) x, (int) z)); - } - } + for (long x : MiscUtil.range(from.getX(), to.getX())) { + for (long z : MiscUtil.range(from.getZ(), to.getZ())) { + ret.add(new FLocation(from.getWorldName(), (int) x, (int) z)); + } + } - return ret; - } + return ret; + } - public Chunk getChunk() { - return Bukkit.getWorld(worldName).getChunkAt(x, z); - } + public Chunk getChunk() { + return Bukkit.getWorld(worldName).getChunkAt(x, z); + } - public String getWorldName() { - return worldName; - } + public String getWorldName() { + return worldName; + } - public void setWorldName(String worldName) { - this.worldName = worldName; - } + public void setWorldName(String worldName) { + this.worldName = worldName; + } - //----------------------------------------------// - // Block/Chunk/Region Value Transformation - //----------------------------------------------// + //----------------------------------------------// + // Block/Chunk/Region Value Transformation + //----------------------------------------------// - public World getWorld() { - return Bukkit.getWorld(worldName); - } + public World getWorld() { + return Bukkit.getWorld(worldName); + } - public long getX() { - return x; - } + public long getX() { + return x; + } - public void setX(int x) { - this.x = x; - } + public void setX(int x) { + this.x = x; + } - public long getZ() { - return z; - } + public long getZ() { + return z; + } - public void setZ(int z) { - this.z = z; - } + public void setZ(int z) { + this.z = z; + } - public String getCoordString() { - return "" + x + "," + z; - } + public String getCoordString() { + return "" + x + "," + z; + } - //----------------------------------------------// - // Misc Geometry - //----------------------------------------------// + //----------------------------------------------// + // Misc Geometry + //----------------------------------------------// - @Override - public String toString() { - return "[" + this.getWorldName() + "," + this.getCoordString() + "]"; - } + @Override + public String toString() { + return "[" + this.getWorldName() + "," + this.getCoordString() + "]"; + } - public FLocation getRelative(int dx, int dz) { - return new FLocation(this.worldName, this.x + dx, this.z + dz); - } + public FLocation getRelative(int dx, int dz) { + return new FLocation(this.worldName, this.x + dx, this.z + dz); + } - public double getDistanceTo(FLocation that) { - double dx = that.x - this.x; - double dz = that.z - this.z; - return Math.sqrt(dx * dx + dz * dz); - } + public double getDistanceTo(FLocation that) { + double dx = that.x - this.x; + double dz = that.z - this.z; + return Math.sqrt(dx * dx + dz * dz); + } - public double getDistanceSquaredTo(FLocation that) { - double dx = that.x - this.x; - double dz = that.z - this.z; - return dx * dx + dz * dz; - } + public double getDistanceSquaredTo(FLocation that) { + double dx = that.x - this.x; + double dz = that.z - this.z; + return dx * dx + dz * dz; + } - public boolean isInChunk(Location loc) { - if (loc == null) { - return false; - } - Chunk chunk = loc.getChunk(); - return loc.getWorld().getName().equalsIgnoreCase(getWorldName()) && chunk.getX() == x && chunk.getZ() == z; - } + public boolean isInChunk(Location loc) { + if (loc == null) { + return false; + } + Chunk chunk = loc.getChunk(); + return loc.getWorld().getName().equalsIgnoreCase(getWorldName()) && chunk.getX() == x && chunk.getZ() == z; + } - /** - * Checks if the chunk represented by this FLocation is outside the world border - * - * @param buffer the number of chunks from the border that will be treated as "outside" - * @return whether this location is outside of the border - */ - public boolean isOutsideWorldBorder(int buffer) { - if (!worldBorderSupport) { - return false; - } + /** + * Checks if the chunk represented by this FLocation is outside the world border + * + * @param buffer the number of chunks from the border that will be treated as "outside" + * @return whether this location is outside of the border + */ + public boolean isOutsideWorldBorder(int buffer) { + if (!worldBorderSupport) { + return false; + } - WorldBorder border = getWorld().getWorldBorder(); - Chunk chunk = border.getCenter().getChunk(); + WorldBorder border = getWorld().getWorldBorder(); + Chunk chunk = border.getCenter().getChunk(); - int lim = FLocation.chunkToRegion((int) border.getSize()) - buffer; - int diffX = chunk.getX() - x; - int diffZ = chunk.getZ() - z; - return diffX > lim || diffZ > lim || -diffX > lim - 1 || -diffZ > lim - 1; - } + int lim = FLocation.chunkToRegion((int) border.getSize()) - buffer; + int diffX = chunk.getX() - x; + int diffZ = chunk.getZ() - z; + return diffX > lim || diffZ > lim || -diffX > lim - 1 || -diffZ > lim - 1; + } - //----------------------------------------------// - // Some Geometry - //----------------------------------------------// - public Set getCircle(double radius) { - double radiusSquared = radius * radius; + //----------------------------------------------// + // Some Geometry + //----------------------------------------------// + public Set getCircle(double radius) { + double radiusSquared = radius * radius; - Set ret = new LinkedHashSet<>(); - if (radius <= 0) { - return ret; - } + Set ret = new LinkedHashSet<>(); + if (radius <= 0) { + return ret; + } - int xfrom = (int) Math.floor(this.x - radius); - int xto = (int) Math.ceil(this.x + radius); - int zfrom = (int) Math.floor(this.z - radius); - int zto = (int) Math.ceil(this.z + radius); + int xfrom = (int) Math.floor(this.x - radius); + int xto = (int) Math.ceil(this.x + radius); + int zfrom = (int) Math.floor(this.z - radius); + int zto = (int) Math.ceil(this.z + radius); - for (int x = xfrom; x <= xto; x++) { - for (int z = zfrom; z <= zto; z++) { - FLocation potential = new FLocation(this.worldName, x, z); - if (this.getDistanceSquaredTo(potential) <= radiusSquared) { - ret.add(potential); - } - } - } + for (int x = xfrom; x <= xto; x++) { + for (int z = zfrom; z <= zto; z++) { + FLocation potential = new FLocation(this.worldName, x, z); + if (this.getDistanceSquaredTo(potential) <= radiusSquared) { + ret.add(potential); + } + } + } - return ret; - } + return ret; + } - //----------------------------------------------// - // Comparison - //----------------------------------------------// + //----------------------------------------------// + // Comparison + //----------------------------------------------// - @Override - public int hashCode() { - // should be fast, with good range and few hash collisions: (x * 512) + z + worldName.hashCode - return (this.x << 9) + this.z + (this.worldName != null ? this.worldName.hashCode() : 0); - } + @Override + public int hashCode() { + // should be fast, with good range and few hash collisions: (x * 512) + z + worldName.hashCode + return (this.x << 9) + this.z + (this.worldName != null ? this.worldName.hashCode() : 0); + } - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof FLocation)) { - return false; - } + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof FLocation)) { + return false; + } - FLocation that = (FLocation) obj; - return this.x == that.x && this.z == that.z && (this.worldName == null ? that.worldName == null : this.worldName.equals(that.worldName)); - } + FLocation that = (FLocation) obj; + return this.x == that.x && this.z == that.z && (this.worldName == null ? that.worldName == null : this.worldName.equals(that.worldName)); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/FPlayer.java b/src/main/java/com/massivecraft/factions/FPlayer.java index 48d1a44a..359f09ba 100644 --- a/src/main/java/com/massivecraft/factions/FPlayer.java +++ b/src/main/java/com/massivecraft/factions/FPlayer.java @@ -26,354 +26,354 @@ import java.util.List; public interface FPlayer extends EconomyParticipator { - /** - * Used to know if stealth is toggled on or off - * - * @return if stealth mode is on or not. - */ - boolean isStealthEnabled(); + /** + * Used to know if stealth is toggled on or off + * + * @return if stealth mode is on or not. + */ + boolean isStealthEnabled(); - /** - * Toggles the stealth of the FPlayer depending on the parameter - * - * @param stealthToggle - toggles stealth - */ - void setStealth(boolean stealthToggle); + /** + * Toggles the stealth of the FPlayer depending on the parameter + * + * @param stealthToggle - toggles stealth + */ + void setStealth(boolean stealthToggle); - /** - * Sets the kills and deaths of a player. - */ - void login(); + /** + * Sets the kills and deaths of a player. + */ + void login(); - /** - * Caches the kills and deaths of a player. - */ - void logout(); + /** + * Caches the kills and deaths of a player. + */ + void logout(); - /** - * gets the faction of a FPlayer. - * - * @return Faction of the FPlayer. - */ - Faction getFaction(); + /** + * gets the faction of a FPlayer. + * + * @return Faction of the FPlayer. + */ + Faction getFaction(); - /** - * Sets the faction of the FPlayer - * - * @param faction faction to set. - */ - void setFaction(Faction faction); + /** + * Sets the faction of the FPlayer + * + * @param faction faction to set. + */ + void setFaction(Faction faction); - /** - * Gets the faction ID of the player. - * - * @return FactionsID string - */ - String getFactionId(); + /** + * Gets the faction ID of the player. + * + * @return FactionsID string + */ + String getFactionId(); - /** - * Check if a player has a faction - * - * @return boolean - */ - boolean hasFaction(); + /** + * Check if a player has a faction + * + * @return boolean + */ + boolean hasFaction(); - /** - * Gets autoleave status - * - * @return boolean of the autoleave - */ - boolean willAutoLeave(); + /** + * Gets autoleave status + * + * @return boolean of the autoleave + */ + boolean willAutoLeave(); - void setAutoLeave(boolean autoLeave); + void setAutoLeave(boolean autoLeave); - long getLastFrostwalkerMessage(); + long getLastFrostwalkerMessage(); - void setLastFrostwalkerMessage(); + void setLastFrostwalkerMessage(); - void setMonitorJoins(boolean monitor); + void setMonitorJoins(boolean monitor); - boolean isMonitoringJoins(); + boolean isMonitoringJoins(); - Role getRole(); + Role getRole(); - void setRole(Role role); + void setRole(Role role); - boolean shouldTakeFallDamage(); + boolean shouldTakeFallDamage(); - void setTakeFallDamage(boolean fallDamage); + void setTakeFallDamage(boolean fallDamage); - double getPowerBoost(); + double getPowerBoost(); - void setPowerBoost(double powerBoost); + void setPowerBoost(double powerBoost); - Faction getAutoClaimFor(); + Faction getAutoClaimFor(); - void setAutoClaimFor(Faction faction); + void setAutoClaimFor(Faction faction); - boolean isAutoSafeClaimEnabled(); + boolean isAutoSafeClaimEnabled(); - void setIsAutoSafeClaimEnabled(boolean enabled); + void setIsAutoSafeClaimEnabled(boolean enabled); - boolean isAutoWarClaimEnabled(); + boolean isAutoWarClaimEnabled(); - void setIsAutoWarClaimEnabled(boolean enabled); + void setIsAutoWarClaimEnabled(boolean enabled); - boolean isAdminBypassing(); + boolean isAdminBypassing(); - boolean isVanished(); + boolean isVanished(); - void setIsAdminBypassing(boolean val); + void setIsAdminBypassing(boolean val); - ChatMode getChatMode(); + ChatMode getChatMode(); - void setChatMode(ChatMode chatMode); + void setChatMode(ChatMode chatMode); - boolean isIgnoreAllianceChat(); + boolean isIgnoreAllianceChat(); - void setIgnoreAllianceChat(boolean ignore); + void setIgnoreAllianceChat(boolean ignore); - boolean isSpyingChat(); + boolean isSpyingChat(); - void setSpyingChat(boolean chatSpying); + void setSpyingChat(boolean chatSpying); - boolean showScoreboard(); + boolean showScoreboard(); - void setShowScoreboard(boolean show); + void setShowScoreboard(boolean show); - // FIELD: account - String getAccountId(); + // FIELD: account + String getAccountId(); - void resetFactionData(boolean doSpoutUpdate); + void resetFactionData(boolean doSpoutUpdate); - void resetFactionData(); + void resetFactionData(); - long getLastLoginTime(); + long getLastLoginTime(); - void setLastLoginTime(long lastLoginTime); + void setLastLoginTime(long lastLoginTime); - boolean isMapAutoUpdating(); + boolean isMapAutoUpdating(); - void setMapAutoUpdating(boolean mapAutoUpdating); + void setMapAutoUpdating(boolean mapAutoUpdating); - boolean hasLoginPvpDisabled(); + boolean hasLoginPvpDisabled(); - FLocation getLastStoodAt(); + FLocation getLastStoodAt(); - void setLastStoodAt(FLocation flocation); + void setLastStoodAt(FLocation flocation); - String getTitle(); + String getTitle(); - void setTitle(CommandSender sender, String title); + void setTitle(CommandSender sender, String title); - String getName(); + String getName(); - String getTag(); + String getTag(); - // Base concatenations: + // Base concatenations: - String getNameAndSomething(String something); + String getNameAndSomething(String something); - String getNameAndTitle(); + String getNameAndTitle(); - String getNameAndTag(); + String getNameAndTag(); - // Colored concatenations: - // These are used in information messages + // Colored concatenations: + // These are used in information messages - String getNameAndTitle(Faction faction); + String getNameAndTitle(Faction faction); - String getNameAndTitle(FPlayer fplayer); + String getNameAndTitle(FPlayer fplayer); - // Chat Tag: - // These are injected into the format of global chat messages. + // Chat Tag: + // These are injected into the format of global chat messages. - String getChatTag(); + String getChatTag(); - // Colored Chat Tag - String getChatTag(Faction faction); + // Colored Chat Tag + String getChatTag(Faction faction); - String getChatTag(FPlayer fplayer); + String getChatTag(FPlayer fplayer); - int getKills(); + int getKills(); - int getDeaths(); + int getDeaths(); - void takeMoney(int amt); + void takeMoney(int amt); - boolean hasMoney(int amt); + boolean hasMoney(int amt); - //inspect Stuff + //inspect Stuff - boolean isInspectMode(); + boolean isInspectMode(); - void setInspectMode(boolean status); + void setInspectMode(boolean status); - // Fly Checks + // Fly Checks - Boolean canflyinWilderness(); + Boolean canflyinWilderness(); - Boolean canflyinWarzone(); + Boolean canflyinWarzone(); - Boolean canflyinSafezone(); + Boolean canflyinSafezone(); - Boolean canflyinEnemy(); + Boolean canflyinEnemy(); - Boolean canflyinAlly(); + Boolean canflyinAlly(); - Boolean canflyinTruce(); + Boolean canflyinTruce(); - Boolean canflyinNeutral(); + Boolean canflyinNeutral(); - // ------------------------------- - // Relation and relation colors - // ------------------------------- + // ------------------------------- + // Relation and relation colors + // ------------------------------- - @Override - String describeTo(RelationParticipator that, boolean ucfirst); + @Override + String describeTo(RelationParticipator that, boolean ucfirst); - @Override - String describeTo(RelationParticipator that); + @Override + String describeTo(RelationParticipator that); - @Override - Relation getRelationTo(RelationParticipator rp); + @Override + Relation getRelationTo(RelationParticipator rp); - @Override - Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful); + @Override + Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful); - Relation getRelationToLocation(); + Relation getRelationToLocation(); - @Override - ChatColor getColorTo(RelationParticipator rp); + @Override + ChatColor getColorTo(RelationParticipator rp); - String getRolePrefix(); + String getRolePrefix(); - //----------------------------------------------// - // Health - //----------------------------------------------// - void heal(int amnt); + //----------------------------------------------// + // Health + //----------------------------------------------// + void heal(int amnt); - //----------------------------------------------// - // Power - //----------------------------------------------// - double getPower(); + //----------------------------------------------// + // Power + //----------------------------------------------// + double getPower(); - void alterPower(double delta); + void alterPower(double delta); - double getPowerMax(); + double getPowerMax(); - double getPowerMin(); + double getPowerMin(); - int getPowerRounded(); + int getPowerRounded(); - int getPowerMaxRounded(); + int getPowerMaxRounded(); - int getPowerMinRounded(); + int getPowerMinRounded(); - void updatePower(); + void updatePower(); - void losePowerFromBeingOffline(); + void losePowerFromBeingOffline(); - void onDeath(); + void onDeath(); - //----------------------------------------------// - // Territory - //----------------------------------------------// - boolean isInOwnTerritory(); + //----------------------------------------------// + // Territory + //----------------------------------------------// + boolean isInOwnTerritory(); - boolean isInOthersTerritory(); + boolean isInOthersTerritory(); - boolean isInAllyTerritory(); + boolean isInAllyTerritory(); - boolean isInNeutralTerritory(); + boolean isInNeutralTerritory(); - boolean isInEnemyTerritory(); + boolean isInEnemyTerritory(); - void sendFactionHereMessage(Faction from); + void sendFactionHereMessage(Faction from); - // ------------------------------- - // Actions - // ------------------------------- + // ------------------------------- + // Actions + // ------------------------------- - void leave(boolean makePay); + void leave(boolean makePay); - boolean canClaimForFaction(Faction forFaction); + boolean canClaimForFaction(Faction forFaction); - boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure); + boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure); - boolean canClaimForFactionAtLocation(Faction forFaction, FLocation location, boolean notifyFailure); + boolean canClaimForFactionAtLocation(Faction forFaction, FLocation location, boolean notifyFailure); - boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure); + boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure); - boolean attemptClaim(Faction forFaction, FLocation location, boolean notifyFailure); + boolean attemptClaim(Faction forFaction, FLocation location, boolean notifyFailure); - boolean isInVault(); + boolean isInVault(); - void setInVault(boolean status); + void setInVault(boolean status); - void msg(String str, Object... args); + void msg(String str, Object... args); - String getId(); + String getId(); - void setId(String id); + void setId(String id); - Player getPlayer(); + Player getPlayer(); - boolean isOnline(); + boolean isOnline(); - void sendMessage(String message); + void sendMessage(String message); - void sendMessage(List messages); + void sendMessage(List messages); - void sendFancyMessage(FancyMessage message); + void sendFancyMessage(FancyMessage message); - void sendFancyMessage(List message); + void sendFancyMessage(List message); - int getMapHeight(); + int getMapHeight(); - void setMapHeight(int height); + void setMapHeight(int height); - boolean isOnlineAndVisibleTo(Player me); + boolean isOnlineAndVisibleTo(Player me); - void remove(); + void remove(); - boolean isOffline(); + boolean isOffline(); - boolean isFlying(); + boolean isFlying(); - void setFlying(boolean fly); + void setFlying(boolean fly); - void setFFlying(boolean fly, boolean damage); + void setFFlying(boolean fly, boolean damage); - boolean canFlyAtLocation(); + boolean canFlyAtLocation(); - boolean canFlyAtLocation(FLocation location); + boolean canFlyAtLocation(FLocation location); - boolean isEnteringPassword(); + boolean isEnteringPassword(); - void setEnteringPassword(boolean toggle, String warp); + void setEnteringPassword(boolean toggle, String warp); - String getEnteringWarp(); + String getEnteringWarp(); - boolean checkIfNearbyEnemies(); + boolean checkIfNearbyEnemies(); - // ------------------------------- - // Warmups - // ------------------------------- + // ------------------------------- + // Warmups + // ------------------------------- - boolean isWarmingUp(); + boolean isWarmingUp(); - WarmUpUtil.Warmup getWarmupType(); + WarmUpUtil.Warmup getWarmupType(); - void addWarmup(WarmUpUtil.Warmup warmup, int taskId); + void addWarmup(WarmUpUtil.Warmup warmup, int taskId); - void stopWarmup(); + void stopWarmup(); - void clearWarmup(); + void clearWarmup(); } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/FPlayers.java b/src/main/java/com/massivecraft/factions/FPlayers.java index aca12183..a11917e7 100644 --- a/src/main/java/com/massivecraft/factions/FPlayers.java +++ b/src/main/java/com/massivecraft/factions/FPlayers.java @@ -1,41 +1,41 @@ -package com.massivecraft.factions; - -import com.massivecraft.factions.zcore.persist.json.JSONFPlayers; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import java.util.Collection; - -public abstract class FPlayers { - protected static FPlayers instance = getFPlayersImpl(); - - public static FPlayers getInstance() { - return instance; - } - - private static FPlayers getFPlayersImpl() { - switch (Conf.backEnd) { - case JSON: - return new JSONFPlayers(); - } - return null; - } - - public abstract void clean(); - - public abstract Collection getOnlinePlayers(); - - public abstract FPlayer getByPlayer(Player player); - - public abstract Collection getAllFPlayers(); - - public abstract void forceSave(); - - public abstract void forceSave(boolean sync); - - public abstract FPlayer getByOfflinePlayer(OfflinePlayer player); - - public abstract FPlayer getById(String string); - - public abstract void load(); -} +package com.massivecraft.factions; + +import com.massivecraft.factions.zcore.persist.json.JSONFPlayers; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; + +import java.util.Collection; + +public abstract class FPlayers { + protected static FPlayers instance = getFPlayersImpl(); + + public static FPlayers getInstance() { + return instance; + } + + private static FPlayers getFPlayersImpl() { + switch (Conf.backEnd) { + case JSON: + return new JSONFPlayers(); + } + return null; + } + + public abstract void clean(); + + public abstract Collection getOnlinePlayers(); + + public abstract FPlayer getByPlayer(Player player); + + public abstract Collection getAllFPlayers(); + + public abstract void forceSave(); + + public abstract void forceSave(boolean sync); + + public abstract FPlayer getByOfflinePlayer(OfflinePlayer player); + + public abstract FPlayer getById(String string); + + public abstract void load(); +} diff --git a/src/main/java/com/massivecraft/factions/Faction.java b/src/main/java/com/massivecraft/factions/Faction.java index be6412c6..5e97f012 100644 --- a/src/main/java/com/massivecraft/factions/Faction.java +++ b/src/main/java/com/massivecraft/factions/Faction.java @@ -21,327 +21,328 @@ import java.util.*; import java.util.concurrent.ConcurrentHashMap; public interface Faction extends EconomyParticipator { - HashMap> getAnnouncements(); + HashMap> getAnnouncements(); - ConcurrentHashMap getWarps(); + ConcurrentHashMap getWarps(); - LazyLocation getWarp(String name); + LazyLocation getWarp(String name); - void setWarp(String name, LazyLocation loc); + void setWarp(String name, LazyLocation loc); - boolean isWarp(String name); + boolean isWarp(String name); - boolean hasWarpPassword(String warp); + boolean hasWarpPassword(String warp); - boolean isWarpPassword(String warp, String password); + boolean isWarpPassword(String warp, String password); - void setWarpPassword(String warp, String password); + void setWarpPassword(String warp, String password); - boolean removeWarp(String name); + boolean removeWarp(String name); - void clearWarps(); + void clearWarps(); - int getMaxVaults(); + int getMaxVaults(); - void setMaxVaults(int value); + void setMaxVaults(int value); - void addAnnouncement(FPlayer fPlayer, String msg); + void addAnnouncement(FPlayer fPlayer, String msg); - void sendUnreadAnnouncements(FPlayer fPlayer); + void sendUnreadAnnouncements(FPlayer fPlayer); - void removeAnnouncements(FPlayer fPlayer); + void removeAnnouncements(FPlayer fPlayer); - Set getInvites(); + Set getInvites(); - String getFocused(); + String getFocused(); - void setFocused(String setFocused); + void setFocused(String setFocused); - String getId(); + String getId(); - void setId(String id); + void setId(String id); - void invite(FPlayer fplayer); + void invite(FPlayer fplayer); - void deinvite(FPlayer fplayer); + void deinvite(FPlayer fplayer); - void setUpgrade(Upgrade upgrade, int level); + void setUpgrade(Upgrade upgrade, int level); - int getUpgrade(Upgrade upgrade); + int getUpgrade(Upgrade upgrade); - boolean isInvited(FPlayer fplayer); + boolean isInvited(FPlayer fplayer); - void ban(FPlayer target, FPlayer banner); + void ban(FPlayer target, FPlayer banner); - void unban(FPlayer player); + void unban(FPlayer player); - boolean isBanned(FPlayer player); + boolean isBanned(FPlayer player); - Set getBannedPlayers(); + Set getBannedPlayers(); - HashMap getRulesMap(); + HashMap getRulesMap(); - void setRule(int index, String rule); + void setRule(int index, String rule); - void addRule(String rule); + void addRule(String rule); - void removeRule(int index); + void removeRule(int index); - void clearRules(); + void clearRules(); - Location getCheckpoint(); + Location getCheckpoint(); - void setCheckpoint(Location location); + void setCheckpoint(Location location); - void addTnt(int amt); + void addTnt(int amt); - void takeTnt(int amt); + void takeTnt(int amt); - Location getVault(); + Location getVault(); - void setVault(Location vaultLocation); + void setVault(Location vaultLocation); - Inventory getChestInventory(); + Inventory getChestInventory(); - void setChestSize(int chestSize); + void setChestSize(int chestSize); - void setBannerPattern(ItemStack banner); + void setBannerPattern(ItemStack banner); - ItemStack getBanner(); + ItemStack getBanner(); - int getTnt(); + int getTnt(); - String getRule(int index); + String getRule(int index); - boolean getOpen(); + boolean getOpen(); - void setOpen(boolean isOpen); + void setOpen(boolean isOpen); - boolean isPeaceful(); + boolean isPeaceful(); - void setPeaceful(boolean isPeaceful); + void setPeaceful(boolean isPeaceful); - boolean getPeacefulExplosionsEnabled(); + boolean getPeacefulExplosionsEnabled(); - void setPeacefulExplosionsEnabled(boolean val); + void setPeacefulExplosionsEnabled(boolean val); - boolean noExplosionsInTerritory(); + boolean noExplosionsInTerritory(); - boolean isPermanent(); + boolean isPermanent(); - void setPermanent(boolean isPermanent); + void setPermanent(boolean isPermanent); - String getTag(); + String getTag(); - void setTag(String str); + void setTag(String str); - String getTag(String prefix); + String getTag(String prefix); - String getTag(Faction otherFaction); + String getTag(Faction otherFaction); - String getTag(FPlayer otherFplayer); + String getTag(FPlayer otherFplayer); - String getComparisonTag(); + String getComparisonTag(); - String getDescription(); + String getDescription(); - void setDescription(String value); + void setDescription(String value); - boolean hasHome(); + boolean hasHome(); - Location getHome(); + Location getHome(); - void setHome(Location home); + void setHome(Location home); - long getFoundedDate(); + long getFoundedDate(); - void setFoundedDate(long newDate); + void setFoundedDate(long newDate); - void confirmValidHome(); + void confirmValidHome(); - String getAccountId(); + String getAccountId(); - Integer getPermanentPower(); + Integer getPermanentPower(); - void setPermanentPower(Integer permanentPower); + void setPermanentPower(Integer permanentPower); - boolean hasPermanentPower(); + boolean hasPermanentPower(); - double getPowerBoost(); + double getPowerBoost(); - void setPowerBoost(double powerBoost); + void setPowerBoost(double powerBoost); - boolean noPvPInTerritory(); + boolean noPvPInTerritory(); - boolean noMonstersInTerritory(); + boolean noMonstersInTerritory(); - boolean isNormal(); + boolean isNormal(); - @Deprecated - boolean isNone(); + @Deprecated + boolean isNone(); - boolean isWilderness(); + boolean isWilderness(); - boolean isSafeZone(); + boolean isSafeZone(); - boolean isWarZone(); + boolean isWarZone(); - boolean isPlayerFreeType(); + boolean isPlayerFreeType(); - boolean isPowerFrozen(); + boolean isPowerFrozen(); - void setLastDeath(long time); + void setLastDeath(long time); - int getKills(); + int getKills(); - int getDeaths(); + int getDeaths(); - Access getAccess(Permissable permissable, PermissableAction permissableAction); + Access getAccess(Permissable permissable, PermissableAction permissableAction); - Access getAccess(FPlayer player, PermissableAction permissableAction); + Access getAccess(FPlayer player, PermissableAction permissableAction); - void setPermission(Permissable permissable, PermissableAction permissableAction, Access access); + void setPermission(Permissable permissable, PermissableAction permissableAction, Access access); - void resetPerms(); - void setDefaultPerms(); + void resetPerms(); - void disband(Player disbander); + void setDefaultPerms(); - void disband(Player disbander, PlayerDisbandReason reason); + void disband(Player disbander); - // ------------------------------- - // Relation and relation colors - // ------------------------------- + void disband(Player disbander, PlayerDisbandReason reason); - Map> getPermissions(); + // ------------------------------- + // Relation and relation colors + // ------------------------------- - @Override - String describeTo(RelationParticipator that, boolean ucfirst); + Map> getPermissions(); - @Override - String describeTo(RelationParticipator that); + @Override + String describeTo(RelationParticipator that, boolean ucfirst); - @Override - Relation getRelationTo(RelationParticipator rp); + @Override + String describeTo(RelationParticipator that); - @Override - Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful); + @Override + Relation getRelationTo(RelationParticipator rp); - @Override - ChatColor getColorTo(RelationParticipator rp); + @Override + Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful); - Relation getRelationWish(Faction otherFaction); + @Override + ChatColor getColorTo(RelationParticipator rp); - void setRelationWish(Faction otherFaction, Relation relation); + Relation getRelationWish(Faction otherFaction); - int getRelationCount(Relation relation); + void setRelationWish(Faction otherFaction, Relation relation); - // ----------------------------------------------// - // Power - // ----------------------------------------------// - double getPower(); + int getRelationCount(Relation relation); - double getPowerMax(); + // ----------------------------------------------// + // Power + // ----------------------------------------------// + double getPower(); - int getPowerRounded(); + double getPowerMax(); - int getPowerMaxRounded(); + int getPowerRounded(); - int getLandRounded(); + int getPowerMaxRounded(); - int getLandRoundedInWorld(String worldName); + int getLandRounded(); - // ------------------------------- - // FPlayers - // ------------------------------- + int getLandRoundedInWorld(String worldName); - boolean hasLandInflation(); + // ------------------------------- + // FPlayers + // ------------------------------- - // maintain the reference list of FPlayers in this faction - void refreshFPlayers(); + boolean hasLandInflation(); - boolean addFPlayer(FPlayer fplayer); + // maintain the reference list of FPlayers in this faction + void refreshFPlayers(); - boolean removeFPlayer(FPlayer fplayer); + boolean addFPlayer(FPlayer fplayer); - int getSize(); + boolean removeFPlayer(FPlayer fplayer); - Set getFPlayers(); + int getSize(); - Set getFPlayersWhereOnline(boolean online); + Set getFPlayers(); - Set getFPlayersWhereOnline(boolean online, FPlayer viewer); + Set getFPlayersWhereOnline(boolean online); - FPlayer getFPlayerAdmin(); + Set getFPlayersWhereOnline(boolean online, FPlayer viewer); - FPlayer getFPlayerLeader(); + FPlayer getFPlayerAdmin(); - ArrayList getFPlayersWhereRole(Role role); + FPlayer getFPlayerLeader(); - ArrayList getOnlinePlayers(); + ArrayList getFPlayersWhereRole(Role role); - // slightly faster check than getOnlinePlayers() if you just want to see if - // there are any players online - boolean hasPlayersOnline(); + ArrayList getOnlinePlayers(); - void memberLoggedOff(); + // slightly faster check than getOnlinePlayers() if you just want to see if + // there are any players online + boolean hasPlayersOnline(); - // used when current leader is about to be removed from the faction; - // promotes new leader, or disbands faction if no other members left - void promoteNewLeader(); + void memberLoggedOff(); - void promoteNewLeader(boolean autoLeave); + // used when current leader is about to be removed from the faction; + // promotes new leader, or disbands faction if no other members left + void promoteNewLeader(); - Role getDefaultRole(); + void promoteNewLeader(boolean autoLeave); - void setDefaultRole(Role role); + Role getDefaultRole(); - // ----------------------------------------------// - // Messages - // ----------------------------------------------// - void msg(String message, Object... args); + void setDefaultRole(Role role); - void sendMessage(String message); + // ----------------------------------------------// + // Messages + // ----------------------------------------------// + void msg(String message, Object... args); - // ----------------------------------------------// - // Ownership of specific claims - // ----------------------------------------------// + void sendMessage(String message); - void sendMessage(List messages); + // ----------------------------------------------// + // Ownership of specific claims + // ----------------------------------------------// - Map> getClaimOwnership(); + void sendMessage(List messages); - void clearAllClaimOwnership(); + Map> getClaimOwnership(); - void clearClaimOwnership(FLocation loc); + void clearAllClaimOwnership(); - void clearClaimOwnership(FPlayer player); + void clearClaimOwnership(FLocation loc); - int getCountOfClaimsWithOwners(); + void clearClaimOwnership(FPlayer player); - boolean doesLocationHaveOwnersSet(FLocation loc); + int getCountOfClaimsWithOwners(); - boolean isPlayerInOwnerList(FPlayer player, FLocation loc); + boolean doesLocationHaveOwnersSet(FLocation loc); - void setPlayerAsOwner(FPlayer player, FLocation loc); + boolean isPlayerInOwnerList(FPlayer player, FLocation loc); - void removePlayerAsOwner(FPlayer player, FLocation loc); + void setPlayerAsOwner(FPlayer player, FLocation loc); - Set getOwnerList(FLocation loc); + void removePlayerAsOwner(FPlayer player, FLocation loc); - String getOwnerListString(FLocation loc); + Set getOwnerList(FLocation loc); - boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc); + String getOwnerListString(FLocation loc); - // ----------------------------------------------// - // Persistance and entity management - // ----------------------------------------------// - void remove(); + boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc); - Set getAllClaims(); + // ----------------------------------------------// + // Persistance and entity management + // ----------------------------------------------// + void remove(); - String getPaypal(); + Set getAllClaims(); - void paypalSet(String paypal); + String getPaypal(); + + void paypalSet(String paypal); } diff --git a/src/main/java/com/massivecraft/factions/Factions.java b/src/main/java/com/massivecraft/factions/Factions.java index 285da06c..b573c3cf 100644 --- a/src/main/java/com/massivecraft/factions/Factions.java +++ b/src/main/java/com/massivecraft/factions/Factions.java @@ -1,55 +1,55 @@ -package com.massivecraft.factions; - -import com.massivecraft.factions.zcore.persist.json.JSONFactions; - -import java.util.ArrayList; -import java.util.Set; - -public abstract class Factions { - protected static Factions instance = getFactionsImpl(); - - public static Factions getInstance() { - return instance; - } - - private static Factions getFactionsImpl() { - switch (Conf.backEnd) { - case JSON: - return new JSONFactions(); - } - return null; - } - - public abstract Faction getFactionById(String id); - - public abstract Faction getByTag(String str); - - public abstract Faction getBestTagMatch(String start); - - public abstract boolean isTagTaken(String str); - - public abstract boolean isValidFactionId(String id); - - public abstract Faction createFaction(); - - public abstract void removeFaction(String id); - - public abstract Set getFactionTags(); - - public abstract ArrayList getAllFactions(); - - @Deprecated - public abstract Faction getNone(); - - public abstract Faction getWilderness(); - - public abstract Faction getSafeZone(); - - public abstract Faction getWarZone(); - - public abstract void forceSave(); - - public abstract void forceSave(boolean sync); - - public abstract void load(); -} +package com.massivecraft.factions; + +import com.massivecraft.factions.zcore.persist.json.JSONFactions; + +import java.util.ArrayList; +import java.util.Set; + +public abstract class Factions { + protected static Factions instance = getFactionsImpl(); + + public static Factions getInstance() { + return instance; + } + + private static Factions getFactionsImpl() { + switch (Conf.backEnd) { + case JSON: + return new JSONFactions(); + } + return null; + } + + public abstract Faction getFactionById(String id); + + public abstract Faction getByTag(String str); + + public abstract Faction getBestTagMatch(String start); + + public abstract boolean isTagTaken(String str); + + public abstract boolean isValidFactionId(String id); + + public abstract Faction createFaction(); + + public abstract void removeFaction(String id); + + public abstract Set getFactionTags(); + + public abstract ArrayList getAllFactions(); + + @Deprecated + public abstract Faction getNone(); + + public abstract Faction getWilderness(); + + public abstract Faction getSafeZone(); + + public abstract Faction getWarZone(); + + public abstract void forceSave(); + + public abstract void forceSave(boolean sync); + + public abstract void load(); +} diff --git a/src/main/java/com/massivecraft/factions/MassiveStats.java b/src/main/java/com/massivecraft/factions/MassiveStats.java index babb89a8..a1f01e56 100644 --- a/src/main/java/com/massivecraft/factions/MassiveStats.java +++ b/src/main/java/com/massivecraft/factions/MassiveStats.java @@ -34,464 +34,464 @@ import java.net.URL; @SuppressWarnings("all") public class MassiveStats implements Listener { - /* START: MASSIVESTATS SETTINGS */ - public static final int CLIENT_VERSION = 0; // v3.0 - public static final String API_URL = "https://report.massivestats.com/v2/"; + /* START: MASSIVESTATS SETTINGS */ + public static final int CLIENT_VERSION = 0; // v3.0 + public static final String API_URL = "https://report.massivestats.com/v2/"; - public static final String MASSIVE_UPDATE_PERMISSION = "massivestats.update"; - /* END: MASSIVESTATS SETTINGS */ - private final JavaPlugin plugin; - private MassiveStatsUpdateTask task = null; - private int pingInterval; - private MassiveStatsDataResponse lastResponse; - private boolean listenerDisabled; - private Class jsonElement; - private Class jsonParser; - private Class jsonObject; - private Class jsonPrimitive; + public static final String MASSIVE_UPDATE_PERMISSION = "massivestats.update"; + /* END: MASSIVESTATS SETTINGS */ + private final JavaPlugin plugin; + private MassiveStatsUpdateTask task = null; + private int pingInterval; + private MassiveStatsDataResponse lastResponse; + private boolean listenerDisabled; + private Class jsonElement; + private Class jsonParser; + private Class jsonObject; + private Class jsonPrimitive; - /** - * @param plugin The plugin you wish to collect data for. - * @author Sam Jakob Harker - */ - public MassiveStats(JavaPlugin plugin) { - this(plugin, 900); // default value: 900 seconds (= 15 minutes) - } + /** + * @param plugin The plugin you wish to collect data for. + * @author Sam Jakob Harker + */ + public MassiveStats(JavaPlugin plugin) { + this(plugin, 900); // default value: 900 seconds (= 15 minutes) + } - /** - * @param plugin The plugin you wish to collect data for. - * @param pingInterval Duration between requests. - * @author Sam Jakob Harker - */ - public MassiveStats(JavaPlugin plugin, int pingInterval) { - try { - jsonElement = Class.forName("com.google.gson.JsonElement"); - jsonParser = Class.forName("com.google.gson.JsonParser"); - jsonObject = Class.forName("com.google.gson.JsonObject"); - jsonPrimitive = Class.forName("com.google.gson.JsonPrimitive"); - } catch (ClassNotFoundException ex) { - // Gson not included in classpath (so use NMS version) - try { - jsonElement = Class.forName("net.minecraft.util.com.google.gson.JsonElement"); - jsonParser = Class.forName("net.minecraft.util.com.google.gson.JsonParser"); - jsonObject = Class.forName("net.minecraft.util.com.google.gson.JsonObject"); - jsonPrimitive = Class.forName("net.minecraft.util.com.google.gson.JsonPrimitive"); - } catch (ClassNotFoundException ignored) { - Bukkit.getLogger().severe("MassiveStats could not find an instance/version of Gson to use."); - this.plugin = null; - return; - } - } + /** + * @param plugin The plugin you wish to collect data for. + * @param pingInterval Duration between requests. + * @author Sam Jakob Harker + */ + public MassiveStats(JavaPlugin plugin, int pingInterval) { + try { + jsonElement = Class.forName("com.google.gson.JsonElement"); + jsonParser = Class.forName("com.google.gson.JsonParser"); + jsonObject = Class.forName("com.google.gson.JsonObject"); + jsonPrimitive = Class.forName("com.google.gson.JsonPrimitive"); + } catch (ClassNotFoundException ex) { + // Gson not included in classpath (so use NMS version) + try { + jsonElement = Class.forName("net.minecraft.util.com.google.gson.JsonElement"); + jsonParser = Class.forName("net.minecraft.util.com.google.gson.JsonParser"); + jsonObject = Class.forName("net.minecraft.util.com.google.gson.JsonObject"); + jsonPrimitive = Class.forName("net.minecraft.util.com.google.gson.JsonPrimitive"); + } catch (ClassNotFoundException ignored) { + Bukkit.getLogger().severe("MassiveStats could not find an instance/version of Gson to use."); + this.plugin = null; + return; + } + } - // Ensure the pingInterval that is set is reasonable. - if (pingInterval < 10 || pingInterval > 86400) { - pingInterval = 900; - } + // Ensure the pingInterval that is set is reasonable. + if (pingInterval < 10 || pingInterval > 86400) { + pingInterval = 900; + } - // Ensure that a plugin instance has been provided. - if (plugin == null) { - throw new IllegalArgumentException("You must provide a plugin for MassiveStats to collect data for!"); - } + // Ensure that a plugin instance has been provided. + if (plugin == null) { + throw new IllegalArgumentException("You must provide a plugin for MassiveStats to collect data for!"); + } - // Set the ping interval. - this.pingInterval = pingInterval; - // Set the plugin reference. - this.plugin = plugin; - // and start sending data to the MassiveStats server immediately. - start(); + // Set the ping interval. + this.pingInterval = pingInterval; + // Set the plugin reference. + this.plugin = plugin; + // and start sending data to the MassiveStats server immediately. + start(); - // Register join/leave events for the plugin - Bukkit.getServer().getPluginManager().registerEvents(this, plugin); - } + // Register join/leave events for the plugin + Bukkit.getServer().getPluginManager().registerEvents(this, plugin); + } - /** - * Gets whether or not the built-in MassiveStats {@link org.bukkit.event.player.PlayerJoinEvent} listener is enabled. - * - * @return Whether or not the MassiveStats listener is enabled. - */ - public boolean isListenerDisabled() { - return listenerDisabled; - } + /** + * Gets whether or not the built-in MassiveStats {@link org.bukkit.event.player.PlayerJoinEvent} listener is enabled. + * + * @return Whether or not the MassiveStats listener is enabled. + */ + public boolean isListenerDisabled() { + return listenerDisabled; + } - /** - * Sets whether or not the built-in MassiveStats {@link org.bukkit.event.player.PlayerJoinEvent} listener is enabled. - * - * @param listenerDisabled Whether or not the MassiveStats listener is enabled. - */ - public void setListenerDisabled(boolean listenerDisabled) { - this.listenerDisabled = listenerDisabled; - } + /** + * Sets whether or not the built-in MassiveStats {@link org.bukkit.event.player.PlayerJoinEvent} listener is enabled. + * + * @param listenerDisabled Whether or not the MassiveStats listener is enabled. + */ + public void setListenerDisabled(boolean listenerDisabled) { + this.listenerDisabled = listenerDisabled; + } - /** - * Start the MassiveStats reporting timer. - * If the timer is already running, this method will do nothing. - * - * @author Sam Jakob Harker - */ - public void start() { - if (this.plugin == null) { - Bukkit.getLogger().severe("MassiveStats could not find an instance/version of Gson to use and thus cannot start."); - return; - } + /** + * Start the MassiveStats reporting timer. + * If the timer is already running, this method will do nothing. + * + * @author Sam Jakob Harker + */ + public void start() { + if (this.plugin == null) { + Bukkit.getLogger().severe("MassiveStats could not find an instance/version of Gson to use and thus cannot start."); + return; + } - if (task == null) { - // If the API endpoint URL is invalid, don't start a new task to prevent the user from being spammed. - try { - new URL(MassiveStats.API_URL); - } catch (MalformedURLException ex) { - getPlugin() - .getLogger().warning("You have specified an invalid API endpoint for MassiveStats."); - return; - } + if (task == null) { + // If the API endpoint URL is invalid, don't start a new task to prevent the user from being spammed. + try { + new URL(MassiveStats.API_URL); + } catch (MalformedURLException ex) { + getPlugin() + .getLogger().warning("You have specified an invalid API endpoint for MassiveStats."); + return; + } - task = new MassiveStatsUpdateTask(this); - task.runTaskTimerAsynchronously(plugin, 0L, pingInterval * 20L); - } - } + task = new MassiveStatsUpdateTask(this); + task.runTaskTimerAsynchronously(plugin, 0L, pingInterval * 20L); + } + } - /** - * Stop the MassiveStats reporting timer. - * Requests will no longer be sent to the server - or until {@link #start()} is invoked. - * - * @author Sam Jakob Harker - */ - public void stop() { - if (task == null) { - return; - } + /** + * Stop the MassiveStats reporting timer. + * Requests will no longer be sent to the server - or until {@link #start()} is invoked. + * + * @author Sam Jakob Harker + */ + public void stop() { + if (task == null) { + return; + } - task.cancel(); - task = null; - } + task.cancel(); + task = null; + } - /** - * Returns the duration, in seconds, that MassiveStats will wait before sending another request to the server. - * - * @return Duration between requests. - * @author Sam Jakob Harker - */ - public int getPingInterval() { - return pingInterval; - } + /** + * Returns the duration, in seconds, that MassiveStats will wait before sending another request to the server. + * + * @return Duration between requests. + * @author Sam Jakob Harker + */ + public int getPingInterval() { + return pingInterval; + } - /** - * Sets the duration, in seconds, that MassiveStats should wait before sending another request to the server. - * - * @param pingInterval Duration between requests. - * @author Sam Jakob Harker - */ - public void setPingInterval(int pingInterval) { - this.pingInterval = pingInterval; + /** + * Sets the duration, in seconds, that MassiveStats should wait before sending another request to the server. + * + * @param pingInterval Duration between requests. + * @author Sam Jakob Harker + */ + public void setPingInterval(int pingInterval) { + this.pingInterval = pingInterval; - stop(); - start(); - } + stop(); + start(); + } - /** - * Returns the plugin that this MassiveStats instance is collecting data for. - * - * @return MassiveStats instance plugin. - * @author Sam Jakob Harker - */ - public JavaPlugin getPlugin() { - return plugin; - } + /** + * Returns the plugin that this MassiveStats instance is collecting data for. + * + * @return MassiveStats instance plugin. + * @author Sam Jakob Harker + */ + public JavaPlugin getPlugin() { + return plugin; + } - /** - * Returns the contents of the last response from the MassiveStats server. - * - * @return MassiveStats server response. - * @author Sam Jakob Harker - */ - public MassiveStatsDataResponse getLastResponse() { - return lastResponse; - } + /** + * Returns the contents of the last response from the MassiveStats server. + * + * @return MassiveStats server response. + * @author Sam Jakob Harker + */ + public MassiveStatsDataResponse getLastResponse() { + return lastResponse; + } - void setLastResponse(MassiveStatsDataResponse lastResponse) { - this.lastResponse = lastResponse; - } + void setLastResponse(MassiveStatsDataResponse lastResponse) { + this.lastResponse = lastResponse; + } - @EventHandler - public void onPlayerJoin(PlayerJoinEvent event) { - // Ensure the listener should be active - if (lastResponse == null || listenerDisabled) { - return; - } + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + // Ensure the listener should be active + if (lastResponse == null || listenerDisabled) { + return; + } - // Of course, only notify the user if the plugin is not up to date. - if (lastResponse.isUpToDate()) { - return; - } + // Of course, only notify the user if the plugin is not up to date. + if (lastResponse.isUpToDate()) { + return; + } - // and only notify operators - or players with the correct permission. - if (!event.getPlayer().isOp() && !event.getPlayer().hasPermission(MassiveStats.MASSIVE_UPDATE_PERMISSION)) { - return; - } + // and only notify operators - or players with the correct permission. + if (!event.getPlayer().isOp() && !event.getPlayer().hasPermission(MassiveStats.MASSIVE_UPDATE_PERMISSION)) { + return; + } - event.getPlayer().sendMessage(lastResponse.getUpdateMessage()); - } + event.getPlayer().sendMessage(lastResponse.getUpdateMessage()); + } - Class getJsonElement() { - return jsonElement; - } + Class getJsonElement() { + return jsonElement; + } - Class getJsonParser() { - return jsonParser; - } + Class getJsonParser() { + return jsonParser; + } - Class getJsonObject() { - return jsonObject; - } + Class getJsonObject() { + return jsonObject; + } - Class getJsonPrimitive() { - return jsonPrimitive; - } + Class getJsonPrimitive() { + return jsonPrimitive; + } } class MassiveStatsUpdateTask extends BukkitRunnable { - private final MassiveStats instance; + private final MassiveStats instance; - MassiveStatsUpdateTask(MassiveStats requester) { - instance = requester; - } + MassiveStatsUpdateTask(MassiveStats requester) { + instance = requester; + } - @Override - @SuppressWarnings("all") - public void run() { - try { - // Generate the request payload and serialize it as JSON. - String payload = new MassiveStatsDataRequest(instance).serialize(); + @Override + @SuppressWarnings("all") + public void run() { + try { + // Generate the request payload and serialize it as JSON. + String payload = new MassiveStatsDataRequest(instance).serialize(); - // Then create a new HttpsUrlConnection to the API server and open it. - HttpsURLConnection connection = (HttpsURLConnection) new URL(MassiveStats.API_URL).openConnection(); + // Then create a new HttpsUrlConnection to the API server and open it. + HttpsURLConnection connection = (HttpsURLConnection) new URL(MassiveStats.API_URL).openConnection(); - // Ensure that we don't hang the server with our 'dang shenanigans'. - connection.setConnectTimeout(2500); - connection.setReadTimeout(3500); + // Ensure that we don't hang the server with our 'dang shenanigans'. + connection.setConnectTimeout(2500); + connection.setReadTimeout(3500); - // Set the all-important request headers before we begin POSTing... - connection.setRequestMethod("POST"); - connection.setRequestProperty("Accept", "application/json"); - connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); - connection.setRequestProperty("User-Agent", "Massive/" + MassiveStats.CLIENT_VERSION); + // Set the all-important request headers before we begin POSTing... + connection.setRequestMethod("POST"); + connection.setRequestProperty("Accept", "application/json"); + connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); + connection.setRequestProperty("User-Agent", "Massive/" + MassiveStats.CLIENT_VERSION); - // Open the output stream, write the payload, and then close the stream. - connection.setDoOutput(true); - DataOutputStream output = new DataOutputStream(connection.getOutputStream()); - output.writeBytes(payload); - output.flush(); - output.close(); + // Open the output stream, write the payload, and then close the stream. + connection.setDoOutput(true); + DataOutputStream output = new DataOutputStream(connection.getOutputStream()); + output.writeBytes(payload); + output.flush(); + output.close(); - // Ensure that the server was happy with our data. - int responseCode = connection.getResponseCode(); - if (responseCode != 200) { - throw new IOException(); - } + // Ensure that the server was happy with our data. + int responseCode = connection.getResponseCode(); + if (responseCode != 200) { + throw new IOException(); + } - // Now, read the server's response to our payload... - BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); - StringBuilder response = new StringBuilder(); + // Now, read the server's response to our payload... + BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder response = new StringBuilder(); - // ...line by line. - String line; - while ((line = input.readLine()) != null) { - response.append(line); - } - input.close(); + // ...line by line. + String line; + while ((line = input.readLine()) != null) { + response.append(line); + } + input.close(); - // Now, we parse the JSON object. - try { - if (response.toString().contains("ERR_DATA_MISSING")) { - Bukkit.getLogger().severe("MassiveStats has encountered an error for the following plugin: " - + instance.getPlugin().getName()); - instance.stop(); - return; - } + // Now, we parse the JSON object. + try { + if (response.toString().contains("ERR_DATA_MISSING")) { + Bukkit.getLogger().severe("MassiveStats has encountered an error for the following plugin: " + + instance.getPlugin().getName()); + instance.stop(); + return; + } - Object parser = instance.getJsonParser().newInstance(); + Object parser = instance.getJsonParser().newInstance(); - // JsonElement - Object serverResponseRaw = - parser.getClass().getMethod("parse", String.class).invoke(parser, response.toString()); + // JsonElement + Object serverResponseRaw = + parser.getClass().getMethod("parse", String.class).invoke(parser, response.toString()); - // JsonObject - Object serverResponse = serverResponseRaw.getClass().getMethod("getAsJsonObject", null) - .invoke(serverResponseRaw, null); + // JsonObject + Object serverResponse = serverResponseRaw.getClass().getMethod("getAsJsonObject", null) + .invoke(serverResponseRaw, null); - Method serverResponseGet = instance.getJsonObject().getMethod("get", String.class); + Method serverResponseGet = instance.getJsonObject().getMethod("get", String.class); - Method getAsBoolean = - instance.getJsonPrimitive().getMethod("getAsBoolean", null); - Method getAsString = - instance.getJsonPrimitive().getMethod("getAsString", null); + Method getAsBoolean = + instance.getJsonPrimitive().getMethod("getAsBoolean", null); + Method getAsString = + instance.getJsonPrimitive().getMethod("getAsString", null); - if (serverResponseGet.invoke(serverResponse, "upToDate") == null) { - Bukkit.getLogger().severe("MassiveStats has encountered an error for the following plugin: " - + instance.getPlugin().getName()); - instance.stop(); - return; - } + if (serverResponseGet.invoke(serverResponse, "upToDate") == null) { + Bukkit.getLogger().severe("MassiveStats has encountered an error for the following plugin: " + + instance.getPlugin().getName()); + instance.stop(); + return; + } - if (serverResponseGet.invoke(serverResponse, "notice") != null) { - Bukkit.getLogger().severe( - (String) getAsString.invoke(serverResponseGet.invoke(serverResponse, "notice")) - ); - instance.stop(); - return; - } + if (serverResponseGet.invoke(serverResponse, "notice") != null) { + Bukkit.getLogger().severe( + (String) getAsString.invoke(serverResponseGet.invoke(serverResponse, "notice")) + ); + instance.stop(); + return; + } - boolean upToDate = (boolean) getAsBoolean.invoke(serverResponseGet.invoke(serverResponse, "upToDate"), null); - String latestVersion = (String) getAsString.invoke(serverResponseGet.invoke(serverResponse, "latestVersion"), null); - String updateMessage = ChatColor.translateAlternateColorCodes( - '&', (String) getAsString.invoke(serverResponseGet.invoke(serverResponse, "updateMessage"), null) - ); + boolean upToDate = (boolean) getAsBoolean.invoke(serverResponseGet.invoke(serverResponse, "upToDate"), null); + String latestVersion = (String) getAsString.invoke(serverResponseGet.invoke(serverResponse, "latestVersion"), null); + String updateMessage = ChatColor.translateAlternateColorCodes( + '&', (String) getAsString.invoke(serverResponseGet.invoke(serverResponse, "updateMessage"), null) + ); - instance.setLastResponse(new MassiveStatsDataResponse( - upToDate, latestVersion, updateMessage - )); + instance.setLastResponse(new MassiveStatsDataResponse( + upToDate, latestVersion, updateMessage + )); - } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { - instance.getPlugin() - .getLogger().warning("MassiveStats returned an invalid response for this plugin."); - } + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + instance.getPlugin() + .getLogger().warning("MassiveStats returned an invalid response for this plugin."); + } - // Finally, call an event to mark the update. - } catch (MalformedURLException ex) { - instance.getPlugin() - .getLogger().warning("You have specified an invalid API endpoint for MassiveStats."); - } catch (IOException ex) { - instance.getPlugin() - .getLogger().warning("MassiveStats was unable to communicate with its API endpoint."); - } - } + // Finally, call an event to mark the update. + } catch (MalformedURLException ex) { + instance.getPlugin() + .getLogger().warning("You have specified an invalid API endpoint for MassiveStats."); + } catch (IOException ex) { + instance.getPlugin() + .getLogger().warning("MassiveStats was unable to communicate with its API endpoint."); + } + } } class MassiveStatsDataRequest { - private Object jsonObject; + private Object jsonObject; - MassiveStatsDataRequest(MassiveStats requester) { - try { - jsonObject = requester.getJsonObject().newInstance(); + MassiveStatsDataRequest(MassiveStats requester) { + try { + jsonObject = requester.getJsonObject().newInstance(); - Method add = - requester.getJsonObject().newInstance().getClass().getMethod("add", String.class, requester.getJsonElement()); - Method addPropertyString = - requester.getJsonObject().newInstance().getClass().getMethod("addProperty", String.class, String.class); - Method addPropertyNumber = - requester.getJsonObject().newInstance().getClass().getMethod("addProperty", String.class, Number.class); - Method addPropertyBoolean = - requester.getJsonObject().newInstance().getClass().getMethod("addProperty", String.class, Boolean.class); + Method add = + requester.getJsonObject().newInstance().getClass().getMethod("add", String.class, requester.getJsonElement()); + Method addPropertyString = + requester.getJsonObject().newInstance().getClass().getMethod("addProperty", String.class, String.class); + Method addPropertyNumber = + requester.getJsonObject().newInstance().getClass().getMethod("addProperty", String.class, Number.class); + Method addPropertyBoolean = + requester.getJsonObject().newInstance().getClass().getMethod("addProperty", String.class, Boolean.class); - addPropertyNumber.invoke(jsonObject, "now", System.currentTimeMillis()); + addPropertyNumber.invoke(jsonObject, "now", System.currentTimeMillis()); - /* PLUGIN DATA */ - Object pluginObject = jsonObject.getClass().newInstance(); - addPropertyString.invoke(pluginObject, "name", requester.getPlugin().getDescription().getName()); - addPropertyString.invoke(pluginObject, "version", requester.getPlugin().getDescription().getVersion()); - add.invoke(jsonObject, "plugin", pluginObject); + /* PLUGIN DATA */ + Object pluginObject = jsonObject.getClass().newInstance(); + addPropertyString.invoke(pluginObject, "name", requester.getPlugin().getDescription().getName()); + addPropertyString.invoke(pluginObject, "version", requester.getPlugin().getDescription().getVersion()); + add.invoke(jsonObject, "plugin", pluginObject); - /* SERVER DATA */ - Object minecraftServerObject = jsonObject.getClass().newInstance(); - addPropertyNumber.invoke(minecraftServerObject, "players", Bukkit.getServer().getOnlinePlayers().size()); - addPropertyBoolean.invoke(minecraftServerObject, "onlineMode", Bukkit.getServer().getOnlineMode()); - addPropertyString.invoke(minecraftServerObject, "version", Bukkit.getServer().getVersion()); + /* SERVER DATA */ + Object minecraftServerObject = jsonObject.getClass().newInstance(); + addPropertyNumber.invoke(minecraftServerObject, "players", Bukkit.getServer().getOnlinePlayers().size()); + addPropertyBoolean.invoke(minecraftServerObject, "onlineMode", Bukkit.getServer().getOnlineMode()); + addPropertyString.invoke(minecraftServerObject, "version", Bukkit.getServer().getVersion()); - Object javaServerObject = jsonObject.getClass().newInstance(); - addPropertyString.invoke(javaServerObject, "version", System.getProperty("java.version")); + Object javaServerObject = jsonObject.getClass().newInstance(); + addPropertyString.invoke(javaServerObject, "version", System.getProperty("java.version")); - Object osServerObject = jsonObject.getClass().newInstance(); - addPropertyString.invoke(osServerObject, "name", System.getProperty("os.name")); - addPropertyString.invoke(osServerObject, "arch", System.getProperty("os.arch")); - addPropertyString.invoke(osServerObject, "version", System.getProperty("os.version")); + Object osServerObject = jsonObject.getClass().newInstance(); + addPropertyString.invoke(osServerObject, "name", System.getProperty("os.name")); + addPropertyString.invoke(osServerObject, "arch", System.getProperty("os.arch")); + addPropertyString.invoke(osServerObject, "version", System.getProperty("os.version")); - Object hardwareServerObject = jsonObject.getClass().newInstance(); - addPropertyNumber.invoke(hardwareServerObject, "cores", Runtime.getRuntime().availableProcessors()); + Object hardwareServerObject = jsonObject.getClass().newInstance(); + addPropertyNumber.invoke(hardwareServerObject, "cores", Runtime.getRuntime().availableProcessors()); - Object serverObject = jsonObject.getClass().newInstance(); - add.invoke(serverObject, "minecraft", minecraftServerObject); - add.invoke(serverObject, "java", javaServerObject); - add.invoke(serverObject, "os", osServerObject); - add.invoke(serverObject, "hardware", hardwareServerObject); + Object serverObject = jsonObject.getClass().newInstance(); + add.invoke(serverObject, "minecraft", minecraftServerObject); + add.invoke(serverObject, "java", javaServerObject); + add.invoke(serverObject, "os", osServerObject); + add.invoke(serverObject, "hardware", hardwareServerObject); - add.invoke(jsonObject, "server", serverObject); + add.invoke(jsonObject, "server", serverObject); - /* MASSIVE DATA */ - Object massiveObject = jsonObject.getClass().newInstance(); - addPropertyNumber.invoke(massiveObject, "version", MassiveStats.CLIENT_VERSION); - addPropertyNumber.invoke(massiveObject, "pingInterval", requester.getPingInterval()); + /* MASSIVE DATA */ + Object massiveObject = jsonObject.getClass().newInstance(); + addPropertyNumber.invoke(massiveObject, "version", MassiveStats.CLIENT_VERSION); + addPropertyNumber.invoke(massiveObject, "pingInterval", requester.getPingInterval()); - //object.add("Massive", massiveObject); - add.invoke(jsonObject, "Massive", massiveObject); - } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { - e.printStackTrace(); - } - } + //object.add("Massive", massiveObject); + add.invoke(jsonObject, "Massive", massiveObject); + } catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) { + e.printStackTrace(); + } + } - @SuppressWarnings("all") - public String serialize() { - //return object.toString(); - try { - Method toString = jsonObject.getClass().getMethod("toString", null); - return (String) toString.invoke(jsonObject); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - e.printStackTrace(); - } + @SuppressWarnings("all") + public String serialize() { + //return object.toString(); + try { + Method toString = jsonObject.getClass().getMethod("toString", null); + return (String) toString.invoke(jsonObject); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + e.printStackTrace(); + } - return null; - } + return null; + } } final class MassiveStatsDataResponse { - private final boolean isUpToDate; - private final String newVersion; - private final String updateMessage; + private final boolean isUpToDate; + private final String newVersion; + private final String updateMessage; - MassiveStatsDataResponse(boolean isUpToDate, String newVersion, String updateMessage) { - this.isUpToDate = isUpToDate; + MassiveStatsDataResponse(boolean isUpToDate, String newVersion, String updateMessage) { + this.isUpToDate = isUpToDate; - if (!isUpToDate) { - this.newVersion = newVersion; - this.updateMessage = updateMessage; - return; - } + if (!isUpToDate) { + this.newVersion = newVersion; + this.updateMessage = updateMessage; + return; + } - this.newVersion = null; - this.updateMessage = null; - } + this.newVersion = null; + this.updateMessage = null; + } - /** - * Indicates whether or not this version of the plugin is the latest. - * True = This is the latest version of the plugin. - * False = There is an update available. - * - * @return Whether or not there is an update available. - */ - public boolean isUpToDate() { - return isUpToDate; - } + /** + * Indicates whether or not this version of the plugin is the latest. + * True = This is the latest version of the plugin. + * False = There is an update available. + * + * @return Whether or not there is an update available. + */ + public boolean isUpToDate() { + return isUpToDate; + } - /** - * Gets the name of the latest version. If this is the latest version, it returns null. - * - * @return The name of the latest version. - */ - public String getLatestVersion() { - return newVersion; - } + /** + * Gets the name of the latest version. If this is the latest version, it returns null. + * + * @return The name of the latest version. + */ + public String getLatestVersion() { + return newVersion; + } - /** - * Gets the message to display, convincing the user to update to the new version of the plugin. - * - * @return The update message to display. - */ - public String getUpdateMessage() { - return updateMessage; - } + /** + * Gets the message to display, convincing the user to update to the new version of the plugin. + * + * @return The update message to display. + */ + public String getUpdateMessage() { + return updateMessage; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/SavageFactions.java b/src/main/java/com/massivecraft/factions/SavageFactions.java index c580400f..bb7f7e2e 100644 --- a/src/main/java/com/massivecraft/factions/SavageFactions.java +++ b/src/main/java/com/massivecraft/factions/SavageFactions.java @@ -52,705 +52,705 @@ import java.util.stream.Collectors; public class SavageFactions extends MPlugin { - // Our single plugin instance. - // Single 4 life. - public static SavageFactions plugin; - public static Permission perms = null; - // Persistence related - public static ArrayList playersFlying = new ArrayList(); - public Essentials ess; - public boolean PlaceholderApi; - // Commands - public FCmdRoot cmdBase; - public CmdAutoHelp cmdAutoHelp; - public boolean mc17 = false; - public boolean mc18 = false; - public boolean mc113 = false; - public boolean useNonPacketParticles = false; - public boolean factionsFlight = false; - //multiversion material fields - public Material SUGAR_CANE_BLOCK, BANNER, CROPS, REDSTONE_LAMP_ON, - STAINED_GLASS, STATIONARY_WATER, STAINED_CLAY, WOOD_BUTTON, - SOIL, MOB_SPANWER, THIN_GLASS, IRON_FENCE, NETHER_FENCE, FENCE, - WOODEN_DOOR, TRAP_DOOR, FENCE_GATE, BURNING_FURNACE, DIODE_BLOCK_OFF, - DIODE_BLOCK_ON, ENCHANTMENT_TABLE, FIREBALL; - SkriptAddon skriptAddon; - private boolean locked = false; - private Integer AutoLeaveTask = null; - private boolean hookedPlayervaults; - private ClipPlaceholderAPIManager clipPlaceholderAPIManager; - private boolean mvdwPlaceholderAPIManager = false; - private Listener[] eventsListener; - - public SavageFactions() { - plugin = this; - } - - public boolean getLocked() { - return this.locked; - } - - public void setLocked(boolean val) { - this.locked = val; - this.setAutoSave(val); - } - - public void playSoundForAll(String sound) { - for (Player pl : Bukkit.getOnlinePlayers()) { - playSound(pl, sound); - } - } - - public void playSoundForAll(List sounds) { - for (Player pl : Bukkit.getOnlinePlayers()) { - playSound(pl, sounds); - } - } - - public void playSound(Player p, List sounds) { - for (String sound : sounds) { - playSound(p, sound); - } - } - - public void playSound(Player p, String sound) { - float pitch = Float.valueOf(sound.split(":")[1]); - sound = sound.split(":")[0]; - p.playSound(p.getLocation(), Sound.valueOf(sound), pitch, 5.0F); - } - - @Override - public void onEnable() { - log("==== Setup ===="); - - - // Vault dependency check. - if (getServer().getPluginManager().getPlugin("Vault") == null) { - log("Vault is not present, the plugin will not run properly."); - getServer().getPluginManager().disablePlugin(plugin); - return; - } - - int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); - if (version == 7) { - SavageFactions.plugin.log("Minecraft Version 1.7 found, disabling banners, itemflags inside GUIs, and Titles."); - mc17 = true; - } else if (version == 8) { - SavageFactions.plugin.log("Minecraft Version 1.8 found, Title Fadeouttime etc will not be configurable."); - mc18 = true; - } else if (version == 13) { - SavageFactions.plugin.log("Minecraft Version 1.13 found, New Items will be used."); - mc113 = true; - changeItemIDSInConfig(); - } - setupMultiversionMaterials(); - migrateFPlayerLeaders(); - log("==== End Setup ===="); - - if (!preEnable()) { - return; - } - this.loadSuccessful = false; - - saveDefaultConfig(); - - // Load Conf from disk - Conf.load(); - com.massivecraft.factions.integration.Essentials.setup(); - hookedPlayervaults = setupPlayervaults(); - FPlayers.getInstance().load(); - Factions.getInstance().load(); - - for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { - Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); - if (faction == null) { - log("Invalid faction id on " + fPlayer.getName() + ":" + fPlayer.getFactionId()); - fPlayer.resetFactionData(false); - continue; - } - faction.addFPlayer(fPlayer); - } - playersFlying.clear(); - for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { - playersFlying.add(fPlayer); - } - UtilFly.run(); - - Board.getInstance().load(); - Board.getInstance().clean(); - - // Add Base Commands - this.cmdBase = new FCmdRoot(); - this.cmdAutoHelp = new CmdAutoHelp(); - this.getBaseCommands().add(cmdBase); - - Econ.setup(); - setupPermissions(); - - if (Conf.worldGuardChecking || Conf.worldGuardBuildPriority) { - Worldguard.init(this); - } - - EngineDynmap.getInstance().init(); - - // start up task which runs the autoLeaveAfterDaysOfInactivity routine - startAutoLeaveTask(false); - - if (getConfig().getBoolean("MassiveStats")) { - // massive stats - new MassiveStats(this); - } - - if (version > 8) { - useNonPacketParticles = true; - log("Minecraft Version 1.9 or higher found, using non packet based particle API"); - } - - if (getConfig().getBoolean("enable-faction-flight")) { - factionsFlight = true; - } - - if (getServer().getPluginManager().getPlugin("Skript") != null) { - log("Skript was found! Registering SavageFactions Addon..."); - skriptAddon = Skript.registerAddon(this); - try { - skriptAddon.loadClasses("com.massivecraft.factions.skript", "expressions"); - } catch (IOException ex) { - ex.printStackTrace(); - } - log("Skript addon registered!"); - } - - - // Register Event Handlers - eventsListener = new Listener[]{ - new FactionsPlayerListener(), - new FactionsChatListener(), - new FactionsEntityListener(), - new FactionsExploitListener(), - new FactionsBlockListener(), - new FUpgradesGUI(), - new EXPUpgrade(), - new CropUpgrades(), - new SpawnerUpgrades(), - }; - - for (Listener eventListener : eventsListener) - getServer().getPluginManager().registerEvents(eventListener, this); - - // since some other plugins execute commands directly through this command interface, provide it - getCommand(this.refCommand).setExecutor(this); - getCommand(this.refCommand).setTabCompleter(this); - - setupEssentials(); - - if (getDescription().getFullName().contains("BETA")) { - divider(); - System.out.println("You are using a BETA version of the plugin!"); - System.out.println("This comes with risks of small bugs in newer features!"); - System.out.println("For support head to: https://github.com/ProSavage/SavageFactions/issues"); - divider(); - } - - this.setupPlaceholderAPI(); - this.postEnable(); - this.loadSuccessful = true; - } - - public SkriptAddon getSkriptAddon() { - return skriptAddon; - } - - private void setupMultiversionMaterials() { - if (mc113) { - BANNER = Material.valueOf("LEGACY_BANNER"); - CROPS = Material.valueOf("LEGACY_CROPS"); - SUGAR_CANE_BLOCK = Material.valueOf("LEGACY_SUGAR_CANE_BLOCK"); - REDSTONE_LAMP_ON = Material.valueOf("LEGACY_REDSTONE_LAMP_ON"); - STAINED_GLASS = Material.valueOf("LEGACY_STAINED_GLASS"); - STATIONARY_WATER = Material.valueOf("LEGACY_STATIONARY_WATER"); - STAINED_CLAY = Material.valueOf("LEGACY_STAINED_CLAY"); - WOOD_BUTTON = Material.valueOf("LEGACY_WOOD_BUTTON"); - SOIL = Material.valueOf("LEGACY_SOIL"); - MOB_SPANWER = Material.valueOf("LEGACY_MOB_SPAWNER"); - THIN_GLASS = Material.valueOf("LEGACY_THIN_GLASS"); - IRON_FENCE = Material.valueOf("LEGACY_IRON_FENCE"); - NETHER_FENCE = Material.valueOf("LEGACY_NETHER_FENCE"); - FENCE = Material.valueOf("LEGACY_FENCE"); - WOODEN_DOOR = Material.valueOf("LEGACY_WOODEN_DOOR"); - TRAP_DOOR = Material.valueOf("LEGACY_TRAP_DOOR"); - FENCE_GATE = Material.valueOf("LEGACY_FENCE_GATE"); - BURNING_FURNACE = Material.valueOf("LEGACY_BURNING_FURNACE"); - DIODE_BLOCK_OFF = Material.valueOf("LEGACY_DIODE_BLOCK_OFF"); - DIODE_BLOCK_ON = Material.valueOf("LEGACY_DIODE_BLOCK_ON"); - ENCHANTMENT_TABLE = Material.valueOf("LEGACY_ENCHANTMENT_TABLE"); - FIREBALL = Material.valueOf("LEGACY_FIREBALL"); - - } else { - if (!mc17) { - BANNER = Material.valueOf("BANNER"); - } - CROPS = Material.valueOf("CROPS"); - SUGAR_CANE_BLOCK = Material.valueOf("SUGAR_CANE_BLOCK"); - REDSTONE_LAMP_ON = Material.valueOf("REDSTONE_LAMP_ON"); - STAINED_GLASS = Material.valueOf("STAINED_GLASS"); - STATIONARY_WATER = Material.valueOf("STATIONARY_WATER"); - STAINED_CLAY = Material.valueOf("STAINED_CLAY"); - WOOD_BUTTON = Material.valueOf("WOOD_BUTTON"); - SOIL = Material.valueOf("SOIL"); - MOB_SPANWER = Material.valueOf("MOB_SPAWNER"); - THIN_GLASS = Material.valueOf("THIN_GLASS"); - IRON_FENCE = Material.valueOf("IRON_FENCE"); - NETHER_FENCE = Material.valueOf("NETHER_FENCE"); - FENCE = Material.valueOf("FENCE"); - WOODEN_DOOR = Material.valueOf("WOODEN_DOOR"); - TRAP_DOOR = Material.valueOf("TRAP_DOOR"); - FENCE_GATE = Material.valueOf("FENCE_GATE"); - BURNING_FURNACE = Material.valueOf("BURNING_FURNACE"); - DIODE_BLOCK_OFF = Material.valueOf("DIODE_BLOCK_OFF"); - DIODE_BLOCK_ON = Material.valueOf("DIODE_BLOCK_ON"); - ENCHANTMENT_TABLE = Material.valueOf("ENCHANTMENT_TABLE"); - FIREBALL = Material.valueOf("FIREBALL"); - } - - } - - private void setupPlaceholderAPI() { - Plugin clip = getServer().getPluginManager().getPlugin("PlaceholderAPI"); - if (clip != null && clip.isEnabled()) { - this.clipPlaceholderAPIManager = new ClipPlaceholderAPIManager(); - if (this.clipPlaceholderAPIManager.register()) { - PlaceholderApi = true; - log(Level.INFO, "Successfully registered placeholders with PlaceholderAPI."); - } else { - PlaceholderApi = false; - } - } else { - PlaceholderApi = false; - } - - Plugin mvdw = getServer().getPluginManager().getPlugin("MVdWPlaceholderAPI"); - if (mvdw != null && mvdw.isEnabled()) { - this.mvdwPlaceholderAPIManager = true; - log(Level.INFO, "Found MVdWPlaceholderAPI. Adding hooks."); - } - } - - private void migrateFPlayerLeaders() { - List lines = new ArrayList<>(); - File fplayerFile = new File("plugins\\Factions\\players.json"); - - try { - BufferedReader br = new BufferedReader(new FileReader(fplayerFile)); - System.out.println("Migrating old players.json file."); - - String line; - while ((line = br.readLine()) != null) { - if (line.contains("\"role\": \"ADMIN\"")) { - line = line.replace("\"role\": \"ADMIN\"", "\"role\": " + "\"LEADER\""); - } - lines.add(line); - } - br.close(); - BufferedWriter bw = new BufferedWriter(new FileWriter(fplayerFile)); - for (String newLine : lines) { - bw.write(newLine + "\n"); - } - bw.flush(); - bw.close(); - } catch (IOException ex) { - System.out.println("File was not found for players.json, assuming" - + " there is no need to migrate old players.json file."); - } - } - - public void changeItemIDSInConfig() { - log("Starting conversion of legacy material in config to 1.13 materials."); - - replaceStringInConfig("fperm-gui.relation.materials.recruit", "WOOD_SWORD", "WOODEN_SWORD"); - replaceStringInConfig("fperm-gui.relation.materials.normal", "GOLD_SWORD", "GOLDEN_SWORD"); - replaceStringInConfig("fperm-gui.relation.materials.ally", "GOLD_AXE", "GOLDEN_AXE"); - replaceStringInConfig("fperm-gui.relation.materials.neutral", "WOOD_AXE", "WOODEN_AXE"); - - ConfigurationSection actionMaterialsConfigSection = getConfig().getConfigurationSection("fperm-gui.action.materials"); - Set actionMaterialKeys = actionMaterialsConfigSection.getKeys(true); - - - for (String key : actionMaterialKeys) { - replaceStringInConfig("fperm-gui.action.materials." + key, "STAINED_GLASS", "GRAY_STAINED_GLASS"); - } - - replaceStringInConfig("fperm-gui.dummy-items.0.material", "STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE"); - replaceStringInConfig("fwarp-gui.dummy-items.0.material", "STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE"); - - replaceStringInConfig("fupgrades.MainMenu.DummyItem.Type", "STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE"); - replaceStringInConfig("fupgrades.MainMenu.EXP.EXPItem.Type", "EXP_BOTTLE", "EXPERIENCE_BOTTLE"); - replaceStringInConfig("fupgrades.MainMenu.Spawners.SpawnerItem.Type", "MOB_SPAWNER", "SPAWNER"); - - replaceStringInConfig("fperm-gui.action.access.allow", "LIME", "LIME_STAINED_GLASS"); - replaceStringInConfig("fperm-gui.action.access.deny", "RED", "RED_STAINED_GLASS"); - replaceStringInConfig("fperm-gui.action.access.undefined", "CYAN", "CYAN_STAINED_GLASS"); - } - - public void replaceStringInConfig(String path, String stringToReplace, String replacementString) { - if (getConfig().getString(path).equals(stringToReplace)) { - // SavageFactions.plugin.log("Replacing legacy material '" + stringToReplace + "' with '" + replacementString + "' for config node '" + path + "'."); - // log("Replacing legacy material '" + stringToReplace + "' with '" + replacementString + "' for config node '" + path + "'."); - - getConfig().set(path, replacementString); - } - } - - public boolean isClipPlaceholderAPIHooked() { - return this.clipPlaceholderAPIManager != null; - } - - public boolean isMVdWPlaceholderAPIHooked() { - return this.mvdwPlaceholderAPIManager; - } - - private boolean setupPermissions() { - try { - RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Permission.class); - if (rsp != null) { - perms = rsp.getProvider(); - } - } catch (NoClassDefFoundError ex) { - return false; - } - return perms != null; - } - - private boolean setupPlayervaults() { - Plugin plugin = getServer().getPluginManager().getPlugin("PlayerVaults"); - return plugin != null && plugin.isEnabled(); - } - - @Override - public GsonBuilder getGsonBuilder() { - Type mapFLocToStringSetType = new TypeToken>>() { - }.getType(); - - Type accessTypeAdatper = new TypeToken>>() { - }.getType(); - - return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().enableComplexMapKeySerialization().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) - .registerTypeAdapter(accessTypeAdatper, new PermissionsMapTypeAdapter()) - .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) - .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()) - .registerTypeAdapter(Inventory.class, new InventoryTypeAdapter()) - .registerTypeAdapter(Location.class, new LocationTypeAdapter()) - .registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY); - } - - private void divider() { - System.out.println(" .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-"); - System.out.println(" / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\"); - System.out.println("`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-'"); - } - - @Override - public void onDisable() { - // only save data if plugin actually completely loaded successfully - if (this.loadSuccessful) { - // Dont save, as this is kind of pointless, as the /f config command manually saves. - // So any edits done are saved, this way manual edits to json can go through. - - // Conf.save(); - } - - if (AutoLeaveTask != null) { - this.getServer().getScheduler().cancelTask(AutoLeaveTask); - AutoLeaveTask = null; - } - - super.onDisable(); - } - - public void startAutoLeaveTask(boolean restartIfRunning) { - if (AutoLeaveTask != null) { - if (!restartIfRunning) { - return; - } - this.getServer().getScheduler().cancelTask(AutoLeaveTask); - } - - if (Conf.autoLeaveRoutineRunsEveryXMinutes > 0.0) { - long ticks = (long) (20 * 60 * Conf.autoLeaveRoutineRunsEveryXMinutes); - AutoLeaveTask = getServer().getScheduler().scheduleSyncRepeatingTask(this, new AutoLeaveTask(), ticks, ticks); - } - } - - @Override - public void postAutoSave() { - //Board.getInstance().forceSave(); Not sure why this was there as it's called after the board is already saved. - Conf.save(); - } - - public ItemStack createItem(Material material, int amount, short datavalue, String name, List lore) { - ItemStack item = new ItemStack(material, amount, datavalue); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(color(name)); - meta.setLore(colorList(lore)); - item.setItemMeta(meta); - return item; - } - - public ItemStack createLazyItem(Material material, int amount, short datavalue, String name, String lore) { - ItemStack item = new ItemStack(material, amount, datavalue); - ItemMeta meta = item.getItemMeta(); - meta.setDisplayName(color(SavageFactions.plugin.getConfig().getString(name))); - meta.setLore(colorList(SavageFactions.plugin.getConfig().getStringList(lore))); - item.setItemMeta(meta); - return item; - } - - public Economy getEcon() { - RegisteredServiceProvider rsp = SavageFactions.plugin.getServer().getServicesManager().getRegistration(Economy.class); - Economy econ = rsp.getProvider(); - return econ; - } - - private boolean setupEssentials() { - SavageFactions.plugin.ess = (Essentials) this.getServer().getPluginManager().getPlugin("Essentials"); - return SavageFactions.plugin.ess == null; - } - - @Override - public boolean logPlayerCommands() { - return Conf.logPlayerCommands; - } - - @Override - public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { - return sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player) sender) || super.handleCommand(sender, commandString, testOnly); - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { - if (split.length == 0) { - return handleCommand(sender, "/f help", false); - } - - // otherwise, needs to be handled; presumably another plugin directly ran the command - String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); - return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false); - } - - @Override - public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer((Player) sender); - List completions = new ArrayList<>(); - String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); - List argsList = new ArrayList<>(Arrays.asList(args)); - argsList.remove(argsList.size() - 1); - String cmdValid = (cmd + " " + TextUtil.implode(argsList, " ")).trim(); - MCommand commandEx = cmdBase; - List> commandsList = cmdBase.subCommands; - - if (Board.getInstance().getFactionAt(new FLocation(fPlayer.getPlayer().getLocation())) == Factions.getInstance().getWarZone()) { - sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cYou cannot use autocomplete in warzone.")); - return new ArrayList<>(); - } - - for (; !commandsList.isEmpty() && !argsList.isEmpty(); argsList.remove(0)) { - String cmdName = argsList.get(0).toLowerCase(); - MCommand commandFounded = commandsList.stream() - .filter(c -> c.aliases.contains(cmdName)) - .findFirst().orElse(null); - - if (commandFounded != null) { - commandEx = commandFounded; - commandsList = commandFounded.subCommands; - } else break; - } - - if (argsList.isEmpty()) { - for (MCommand subCommand : commandEx.subCommands) { - subCommand.setCommandSender(sender); - if (handleCommand(sender, cmdValid + " " + subCommand.aliases.get(0), true) - && subCommand.visibility != CommandVisibility.INVISIBLE - && subCommand.validSenderType(sender, false) - && subCommand.validSenderPermissions(sender, false)) - completions.addAll(subCommand.aliases); - } - } - - String lastArg = args[args.length - 1].toLowerCase(); - - completions = completions.stream() - .filter(m -> m.toLowerCase().startsWith(lastArg)) - .collect(Collectors.toList()); - - return completions; - } - - public void createTimedHologram(final Location location, String text, Long timeout) { - ArmorStand as = (ArmorStand) location.add(0.5, 1, 0.5).getWorld().spawnEntity(location, EntityType.ARMOR_STAND); //Spawn the ArmorStand - as.setVisible(false); //Makes the ArmorStand invisible - as.setGravity(false); //Make sure it doesn't fall - as.setCanPickupItems(false); //I'm not sure what happens if you leave this as it is, but you might as well disable it - as.setCustomName(SavageFactions.plugin.color(text)); //Set this to the text you want - as.setCustomNameVisible(true); //This makes the text appear no matter if your looking at the entity or not - final ArmorStand armorStand = as; - - Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, () -> { - armorStand.remove(); - getLogger().info("Removing Hologram."); - } - , timeout * 20); - } - - - // -------------------------------------------- // - // Functions for other plugins to hook into - // -------------------------------------------- // - - // This value will be updated whenever new hooks are added - public int hookSupportVersion() { - return 3; - } - - // If another plugin is handling insertion of chat tags, this should be used to notify Factions - public void handleFactionTagExternally(boolean notByFactions) { - Conf.chatTagHandledByAnotherPlugin = notByFactions; - } - - // Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat - // enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand() - - public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) { - return event != null && (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); - } - - - // Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels, - // local chat, or anything else which targets individual recipients, so Faction Chat can be done - public boolean isPlayerFactionChatting(Player player) { - if (player == null) { - return false; - } - FPlayer me = FPlayers.getInstance().getByPlayer(player); - - return me != null && me.getChatMode().isAtLeast(ChatMode.ALLIANCE); - } - - // Is this chat message actually a Factions command, and thus should be left alone by other plugins? - - // TODO: GET THIS BACK AND WORKING - - public boolean isFactionsCommand(String check) { - return !(check == null || check.isEmpty()) && this.handleCommand(null, check, true); - } - - // Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat - public String getPlayerFactionTag(Player player) { - return getPlayerFactionTagRelation(player, null); - } - - // Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag - public String getPlayerFactionTagRelation(Player speaker, Player listener) { - String tag = "~"; - - if (speaker == null) { - return tag; - } - - FPlayer me = FPlayers.getInstance().getByPlayer(speaker); - if (me == null) { - return tag; - } - - // if listener isn't set, or config option is disabled, give back uncolored tag - if (listener == null || !Conf.chatTagRelationColored) { - tag = me.getChatTag().trim(); - } else { - FPlayer you = FPlayers.getInstance().getByPlayer(listener); - if (you == null) { - tag = me.getChatTag().trim(); - } else // everything checks out, give the colored tag - { - tag = me.getChatTag(you).trim(); - } - } - if (tag.isEmpty()) { - tag = "~"; - } - - return tag; - } - - // Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat - public String getPlayerTitle(Player player) { - if (player == null) { - return ""; - } - - FPlayer me = FPlayers.getInstance().getByPlayer(player); - if (me == null) { - return ""; - } - - return me.getTitle().trim(); - } - - public String color(String line) { - line = ChatColor.translateAlternateColorCodes('&', line); - return line; - } - - //colors a string list - public List colorList(List lore) { - for (int i = 0; i <= lore.size() - 1; i++) { - lore.set(i, color(lore.get(i))); - } - return lore; - } - - // Get a list of all faction tags (names) - public Set getFactionTags() { - return Factions.getInstance().getFactionTags(); - } - - // Get a list of all players in the specified faction - public Set getPlayersInFaction(String factionTag) { - Set players = new HashSet<>(); - Faction faction = Factions.getInstance().getByTag(factionTag); - if (faction != null) { - for (FPlayer fplayer : faction.getFPlayers()) { - players.add(fplayer.getName()); - } - } - return players; - } - - // Get a list of all online players in the specified faction - public Set getOnlinePlayersInFaction(String factionTag) { - Set players = new HashSet<>(); - Faction faction = Factions.getInstance().getByTag(factionTag); - if (faction != null) { - for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) { - players.add(fplayer.getName()); - } - } - return players; - } - - public boolean isHookedPlayervaults() { - return hookedPlayervaults; - } - - public String getPrimaryGroup(OfflinePlayer player) { - return perms == null || !perms.hasGroupSupport() ? " " : perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player); - } - - public void debug(Level level, String s) { - if (getConfig().getBoolean("debug", false)) { - getLogger().log(level, s); - } - } - - public void debug(String s) { - debug(Level.INFO, s); - } + // Our single plugin instance. + // Single 4 life. + public static SavageFactions plugin; + public static Permission perms = null; + // Persistence related + public static ArrayList playersFlying = new ArrayList(); + public Essentials ess; + public boolean PlaceholderApi; + // Commands + public FCmdRoot cmdBase; + public CmdAutoHelp cmdAutoHelp; + public boolean mc17 = false; + public boolean mc18 = false; + public boolean mc113 = false; + public boolean useNonPacketParticles = false; + public boolean factionsFlight = false; + //multiversion material fields + public Material SUGAR_CANE_BLOCK, BANNER, CROPS, REDSTONE_LAMP_ON, + STAINED_GLASS, STATIONARY_WATER, STAINED_CLAY, WOOD_BUTTON, + SOIL, MOB_SPANWER, THIN_GLASS, IRON_FENCE, NETHER_FENCE, FENCE, + WOODEN_DOOR, TRAP_DOOR, FENCE_GATE, BURNING_FURNACE, DIODE_BLOCK_OFF, + DIODE_BLOCK_ON, ENCHANTMENT_TABLE, FIREBALL; + SkriptAddon skriptAddon; + private boolean locked = false; + private Integer AutoLeaveTask = null; + private boolean hookedPlayervaults; + private ClipPlaceholderAPIManager clipPlaceholderAPIManager; + private boolean mvdwPlaceholderAPIManager = false; + private Listener[] eventsListener; + + public SavageFactions() { + plugin = this; + } + + public boolean getLocked() { + return this.locked; + } + + public void setLocked(boolean val) { + this.locked = val; + this.setAutoSave(val); + } + + public void playSoundForAll(String sound) { + for (Player pl : Bukkit.getOnlinePlayers()) { + playSound(pl, sound); + } + } + + public void playSoundForAll(List sounds) { + for (Player pl : Bukkit.getOnlinePlayers()) { + playSound(pl, sounds); + } + } + + public void playSound(Player p, List sounds) { + for (String sound : sounds) { + playSound(p, sound); + } + } + + public void playSound(Player p, String sound) { + float pitch = Float.valueOf(sound.split(":")[1]); + sound = sound.split(":")[0]; + p.playSound(p.getLocation(), Sound.valueOf(sound), pitch, 5.0F); + } + + @Override + public void onEnable() { + log("==== Setup ===="); + + + // Vault dependency check. + if (getServer().getPluginManager().getPlugin("Vault") == null) { + log("Vault is not present, the plugin will not run properly."); + getServer().getPluginManager().disablePlugin(plugin); + return; + } + + int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); + if (version == 7) { + SavageFactions.plugin.log("Minecraft Version 1.7 found, disabling banners, itemflags inside GUIs, and Titles."); + mc17 = true; + } else if (version == 8) { + SavageFactions.plugin.log("Minecraft Version 1.8 found, Title Fadeouttime etc will not be configurable."); + mc18 = true; + } else if (version == 13) { + SavageFactions.plugin.log("Minecraft Version 1.13 found, New Items will be used."); + mc113 = true; + changeItemIDSInConfig(); + } + setupMultiversionMaterials(); + migrateFPlayerLeaders(); + log("==== End Setup ===="); + + if (!preEnable()) { + return; + } + this.loadSuccessful = false; + + saveDefaultConfig(); + + // Load Conf from disk + Conf.load(); + com.massivecraft.factions.integration.Essentials.setup(); + hookedPlayervaults = setupPlayervaults(); + FPlayers.getInstance().load(); + Factions.getInstance().load(); + + for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { + Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); + if (faction == null) { + log("Invalid faction id on " + fPlayer.getName() + ":" + fPlayer.getFactionId()); + fPlayer.resetFactionData(false); + continue; + } + faction.addFPlayer(fPlayer); + } + playersFlying.clear(); + for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { + playersFlying.add(fPlayer); + } + UtilFly.run(); + + Board.getInstance().load(); + Board.getInstance().clean(); + + // Add Base Commands + this.cmdBase = new FCmdRoot(); + this.cmdAutoHelp = new CmdAutoHelp(); + this.getBaseCommands().add(cmdBase); + + Econ.setup(); + setupPermissions(); + + if (Conf.worldGuardChecking || Conf.worldGuardBuildPriority) { + Worldguard.init(this); + } + + EngineDynmap.getInstance().init(); + + // start up task which runs the autoLeaveAfterDaysOfInactivity routine + startAutoLeaveTask(false); + + if (getConfig().getBoolean("MassiveStats")) { + // massive stats + new MassiveStats(this); + } + + if (version > 8) { + useNonPacketParticles = true; + log("Minecraft Version 1.9 or higher found, using non packet based particle API"); + } + + if (getConfig().getBoolean("enable-faction-flight")) { + factionsFlight = true; + } + + if (getServer().getPluginManager().getPlugin("Skript") != null) { + log("Skript was found! Registering SavageFactions Addon..."); + skriptAddon = Skript.registerAddon(this); + try { + skriptAddon.loadClasses("com.massivecraft.factions.skript", "expressions"); + } catch (IOException ex) { + ex.printStackTrace(); + } + log("Skript addon registered!"); + } + + + // Register Event Handlers + eventsListener = new Listener[]{ + new FactionsPlayerListener(), + new FactionsChatListener(), + new FactionsEntityListener(), + new FactionsExploitListener(), + new FactionsBlockListener(), + new FUpgradesGUI(), + new EXPUpgrade(), + new CropUpgrades(), + new SpawnerUpgrades(), + }; + + for (Listener eventListener : eventsListener) + getServer().getPluginManager().registerEvents(eventListener, this); + + // since some other plugins execute commands directly through this command interface, provide it + getCommand(this.refCommand).setExecutor(this); + getCommand(this.refCommand).setTabCompleter(this); + + setupEssentials(); + + if (getDescription().getFullName().contains("BETA")) { + divider(); + System.out.println("You are using a BETA version of the plugin!"); + System.out.println("This comes with risks of small bugs in newer features!"); + System.out.println("For support head to: https://github.com/ProSavage/SavageFactions/issues"); + divider(); + } + + this.setupPlaceholderAPI(); + this.postEnable(); + this.loadSuccessful = true; + } + + public SkriptAddon getSkriptAddon() { + return skriptAddon; + } + + private void setupMultiversionMaterials() { + if (mc113) { + BANNER = Material.valueOf("LEGACY_BANNER"); + CROPS = Material.valueOf("LEGACY_CROPS"); + SUGAR_CANE_BLOCK = Material.valueOf("LEGACY_SUGAR_CANE_BLOCK"); + REDSTONE_LAMP_ON = Material.valueOf("LEGACY_REDSTONE_LAMP_ON"); + STAINED_GLASS = Material.valueOf("LEGACY_STAINED_GLASS"); + STATIONARY_WATER = Material.valueOf("LEGACY_STATIONARY_WATER"); + STAINED_CLAY = Material.valueOf("LEGACY_STAINED_CLAY"); + WOOD_BUTTON = Material.valueOf("LEGACY_WOOD_BUTTON"); + SOIL = Material.valueOf("LEGACY_SOIL"); + MOB_SPANWER = Material.valueOf("LEGACY_MOB_SPAWNER"); + THIN_GLASS = Material.valueOf("LEGACY_THIN_GLASS"); + IRON_FENCE = Material.valueOf("LEGACY_IRON_FENCE"); + NETHER_FENCE = Material.valueOf("LEGACY_NETHER_FENCE"); + FENCE = Material.valueOf("LEGACY_FENCE"); + WOODEN_DOOR = Material.valueOf("LEGACY_WOODEN_DOOR"); + TRAP_DOOR = Material.valueOf("LEGACY_TRAP_DOOR"); + FENCE_GATE = Material.valueOf("LEGACY_FENCE_GATE"); + BURNING_FURNACE = Material.valueOf("LEGACY_BURNING_FURNACE"); + DIODE_BLOCK_OFF = Material.valueOf("LEGACY_DIODE_BLOCK_OFF"); + DIODE_BLOCK_ON = Material.valueOf("LEGACY_DIODE_BLOCK_ON"); + ENCHANTMENT_TABLE = Material.valueOf("LEGACY_ENCHANTMENT_TABLE"); + FIREBALL = Material.valueOf("LEGACY_FIREBALL"); + + } else { + if (!mc17) { + BANNER = Material.valueOf("BANNER"); + } + CROPS = Material.valueOf("CROPS"); + SUGAR_CANE_BLOCK = Material.valueOf("SUGAR_CANE_BLOCK"); + REDSTONE_LAMP_ON = Material.valueOf("REDSTONE_LAMP_ON"); + STAINED_GLASS = Material.valueOf("STAINED_GLASS"); + STATIONARY_WATER = Material.valueOf("STATIONARY_WATER"); + STAINED_CLAY = Material.valueOf("STAINED_CLAY"); + WOOD_BUTTON = Material.valueOf("WOOD_BUTTON"); + SOIL = Material.valueOf("SOIL"); + MOB_SPANWER = Material.valueOf("MOB_SPAWNER"); + THIN_GLASS = Material.valueOf("THIN_GLASS"); + IRON_FENCE = Material.valueOf("IRON_FENCE"); + NETHER_FENCE = Material.valueOf("NETHER_FENCE"); + FENCE = Material.valueOf("FENCE"); + WOODEN_DOOR = Material.valueOf("WOODEN_DOOR"); + TRAP_DOOR = Material.valueOf("TRAP_DOOR"); + FENCE_GATE = Material.valueOf("FENCE_GATE"); + BURNING_FURNACE = Material.valueOf("BURNING_FURNACE"); + DIODE_BLOCK_OFF = Material.valueOf("DIODE_BLOCK_OFF"); + DIODE_BLOCK_ON = Material.valueOf("DIODE_BLOCK_ON"); + ENCHANTMENT_TABLE = Material.valueOf("ENCHANTMENT_TABLE"); + FIREBALL = Material.valueOf("FIREBALL"); + } + + } + + private void setupPlaceholderAPI() { + Plugin clip = getServer().getPluginManager().getPlugin("PlaceholderAPI"); + if (clip != null && clip.isEnabled()) { + this.clipPlaceholderAPIManager = new ClipPlaceholderAPIManager(); + if (this.clipPlaceholderAPIManager.register()) { + PlaceholderApi = true; + log(Level.INFO, "Successfully registered placeholders with PlaceholderAPI."); + } else { + PlaceholderApi = false; + } + } else { + PlaceholderApi = false; + } + + Plugin mvdw = getServer().getPluginManager().getPlugin("MVdWPlaceholderAPI"); + if (mvdw != null && mvdw.isEnabled()) { + this.mvdwPlaceholderAPIManager = true; + log(Level.INFO, "Found MVdWPlaceholderAPI. Adding hooks."); + } + } + + private void migrateFPlayerLeaders() { + List lines = new ArrayList<>(); + File fplayerFile = new File("plugins\\Factions\\players.json"); + + try { + BufferedReader br = new BufferedReader(new FileReader(fplayerFile)); + System.out.println("Migrating old players.json file."); + + String line; + while ((line = br.readLine()) != null) { + if (line.contains("\"role\": \"ADMIN\"")) { + line = line.replace("\"role\": \"ADMIN\"", "\"role\": " + "\"LEADER\""); + } + lines.add(line); + } + br.close(); + BufferedWriter bw = new BufferedWriter(new FileWriter(fplayerFile)); + for (String newLine : lines) { + bw.write(newLine + "\n"); + } + bw.flush(); + bw.close(); + } catch (IOException ex) { + System.out.println("File was not found for players.json, assuming" + + " there is no need to migrate old players.json file."); + } + } + + public void changeItemIDSInConfig() { + log("Starting conversion of legacy material in config to 1.13 materials."); + + replaceStringInConfig("fperm-gui.relation.materials.recruit", "WOOD_SWORD", "WOODEN_SWORD"); + replaceStringInConfig("fperm-gui.relation.materials.normal", "GOLD_SWORD", "GOLDEN_SWORD"); + replaceStringInConfig("fperm-gui.relation.materials.ally", "GOLD_AXE", "GOLDEN_AXE"); + replaceStringInConfig("fperm-gui.relation.materials.neutral", "WOOD_AXE", "WOODEN_AXE"); + + ConfigurationSection actionMaterialsConfigSection = getConfig().getConfigurationSection("fperm-gui.action.materials"); + Set actionMaterialKeys = actionMaterialsConfigSection.getKeys(true); + + + for (String key : actionMaterialKeys) { + replaceStringInConfig("fperm-gui.action.materials." + key, "STAINED_GLASS", "GRAY_STAINED_GLASS"); + } + + replaceStringInConfig("fperm-gui.dummy-items.0.material", "STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE"); + replaceStringInConfig("fwarp-gui.dummy-items.0.material", "STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE"); + + replaceStringInConfig("fupgrades.MainMenu.DummyItem.Type", "STAINED_GLASS_PANE", "GRAY_STAINED_GLASS_PANE"); + replaceStringInConfig("fupgrades.MainMenu.EXP.EXPItem.Type", "EXP_BOTTLE", "EXPERIENCE_BOTTLE"); + replaceStringInConfig("fupgrades.MainMenu.Spawners.SpawnerItem.Type", "MOB_SPAWNER", "SPAWNER"); + + replaceStringInConfig("fperm-gui.action.access.allow", "LIME", "LIME_STAINED_GLASS"); + replaceStringInConfig("fperm-gui.action.access.deny", "RED", "RED_STAINED_GLASS"); + replaceStringInConfig("fperm-gui.action.access.undefined", "CYAN", "CYAN_STAINED_GLASS"); + } + + public void replaceStringInConfig(String path, String stringToReplace, String replacementString) { + if (getConfig().getString(path).equals(stringToReplace)) { + // SavageFactions.plugin.log("Replacing legacy material '" + stringToReplace + "' with '" + replacementString + "' for config node '" + path + "'."); + // log("Replacing legacy material '" + stringToReplace + "' with '" + replacementString + "' for config node '" + path + "'."); + + getConfig().set(path, replacementString); + } + } + + public boolean isClipPlaceholderAPIHooked() { + return this.clipPlaceholderAPIManager != null; + } + + public boolean isMVdWPlaceholderAPIHooked() { + return this.mvdwPlaceholderAPIManager; + } + + private boolean setupPermissions() { + try { + RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Permission.class); + if (rsp != null) { + perms = rsp.getProvider(); + } + } catch (NoClassDefFoundError ex) { + return false; + } + return perms != null; + } + + private boolean setupPlayervaults() { + Plugin plugin = getServer().getPluginManager().getPlugin("PlayerVaults"); + return plugin != null && plugin.isEnabled(); + } + + @Override + public GsonBuilder getGsonBuilder() { + Type mapFLocToStringSetType = new TypeToken>>() { + }.getType(); + + Type accessTypeAdatper = new TypeToken>>() { + }.getType(); + + return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().enableComplexMapKeySerialization().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE) + .registerTypeAdapter(accessTypeAdatper, new PermissionsMapTypeAdapter()) + .registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()) + .registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()) + .registerTypeAdapter(Inventory.class, new InventoryTypeAdapter()) + .registerTypeAdapter(Location.class, new LocationTypeAdapter()) + .registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY); + } + + private void divider() { + System.out.println(" .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-. .-.-"); + System.out.println(" / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\ \\ / / \\"); + System.out.println("`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-' `-`-'"); + } + + @Override + public void onDisable() { + // only save data if plugin actually completely loaded successfully + if (this.loadSuccessful) { + // Dont save, as this is kind of pointless, as the /f config command manually saves. + // So any edits done are saved, this way manual edits to json can go through. + + // Conf.save(); + } + + if (AutoLeaveTask != null) { + this.getServer().getScheduler().cancelTask(AutoLeaveTask); + AutoLeaveTask = null; + } + + super.onDisable(); + } + + public void startAutoLeaveTask(boolean restartIfRunning) { + if (AutoLeaveTask != null) { + if (!restartIfRunning) { + return; + } + this.getServer().getScheduler().cancelTask(AutoLeaveTask); + } + + if (Conf.autoLeaveRoutineRunsEveryXMinutes > 0.0) { + long ticks = (long) (20 * 60 * Conf.autoLeaveRoutineRunsEveryXMinutes); + AutoLeaveTask = getServer().getScheduler().scheduleSyncRepeatingTask(this, new AutoLeaveTask(), ticks, ticks); + } + } + + @Override + public void postAutoSave() { + //Board.getInstance().forceSave(); Not sure why this was there as it's called after the board is already saved. + Conf.save(); + } + + public ItemStack createItem(Material material, int amount, short datavalue, String name, List lore) { + ItemStack item = new ItemStack(material, amount, datavalue); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(color(name)); + meta.setLore(colorList(lore)); + item.setItemMeta(meta); + return item; + } + + public ItemStack createLazyItem(Material material, int amount, short datavalue, String name, String lore) { + ItemStack item = new ItemStack(material, amount, datavalue); + ItemMeta meta = item.getItemMeta(); + meta.setDisplayName(color(SavageFactions.plugin.getConfig().getString(name))); + meta.setLore(colorList(SavageFactions.plugin.getConfig().getStringList(lore))); + item.setItemMeta(meta); + return item; + } + + public Economy getEcon() { + RegisteredServiceProvider rsp = SavageFactions.plugin.getServer().getServicesManager().getRegistration(Economy.class); + Economy econ = rsp.getProvider(); + return econ; + } + + private boolean setupEssentials() { + SavageFactions.plugin.ess = (Essentials) this.getServer().getPluginManager().getPlugin("Essentials"); + return SavageFactions.plugin.ess == null; + } + + @Override + public boolean logPlayerCommands() { + return Conf.logPlayerCommands; + } + + @Override + public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { + return sender instanceof Player && FactionsPlayerListener.preventCommand(commandString, (Player) sender) || super.handleCommand(sender, commandString, testOnly); + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { + if (split.length == 0) { + return handleCommand(sender, "/f help", false); + } + + // otherwise, needs to be handled; presumably another plugin directly ran the command + String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); + return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false); + } + + @Override + public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer((Player) sender); + List completions = new ArrayList<>(); + String cmd = Conf.baseCommandAliases.isEmpty() ? "/f" : "/" + Conf.baseCommandAliases.get(0); + List argsList = new ArrayList<>(Arrays.asList(args)); + argsList.remove(argsList.size() - 1); + String cmdValid = (cmd + " " + TextUtil.implode(argsList, " ")).trim(); + MCommand commandEx = cmdBase; + List> commandsList = cmdBase.subCommands; + + if (Board.getInstance().getFactionAt(new FLocation(fPlayer.getPlayer().getLocation())) == Factions.getInstance().getWarZone()) { + sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&cYou cannot use autocomplete in warzone.")); + return new ArrayList<>(); + } + + for (; !commandsList.isEmpty() && !argsList.isEmpty(); argsList.remove(0)) { + String cmdName = argsList.get(0).toLowerCase(); + MCommand commandFounded = commandsList.stream() + .filter(c -> c.aliases.contains(cmdName)) + .findFirst().orElse(null); + + if (commandFounded != null) { + commandEx = commandFounded; + commandsList = commandFounded.subCommands; + } else break; + } + + if (argsList.isEmpty()) { + for (MCommand subCommand : commandEx.subCommands) { + subCommand.setCommandSender(sender); + if (handleCommand(sender, cmdValid + " " + subCommand.aliases.get(0), true) + && subCommand.visibility != CommandVisibility.INVISIBLE + && subCommand.validSenderType(sender, false) + && subCommand.validSenderPermissions(sender, false)) + completions.addAll(subCommand.aliases); + } + } + + String lastArg = args[args.length - 1].toLowerCase(); + + completions = completions.stream() + .filter(m -> m.toLowerCase().startsWith(lastArg)) + .collect(Collectors.toList()); + + return completions; + } + + public void createTimedHologram(final Location location, String text, Long timeout) { + ArmorStand as = (ArmorStand) location.add(0.5, 1, 0.5).getWorld().spawnEntity(location, EntityType.ARMOR_STAND); //Spawn the ArmorStand + as.setVisible(false); //Makes the ArmorStand invisible + as.setGravity(false); //Make sure it doesn't fall + as.setCanPickupItems(false); //I'm not sure what happens if you leave this as it is, but you might as well disable it + as.setCustomName(SavageFactions.plugin.color(text)); //Set this to the text you want + as.setCustomNameVisible(true); //This makes the text appear no matter if your looking at the entity or not + final ArmorStand armorStand = as; + + Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, () -> { + armorStand.remove(); + getLogger().info("Removing Hologram."); + } + , timeout * 20); + } + + + // -------------------------------------------- // + // Functions for other plugins to hook into + // -------------------------------------------- // + + // This value will be updated whenever new hooks are added + public int hookSupportVersion() { + return 3; + } + + // If another plugin is handling insertion of chat tags, this should be used to notify Factions + public void handleFactionTagExternally(boolean notByFactions) { + Conf.chatTagHandledByAnotherPlugin = notByFactions; + } + + // Simply put, should this chat event be left for Factions to handle? For now, that means players with Faction Chat + // enabled or use of the Factions f command without a slash; combination of isPlayerFactionChatting() and isFactionsCommand() + + public boolean shouldLetFactionsHandleThisChat(AsyncPlayerChatEvent event) { + return event != null && (isPlayerFactionChatting(event.getPlayer()) || isFactionsCommand(event.getMessage())); + } + + + // Does player have Faction Chat enabled? If so, chat plugins should preferably not do channels, + // local chat, or anything else which targets individual recipients, so Faction Chat can be done + public boolean isPlayerFactionChatting(Player player) { + if (player == null) { + return false; + } + FPlayer me = FPlayers.getInstance().getByPlayer(player); + + return me != null && me.getChatMode().isAtLeast(ChatMode.ALLIANCE); + } + + // Is this chat message actually a Factions command, and thus should be left alone by other plugins? + + // TODO: GET THIS BACK AND WORKING + + public boolean isFactionsCommand(String check) { + return !(check == null || check.isEmpty()) && this.handleCommand(null, check, true); + } + + // Get a player's faction tag (faction name), mainly for usage by chat plugins for local/channel chat + public String getPlayerFactionTag(Player player) { + return getPlayerFactionTagRelation(player, null); + } + + // Same as above, but with relation (enemy/neutral/ally) coloring potentially added to the tag + public String getPlayerFactionTagRelation(Player speaker, Player listener) { + String tag = "~"; + + if (speaker == null) { + return tag; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(speaker); + if (me == null) { + return tag; + } + + // if listener isn't set, or config option is disabled, give back uncolored tag + if (listener == null || !Conf.chatTagRelationColored) { + tag = me.getChatTag().trim(); + } else { + FPlayer you = FPlayers.getInstance().getByPlayer(listener); + if (you == null) { + tag = me.getChatTag().trim(); + } else // everything checks out, give the colored tag + { + tag = me.getChatTag(you).trim(); + } + } + if (tag.isEmpty()) { + tag = "~"; + } + + return tag; + } + + // Get a player's title within their faction, mainly for usage by chat plugins for local/channel chat + public String getPlayerTitle(Player player) { + if (player == null) { + return ""; + } + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me == null) { + return ""; + } + + return me.getTitle().trim(); + } + + public String color(String line) { + line = ChatColor.translateAlternateColorCodes('&', line); + return line; + } + + //colors a string list + public List colorList(List lore) { + for (int i = 0; i <= lore.size() - 1; i++) { + lore.set(i, color(lore.get(i))); + } + return lore; + } + + // Get a list of all faction tags (names) + public Set getFactionTags() { + return Factions.getInstance().getFactionTags(); + } + + // Get a list of all players in the specified faction + public Set getPlayersInFaction(String factionTag) { + Set players = new HashSet<>(); + Faction faction = Factions.getInstance().getByTag(factionTag); + if (faction != null) { + for (FPlayer fplayer : faction.getFPlayers()) { + players.add(fplayer.getName()); + } + } + return players; + } + + // Get a list of all online players in the specified faction + public Set getOnlinePlayersInFaction(String factionTag) { + Set players = new HashSet<>(); + Faction faction = Factions.getInstance().getByTag(factionTag); + if (faction != null) { + for (FPlayer fplayer : faction.getFPlayersWhereOnline(true)) { + players.add(fplayer.getName()); + } + } + return players; + } + + public boolean isHookedPlayervaults() { + return hookedPlayervaults; + } + + public String getPrimaryGroup(OfflinePlayer player) { + return perms == null || !perms.hasGroupSupport() ? " " : perms.getPrimaryGroup(Bukkit.getWorlds().get(0).toString(), player); + } + + public void debug(Level level, String s) { + if (getConfig().getBoolean("debug", false)) { + getLogger().log(level, s); + } + } + + public void debug(String s) { + debug(Level.INFO, s); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java b/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java index f9a2bdc1..ba413640 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAHome.java @@ -8,45 +8,45 @@ import org.bukkit.event.player.PlayerTeleportEvent; public class CmdAHome extends FCommand { - public CmdAHome() { - super(); - this.aliases.add("ahome"); + public CmdAHome() { + super(); + this.aliases.add("ahome"); - this.requiredArgs.add("player name"); + this.requiredArgs.add("player name"); - this.permission = Permission.AHOME.node; - this.disableOnLock = false; + this.permission = Permission.AHOME.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer target = argAsBestFPlayerMatch(0); - if (target == null) { - msg(TL.GENERIC_NOPLAYERMATCH, argAsString(0)); - return; - } + @Override + public void perform() { + FPlayer target = argAsBestFPlayerMatch(0); + if (target == null) { + msg(TL.GENERIC_NOPLAYERMATCH, argAsString(0)); + return; + } - if (target.isOnline()) { - Faction faction = target.getFaction(); - if (faction.hasHome()) { - target.getPlayer().teleport(faction.getHome(), PlayerTeleportEvent.TeleportCause.PLUGIN); - msg(TL.COMMAND_AHOME_SUCCESS, target.getName()); - target.msg(TL.COMMAND_AHOME_TARGET); - } else { - msg(TL.COMMAND_AHOME_NOHOME, target.getName()); - } - } else { - msg(TL.COMMAND_AHOME_OFFLINE, target.getName()); - } - } + if (target.isOnline()) { + Faction faction = target.getFaction(); + if (faction.hasHome()) { + target.getPlayer().teleport(faction.getHome(), PlayerTeleportEvent.TeleportCause.PLUGIN); + msg(TL.COMMAND_AHOME_SUCCESS, target.getName()); + target.msg(TL.COMMAND_AHOME_TARGET); + } else { + msg(TL.COMMAND_AHOME_NOHOME, target.getName()); + } + } else { + msg(TL.COMMAND_AHOME_OFFLINE, target.getName()); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_AHOME_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_AHOME_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java index ed21beb0..5c03529f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAdmin.java @@ -11,90 +11,90 @@ import org.bukkit.Bukkit; public class CmdAdmin extends FCommand { - public CmdAdmin() { - super(); - this.aliases.add("admin"); - this.aliases.add("setadmin"); - this.aliases.add("leader"); - this.aliases.add("setleader"); + public CmdAdmin() { + super(); + this.aliases.add("admin"); + this.aliases.add("setadmin"); + this.aliases.add("leader"); + this.aliases.add("setleader"); - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); - this.permission = Permission.ADMIN.node; - this.disableOnLock = true; + this.permission = Permission.ADMIN.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer fyou = this.argAsBestFPlayerMatch(0); - if (fyou == null) { - return; - } + @Override + public void perform() { + FPlayer fyou = this.argAsBestFPlayerMatch(0); + if (fyou == null) { + return; + } - boolean permAny = Permission.ADMIN_ANY.has(sender, false); - Faction targetFaction = fyou.getFaction(); + boolean permAny = Permission.ADMIN_ANY.has(sender, false); + Faction targetFaction = fyou.getFaction(); - if (targetFaction != myFaction && !permAny) { - msg(TL.COMMAND_ADMIN_NOTMEMBER, fyou.describeTo(fme, true)); - return; - } + if (targetFaction != myFaction && !permAny) { + msg(TL.COMMAND_ADMIN_NOTMEMBER, fyou.describeTo(fme, true)); + return; + } - if (fme != null && fme.getRole() != Role.LEADER && !permAny) { - msg(TL.COMMAND_ADMIN_NOTADMIN); - return; - } + if (fme != null && fme.getRole() != Role.LEADER && !permAny) { + msg(TL.COMMAND_ADMIN_NOTADMIN); + return; + } - if (fyou == fme && !permAny) { - msg(TL.COMMAND_ADMIN_TARGETSELF); - return; - } + if (fyou == fme && !permAny) { + msg(TL.COMMAND_ADMIN_TARGETSELF); + return; + } - // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction - if (fyou.getFaction() != targetFaction) { - FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(me), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } - } + // only perform a FPlayerJoinEvent when newLeader isn't actually in the faction + if (fyou.getFaction() != targetFaction) { + FPlayerJoinEvent event = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(me), targetFaction, FPlayerJoinEvent.PlayerJoinReason.LEADER); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } + } - FPlayer admin = targetFaction.getFPlayerAdmin(); + FPlayer admin = targetFaction.getFPlayerAdmin(); - if (fyou == admin && fyou.getFaction().getSize() == 1) { - msg(TL.COMMAND_ADMIN_NOMEMBERS); - return; - } + if (fyou == admin && fyou.getFaction().getSize() == 1) { + msg(TL.COMMAND_ADMIN_NOMEMBERS); + return; + } - // if target player is currently admin, demote and replace him - if (fyou == admin) { - targetFaction.promoteNewLeader(); - msg(TL.COMMAND_ADMIN_DEMOTES, fyou.describeTo(fme, true)); - fyou.msg(TL.COMMAND_ADMIN_DEMOTED, senderIsConsole ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fyou, true)); - return; - } + // if target player is currently admin, demote and replace him + if (fyou == admin) { + targetFaction.promoteNewLeader(); + msg(TL.COMMAND_ADMIN_DEMOTES, fyou.describeTo(fme, true)); + fyou.msg(TL.COMMAND_ADMIN_DEMOTED, senderIsConsole ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fyou, true)); + return; + } - // promote target player, and demote existing admin if one exists - if (admin != null) { - admin.setRole(Role.COLEADER); - } - fyou.setRole(Role.LEADER); - msg(TL.COMMAND_ADMIN_PROMOTES, fyou.describeTo(fme, true)); + // promote target player, and demote existing admin if one exists + if (admin != null) { + admin.setRole(Role.COLEADER); + } + fyou.setRole(Role.LEADER); + msg(TL.COMMAND_ADMIN_PROMOTES, fyou.describeTo(fme, true)); - // Inform all players - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, senderIsConsole ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); - } - } + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.COMMAND_ADMIN_PROMOTED, senderIsConsole ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true), fyou.describeTo(fplayer), targetFaction.describeTo(fplayer)); + } + } - public TL getUsageTranslation() { - return TL.COMMAND_ADMIN_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_ADMIN_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java b/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java index 296891d7..952d9d38 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAnnounce.java @@ -9,41 +9,41 @@ import org.bukkit.entity.Player; public class CmdAnnounce extends FCommand { - public CmdAnnounce() { - super(); - this.aliases.add("ann"); - this.aliases.add("announce"); + public CmdAnnounce() { + super(); + this.aliases.add("ann"); + this.aliases.add("announce"); - this.requiredArgs.add("message"); - this.errorOnToManyArgs = false; + this.requiredArgs.add("message"); + this.errorOnToManyArgs = false; - this.permission = Permission.ANNOUNCE.node; - this.disableOnLock = false; + this.permission = Permission.ANNOUNCE.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + } - @Override - public void perform() { - String prefix = ChatColor.GREEN + myFaction.getTag() + ChatColor.YELLOW + " [" + ChatColor.GRAY + me.getName() + ChatColor.YELLOW + "] " + ChatColor.RESET; - String message = StringUtils.join(args, " "); + @Override + public void perform() { + String prefix = ChatColor.GREEN + myFaction.getTag() + ChatColor.YELLOW + " [" + ChatColor.GRAY + me.getName() + ChatColor.YELLOW + "] " + ChatColor.RESET; + String message = StringUtils.join(args, " "); - for (Player player : myFaction.getOnlinePlayers()) { - player.sendMessage(prefix + message); - } + for (Player player : myFaction.getOnlinePlayers()) { + player.sendMessage(prefix + message); + } - // Add for offline players. - for (FPlayer fp : myFaction.getFPlayersWhereOnline(false)) { - myFaction.addAnnouncement(fp, prefix + message); - } - } + // Add for offline players. + for (FPlayer fp : myFaction.getFPlayersWhereOnline(false)) { + myFaction.addAnnouncement(fp, prefix + message); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_ANNOUNCE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_ANNOUNCE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java index 5aa47e72..61742f98 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoClaim.java @@ -7,50 +7,50 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdAutoClaim extends FCommand { - public CmdAutoClaim() { - super(); - this.aliases.add("autoclaim"); + public CmdAutoClaim() { + super(); + this.aliases.add("autoclaim"); - //this.requiredArgs.add(""); - this.optionalArgs.put("faction", "your"); + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "your"); - this.permission = Permission.AUTOCLAIM.node; - this.disableOnLock = true; + this.permission = Permission.AUTOCLAIM.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Faction forFaction = this.argAsFaction(0, myFaction); - if (forFaction == null || forFaction == fme.getAutoClaimFor()) { - fme.setAutoClaimFor(null); - msg(TL.COMMAND_AUTOCLAIM_DISABLED); - return; - } + @Override + public void perform() { + Faction forFaction = this.argAsFaction(0, myFaction); + if (forFaction == null || forFaction == fme.getAutoClaimFor()) { + fme.setAutoClaimFor(null); + msg(TL.COMMAND_AUTOCLAIM_DISABLED); + return; + } - if (!fme.canClaimForFaction(forFaction)) { - if (myFaction == forFaction) { - msg(TL.COMMAND_AUTOCLAIM_REQUIREDRANK, Role.MODERATOR.getTranslation()); - } else { - msg(TL.COMMAND_AUTOCLAIM_OTHERFACTION, forFaction.describeTo(fme)); - } + if (!fme.canClaimForFaction(forFaction)) { + if (myFaction == forFaction) { + msg(TL.COMMAND_AUTOCLAIM_REQUIREDRANK, Role.MODERATOR.getTranslation()); + } else { + msg(TL.COMMAND_AUTOCLAIM_OTHERFACTION, forFaction.describeTo(fme)); + } - return; - } + return; + } - fme.setAutoClaimFor(forFaction); + fme.setAutoClaimFor(forFaction); - msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(fme)); - fme.attemptClaim(forFaction, me.getLocation(), true); - } + msg(TL.COMMAND_AUTOCLAIM_ENABLED, forFaction.describeTo(fme)); + fme.attemptClaim(forFaction, me.getLocation(), true); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_AUTOCLAIM_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_AUTOCLAIM_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java index 798914d3..78ba49c9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdAutoHelp.java @@ -1,48 +1,48 @@ -package com.massivecraft.factions.cmd; - -import com.massivecraft.factions.SavageFactions; -import com.massivecraft.factions.zcore.CommandVisibility; -import com.massivecraft.factions.zcore.MCommand; -import com.massivecraft.factions.zcore.util.TL; - -import java.util.ArrayList; - -public class CmdAutoHelp extends MCommand { - - public CmdAutoHelp() { - super(SavageFactions.plugin); - this.aliases.add("?"); - this.aliases.add("h"); - this.aliases.add("help"); - - this.setHelpShort(""); - - this.optionalArgs.put("page", "1"); - } - - @Override - public void perform() { - - if (this.commandChain.size() == 0) { - return; - } - MCommand pcmd = this.commandChain.get(this.commandChain.size() - 1); - - ArrayList lines = new ArrayList<>(); - - lines.addAll(pcmd.helpLong); - - for (MCommand scmd : pcmd.subCommands) { - if (scmd.visibility == CommandVisibility.VISIBLE || (scmd.visibility == CommandVisibility.SECRET && scmd.validSenderPermissions(sender, false))) { - lines.add(scmd.getUseageTemplate(this.commandChain, true)); - } - } - - sendMessage(p.txt.getPage(lines, this.argAsInt(0, 1), TL.COMMAND_AUTOHELP_HELPFOR.toString() + pcmd.aliases.get(0) + "\"")); - } - - @Override - public TL getUsageTranslation() { - return TL.COMMAND_HELP_DESCRIPTION; - } -} +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.SavageFactions; +import com.massivecraft.factions.zcore.CommandVisibility; +import com.massivecraft.factions.zcore.MCommand; +import com.massivecraft.factions.zcore.util.TL; + +import java.util.ArrayList; + +public class CmdAutoHelp extends MCommand { + + public CmdAutoHelp() { + super(SavageFactions.plugin); + this.aliases.add("?"); + this.aliases.add("h"); + this.aliases.add("help"); + + this.setHelpShort(""); + + this.optionalArgs.put("page", "1"); + } + + @Override + public void perform() { + + if (this.commandChain.size() == 0) { + return; + } + MCommand pcmd = this.commandChain.get(this.commandChain.size() - 1); + + ArrayList lines = new ArrayList<>(); + + lines.addAll(pcmd.helpLong); + + for (MCommand scmd : pcmd.subCommands) { + if (scmd.visibility == CommandVisibility.VISIBLE || (scmd.visibility == CommandVisibility.SECRET && scmd.validSenderPermissions(sender, false))) { + lines.add(scmd.getUseageTemplate(this.commandChain, true)); + } + } + + sendMessage(p.txt.getPage(lines, this.argAsInt(0, 1), TL.COMMAND_AUTOHELP_HELPFOR.toString() + pcmd.aliases.get(0) + "\"")); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_HELP_DESCRIPTION; + } +} diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBan.java b/src/main/java/com/massivecraft/factions/cmd/CmdBan.java index 64551254..2bbe9f33 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBan.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBan.java @@ -15,87 +15,87 @@ import java.util.logging.Level; public class CmdBan extends FCommand { - public CmdBan() { - super(); - this.aliases.add("ban"); + public CmdBan() { + super(); + this.aliases.add("ban"); - this.requiredArgs.add("target"); + this.requiredArgs.add("target"); - this.permission = Permission.BAN.node; - this.disableOnLock = true; + this.permission = Permission.BAN.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { + @Override + public void perform() { - // Adds bypass to admins and clean permission check - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.BAN); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "ban"); - return; - } - } + // Adds bypass to admins and clean permission check + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.BAN); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "ban"); + return; + } + } - // Good on permission checks. Now lets just ban the player. - FPlayer target = argAsFPlayer(0); - if (target == null) { - return; // the above method sends a message if fails to find someone. - } + // Good on permission checks. Now lets just ban the player. + FPlayer target = argAsFPlayer(0); + if (target == null) { + return; // the above method sends a message if fails to find someone. + } - if (fme == target) { - // You may not ban yourself - fme.msg(TL.COMMAND_BAN_SELF); - return; - } else if (target.getFaction() == myFaction && target.getRole().value >= fme.getRole().value) { - // You may not ban someone that has same or higher faction rank - fme.msg(TL.COMMAND_BAN_INSUFFICIENTRANK, target.getName()); - return; - } + if (fme == target) { + // You may not ban yourself + fme.msg(TL.COMMAND_BAN_SELF); + return; + } else if (target.getFaction() == myFaction && target.getRole().value >= fme.getRole().value) { + // You may not ban someone that has same or higher faction rank + fme.msg(TL.COMMAND_BAN_INSUFFICIENTRANK, target.getName()); + return; + } - for (BanInfo banInfo : myFaction.getBannedPlayers()) { - if (banInfo.getBanned().equals(target.getId())) { - msg(TL.COMMAND_BAN_ALREADYBANNED); - return; - } - } + for (BanInfo banInfo : myFaction.getBannedPlayers()) { + if (banInfo.getBanned().equals(target.getId())) { + msg(TL.COMMAND_BAN_ALREADYBANNED); + return; + } + } - // Ban the user. - myFaction.ban(target, fme); - myFaction.deinvite(target); // can't hurt + // Ban the user. + myFaction.ban(target, fme); + myFaction.deinvite(target); // can't hurt - // If in same Faction, lets make sure to kick them and throw an event. - if (target.getFaction() == myFaction) { + // If in same Faction, lets make sure to kick them and throw an event. + if (target.getFaction() == myFaction) { - FPlayerLeaveEvent event = new FPlayerLeaveEvent(target, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.BANNED); - Bukkit.getServer().getPluginManager().callEvent(event); + FPlayerLeaveEvent event = new FPlayerLeaveEvent(target, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.BANNED); + Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - // if someone cancels a ban, we'll get people complaining here. So lets log it. - SavageFactions.plugin.log(Level.WARNING, "Attempted to ban {0} but someone cancelled the kick event. This isn't good.", target.getName()); - return; - } + if (event.isCancelled()) { + // if someone cancels a ban, we'll get people complaining here. So lets log it. + SavageFactions.plugin.log(Level.WARNING, "Attempted to ban {0} but someone cancelled the kick event. This isn't good.", target.getName()); + return; + } - // Didn't get cancelled so remove them and reset their invite. - myFaction.removeFPlayer(target); - target.resetFactionData(); - } + // Didn't get cancelled so remove them and reset their invite. + myFaction.removeFPlayer(target); + target.resetFactionData(); + } - // Lets inform the people! - target.msg(TL.COMMAND_BAN_TARGET, myFaction.getTag(target.getFaction())); - myFaction.msg(TL.COMMAND_BAN_BANNED, fme.getName(), target.getName()); - } + // Lets inform the people! + target.msg(TL.COMMAND_BAN_TARGET, myFaction.getTag(target.getFaction())); + myFaction.msg(TL.COMMAND_BAN_BANNED, fme.getName(), target.getName()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_BAN_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BAN_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java b/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java index 42d8c7e5..87154386 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBanlist.java @@ -13,60 +13,60 @@ import java.util.List; public class CmdBanlist extends FCommand { - public CmdBanlist() { - super(); - this.aliases.add("banlist"); - this.aliases.add("bans"); - this.aliases.add("banl"); + public CmdBanlist() { + super(); + this.aliases.add("banlist"); + this.aliases.add("bans"); + this.aliases.add("banl"); - this.optionalArgs.put("faction", "faction"); + this.optionalArgs.put("faction", "faction"); - this.permission = Permission.BAN.node; - this.disableOnLock = true; + this.permission = Permission.BAN.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Faction target = myFaction; - if (!args.isEmpty()) { - target = argAsFaction(0); - } + @Override + public void perform() { + Faction target = myFaction; + if (!args.isEmpty()) { + target = argAsFaction(0); + } - if (target == Factions.getInstance().getWilderness()) { - sender.sendMessage(TL.COMMAND_BANLIST_NOFACTION.toString()); - return; - } + if (target == Factions.getInstance().getWilderness()) { + sender.sendMessage(TL.COMMAND_BANLIST_NOFACTION.toString()); + return; + } - if (target == null) { - sender.sendMessage(TL.COMMAND_BANLIST_INVALID.format(argAsString(0))); - return; - } + if (target == null) { + sender.sendMessage(TL.COMMAND_BANLIST_INVALID.format(argAsString(0))); + return; + } - List lines = new ArrayList<>(); - lines.add(TL.COMMAND_BANLIST_HEADER.format(target.getBannedPlayers().size(), target.getTag(myFaction))); - int i = 1; + List lines = new ArrayList<>(); + lines.add(TL.COMMAND_BANLIST_HEADER.format(target.getBannedPlayers().size(), target.getTag(myFaction))); + int i = 1; - for (BanInfo info : target.getBannedPlayers()) { - FPlayer banned = FPlayers.getInstance().getById(info.getBanned()); - FPlayer banner = FPlayers.getInstance().getById(info.getBanner()); - String timestamp = TL.sdf.format(info.getTime()); + for (BanInfo info : target.getBannedPlayers()) { + FPlayer banned = FPlayers.getInstance().getById(info.getBanned()); + FPlayer banner = FPlayers.getInstance().getById(info.getBanner()); + String timestamp = TL.sdf.format(info.getTime()); - lines.add(TL.COMMAND_BANLIST_ENTRY.format(i, banned.getName(), banner.getName(), timestamp)); - i++; - } + lines.add(TL.COMMAND_BANLIST_ENTRY.format(i, banned.getName(), banner.getName(), timestamp)); + i++; + } - for (String s : lines) { - fme.sendMessage(s); - } - } + for (String s : lines) { + fme.sendMessage(s); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_BANLIST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BANLIST_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBanner.java b/src/main/java/com/massivecraft/factions/cmd/CmdBanner.java index 7f8e6fa6..46960073 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBanner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBanner.java @@ -13,123 +13,123 @@ import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; public class CmdBanner extends FCommand { - public CmdBanner() { - super(); + public CmdBanner() { + super(); - this.aliases.add("banner"); - this.aliases.add("warbanner"); + this.aliases.add("banner"); + this.aliases.add("warbanner"); - this.permission = Permission.BANNER.node; - this.disableOnLock = false; + this.permission = Permission.BANNER.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fbanners.Enabled")) { - msg(TL.COMMAND_BANNER_DISABLED); - return; - } - if (!fme.hasMoney(SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Cost", 5000))) { - msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); - return; - } - takeMoney(fme, SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Cost", 5000)); + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fbanners.Enabled")) { + msg(TL.COMMAND_BANNER_DISABLED); + return; + } + if (!fme.hasMoney(SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Cost", 5000))) { + msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); + return; + } + takeMoney(fme, SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Cost", 5000)); - //ItemStack warBanner = SavageFactions.plugin.createItem(Material.BANNER, 1, (short) 1, SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"), SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore")); - //BannerMeta bannerMeta = (BannerMeta) warBanner.getItemMeta(); - ItemStack warBanner = fme.getFaction().getBanner(); - if (warBanner != null) { - ItemMeta warmeta = warBanner.getItemMeta(); - warmeta.setDisplayName(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"))); - warmeta.setLore(SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore"))); - warBanner.setItemMeta(warmeta); + //ItemStack warBanner = SavageFactions.plugin.createItem(Material.BANNER, 1, (short) 1, SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"), SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore")); + //BannerMeta bannerMeta = (BannerMeta) warBanner.getItemMeta(); + ItemStack warBanner = fme.getFaction().getBanner(); + if (warBanner != null) { + ItemMeta warmeta = warBanner.getItemMeta(); + warmeta.setDisplayName(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"))); + warmeta.setLore(SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore"))); + warBanner.setItemMeta(warmeta); - } else { + } else { - warBanner = SavageFactions.plugin.createItem(SavageFactions.plugin.BANNER, 1, (short) 1, SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"), SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore")); - } - fme.msg(TL.COMMAND_BANNER_SUCCESS); - warBanner.setAmount(1); - me.getInventory().addItem(warBanner); - } + warBanner = SavageFactions.plugin.createItem(SavageFactions.plugin.BANNER, 1, (short) 1, SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"), SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore")); + } + fme.msg(TL.COMMAND_BANNER_SUCCESS); + warBanner.setAmount(1); + me.getInventory().addItem(warBanner); + } - public boolean hasMoney(FPlayer fme, int amt) { - Economy econ = SavageFactions.plugin.getEcon(); - if (econ.getBalance(fme.getPlayer()) >= amt) { - return true; - } else { - fme.msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); - return false; - } - } + public boolean hasMoney(FPlayer fme, int amt) { + Economy econ = SavageFactions.plugin.getEcon(); + if (econ.getBalance(fme.getPlayer()) >= amt) { + return true; + } else { + fme.msg(TL.COMMAND_BANNER_NOTENOUGHMONEY); + return false; + } + } - public void takeMoney(FPlayer fme, int amt) { - if (hasMoney(fme, amt)) { - Economy econ = SavageFactions.plugin.getEcon(); - econ.withdrawPlayer(fme.getPlayer(), amt); - fme.sendMessage(TL.COMMAND_BANNER_MONEYTAKE.toString().replace("{amount}", amt + "")); - } - } + public void takeMoney(FPlayer fme, int amt) { + if (hasMoney(fme, amt)) { + Economy econ = SavageFactions.plugin.getEcon(); + econ.withdrawPlayer(fme.getPlayer(), amt); + fme.sendMessage(TL.COMMAND_BANNER_MONEYTAKE.toString().replace("{amount}", amt + "")); + } + } - public boolean inventoryContains(Inventory inventory, ItemStack item) { - int count = 0; - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - count += items[i].getAmount(); - } - if (count >= item.getAmount()) { - return true; - } - } - return false; - } + public boolean inventoryContains(Inventory inventory, ItemStack item) { + int count = 0; + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + count += items[i].getAmount(); + } + if (count >= item.getAmount()) { + return true; + } + } + return false; + } - public void removeFromInventory(Inventory inventory, ItemStack item) { - int amt = item.getAmount(); - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - if (items[i].getAmount() > amt) { - items[i].setAmount(items[i].getAmount() - amt); - break; - } else if (items[i].getAmount() == amt) { - items[i] = null; - break; - } else { - amt -= items[i].getAmount(); - items[i] = null; - } - } - } - inventory.setContents(items); - } + public void removeFromInventory(Inventory inventory, ItemStack item) { + int amt = item.getAmount(); + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + if (items[i].getAmount() > amt) { + items[i].setAmount(items[i].getAmount() - amt); + break; + } else if (items[i].getAmount() == amt) { + items[i] = null; + break; + } else { + amt -= items[i].getAmount(); + items[i] = null; + } + } + } + inventory.setContents(items); + } - public int getEmptySlots(Player p) { - PlayerInventory inventory = p.getInventory(); - ItemStack[] cont = inventory.getContents(); - int i = 0; - for (ItemStack item : cont) - if (item != null && item.getType() != Material.AIR) { - i++; - } - return 36 - i; - } + public int getEmptySlots(Player p) { + PlayerInventory inventory = p.getInventory(); + ItemStack[] cont = inventory.getContents(); + int i = 0; + for (ItemStack item : cont) + if (item != null && item.getType() != Material.AIR) { + i++; + } + return 36 - i; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_BANNER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BANNER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java index fcbe859f..514a5c67 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBoom.java @@ -6,47 +6,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdBoom extends FCommand { - public CmdBoom() { - super(); - this.aliases.add("noboom"); - this.aliases.add("explosions"); - this.aliases.add("toggleexplosions"); + public CmdBoom() { + super(); + this.aliases.add("noboom"); + this.aliases.add("explosions"); + this.aliases.add("toggleexplosions"); - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "flip"); + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.NO_BOOM.node; - this.disableOnLock = true; + this.permission = Permission.NO_BOOM.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!myFaction.isPeaceful()) { - fme.msg(TL.COMMAND_BOOM_PEACEFULONLY); - return; - } + @Override + public void perform() { + if (!myFaction.isPeaceful()) { + fme.msg(TL.COMMAND_BOOM_PEACEFULONLY); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostNoBoom, TL.COMMAND_BOOM_TOTOGGLE, TL.COMMAND_BOOM_FORTOGGLE)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostNoBoom, TL.COMMAND_BOOM_TOTOGGLE, TL.COMMAND_BOOM_FORTOGGLE)) { + return; + } - myFaction.setPeacefulExplosionsEnabled(this.argAsBool(0, !myFaction.getPeacefulExplosionsEnabled())); + myFaction.setPeacefulExplosionsEnabled(this.argAsBool(0, !myFaction.getPeacefulExplosionsEnabled())); - String enabled = myFaction.noExplosionsInTerritory() ? TL.GENERIC_DISABLED.toString() : TL.GENERIC_ENABLED.toString(); + String enabled = myFaction.noExplosionsInTerritory() ? TL.GENERIC_DISABLED.toString() : TL.GENERIC_ENABLED.toString(); - // Inform - myFaction.msg(TL.COMMAND_BOOM_ENABLED, fme.describeTo(myFaction), enabled); - } + // Inform + myFaction.msg(TL.COMMAND_BOOM_ENABLED, fme.describeTo(myFaction), enabled); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_BOOM_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BOOM_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java index 3dd55678..410d1865 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdBypass.java @@ -6,39 +6,39 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdBypass extends FCommand { - public CmdBypass() { - super(); - this.aliases.add("bypass"); + public CmdBypass() { + super(); + this.aliases.add("bypass"); - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "flip"); + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.BYPASS.node; - this.disableOnLock = false; + this.permission = Permission.BYPASS.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - fme.setIsAdminBypassing(this.argAsBool(0, !fme.isAdminBypassing())); + @Override + public void perform() { + fme.setIsAdminBypassing(this.argAsBool(0, !fme.isAdminBypassing())); - // TODO: Move this to a transient field in the model?? - if (fme.isAdminBypassing()) { - fme.msg(TL.COMMAND_BYPASS_ENABLE.toString()); - SavageFactions.plugin.log(fme.getName() + TL.COMMAND_BYPASS_ENABLELOG.toString()); - } else { - fme.msg(TL.COMMAND_BYPASS_DISABLE.toString()); - SavageFactions.plugin.log(fme.getName() + TL.COMMAND_BYPASS_DISABLELOG.toString()); - } - } + // TODO: Move this to a transient field in the model?? + if (fme.isAdminBypassing()) { + fme.msg(TL.COMMAND_BYPASS_ENABLE.toString()); + SavageFactions.plugin.log(fme.getName() + TL.COMMAND_BYPASS_ENABLELOG.toString()); + } else { + fme.msg(TL.COMMAND_BYPASS_DISABLE.toString()); + SavageFactions.plugin.log(fme.getName() + TL.COMMAND_BYPASS_DISABLELOG.toString()); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_BYPASS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_BYPASS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java index 983868c0..ffda5965 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChat.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChat.java @@ -8,80 +8,80 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdChat extends FCommand { - public CmdChat() { - super(); - this.aliases.add("c"); - this.aliases.add("chat"); + public CmdChat() { + super(); + this.aliases.add("c"); + this.aliases.add("chat"); - //this.requiredArgs.add(""); - this.optionalArgs.put("mode", "next"); + //this.requiredArgs.add(""); + this.optionalArgs.put("mode", "next"); - this.permission = Permission.CHAT.node; - this.disableOnLock = false; + this.permission = Permission.CHAT.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!Conf.factionOnlyChat) { - msg(TL.COMMAND_CHAT_DISABLED.toString()); - return; - } + @Override + public void perform() { + if (!Conf.factionOnlyChat) { + msg(TL.COMMAND_CHAT_DISABLED.toString()); + return; + } - String modeString = this.argAsString(0); - ChatMode modeTarget = fme.getChatMode().getNext(); + String modeString = this.argAsString(0); + ChatMode modeTarget = fme.getChatMode().getNext(); - if (modeString != null) { - modeString = modeString.toLowerCase(); - // Only allow Mods and higher rank to switch to this channel. - if (modeString.startsWith("m")) { - if (!fme.getRole().isAtLeast(Role.MODERATOR)) { - msg(TL.COMMAND_CHAT_MOD_ONLY); - return; - } else modeTarget = ChatMode.MOD; - } else if (modeString.startsWith("p")) { - modeTarget = ChatMode.PUBLIC; - } else if (modeString.startsWith("a")) { - modeTarget = ChatMode.ALLIANCE; - } else if (modeString.startsWith("f")) { - modeTarget = ChatMode.FACTION; - } else if (modeString.startsWith("t")) { - modeTarget = ChatMode.TRUCE; - } else { - msg(TL.COMMAND_CHAT_INVALIDMODE); - return; - } - } + if (modeString != null) { + modeString = modeString.toLowerCase(); + // Only allow Mods and higher rank to switch to this channel. + if (modeString.startsWith("m")) { + if (!fme.getRole().isAtLeast(Role.MODERATOR)) { + msg(TL.COMMAND_CHAT_MOD_ONLY); + return; + } else modeTarget = ChatMode.MOD; + } else if (modeString.startsWith("p")) { + modeTarget = ChatMode.PUBLIC; + } else if (modeString.startsWith("a")) { + modeTarget = ChatMode.ALLIANCE; + } else if (modeString.startsWith("f")) { + modeTarget = ChatMode.FACTION; + } else if (modeString.startsWith("t")) { + modeTarget = ChatMode.TRUCE; + } else { + msg(TL.COMMAND_CHAT_INVALIDMODE); + return; + } + } - fme.setChatMode(modeTarget); + fme.setChatMode(modeTarget); - switch (fme.getChatMode()) { - case MOD: - msg(TL.COMMAND_CHAT_MODE_MOD); - break; - case PUBLIC: - msg(TL.COMMAND_CHAT_MODE_PUBLIC); - break; - case ALLIANCE: - msg(TL.COMMAND_CHAT_MODE_ALLIANCE); - break; - case TRUCE: - msg(TL.COMMAND_CHAT_MODE_TRUCE); - break; - default: - msg(TL.COMMAND_CHAT_MODE_FACTION); - break; - } - } + switch (fme.getChatMode()) { + case MOD: + msg(TL.COMMAND_CHAT_MODE_MOD); + break; + case PUBLIC: + msg(TL.COMMAND_CHAT_MODE_PUBLIC); + break; + case ALLIANCE: + msg(TL.COMMAND_CHAT_MODE_ALLIANCE); + break; + case TRUCE: + msg(TL.COMMAND_CHAT_MODE_TRUCE); + break; + default: + msg(TL.COMMAND_CHAT_MODE_FACTION); + break; + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CHAT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CHAT_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java index f6cd198f..d8d1b4e3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChatSpy.java @@ -6,37 +6,37 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdChatSpy extends FCommand { - public CmdChatSpy() { - super(); - this.aliases.add("chatspy"); + public CmdChatSpy() { + super(); + this.aliases.add("chatspy"); - this.optionalArgs.put("on/off", "flip"); + this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.CHATSPY.node; - this.disableOnLock = false; + this.permission = Permission.CHATSPY.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - fme.setSpyingChat(this.argAsBool(0, !fme.isSpyingChat())); + @Override + public void perform() { + fme.setSpyingChat(this.argAsBool(0, !fme.isSpyingChat())); - if (fme.isSpyingChat()) { - fme.msg(TL.COMMAND_CHATSPY_ENABLE); - SavageFactions.plugin.log(fme.getName() + TL.COMMAND_CHATSPY_ENABLELOG.toString()); - } else { - fme.msg(TL.COMMAND_CHATSPY_DISABLE); - SavageFactions.plugin.log(fme.getName() + TL.COMMAND_CHATSPY_DISABLELOG.toString()); - } - } + if (fme.isSpyingChat()) { + fme.msg(TL.COMMAND_CHATSPY_ENABLE); + SavageFactions.plugin.log(fme.getName() + TL.COMMAND_CHATSPY_ENABLELOG.toString()); + } else { + fme.msg(TL.COMMAND_CHATSPY_DISABLE); + SavageFactions.plugin.log(fme.getName() + TL.COMMAND_CHATSPY_DISABLELOG.toString()); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CHATSPY_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CHATSPY_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java b/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java index 01021f8d..fe153b0a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCheckpoint.java @@ -6,66 +6,66 @@ import com.massivecraft.factions.util.WarmUpUtil; import com.massivecraft.factions.zcore.util.TL; public class CmdCheckpoint extends FCommand { - public CmdCheckpoint() { - super(); - this.aliases.add("checkp"); - this.aliases.add("checkpoint"); - this.aliases.add("cpoint"); + public CmdCheckpoint() { + super(); + this.aliases.add("checkp"); + this.aliases.add("checkpoint"); + this.aliases.add("cpoint"); - this.optionalArgs.put("set", ""); + this.optionalArgs.put("set", ""); - this.permission = Permission.CHECKPOINT.node; - this.disableOnLock = false; + this.permission = Permission.CHECKPOINT.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("checkpoints.Enabled")) { - fme.msg(TL.COMMAND_CHECKPOINT_DISABLED); - return; - } - if (args.size() == 1) { - FLocation myLocation = new FLocation(fme.getPlayer().getLocation()); - Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); - if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == fme.getFaction()) { - fme.getFaction().setCheckpoint(fme.getPlayer().getLocation()); - fme.msg(TL.COMMAND_CHECKPOINT_SET); - return; - } else { - fme.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); - return; - } - } - if (fme.getFaction().getCheckpoint() == null) { - fme.msg(TL.COMMAND_CHECKPOINT_NOT_SET); - return; - } - FLocation checkLocation = new FLocation(fme.getFaction().getCheckpoint()); - Faction checkfaction = Board.getInstance().getFactionAt(checkLocation); + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("checkpoints.Enabled")) { + fme.msg(TL.COMMAND_CHECKPOINT_DISABLED); + return; + } + if (args.size() == 1) { + FLocation myLocation = new FLocation(fme.getPlayer().getLocation()); + Faction myLocFaction = Board.getInstance().getFactionAt(myLocation); + if (myLocFaction == Factions.getInstance().getWilderness() || myLocFaction == fme.getFaction()) { + fme.getFaction().setCheckpoint(fme.getPlayer().getLocation()); + fme.msg(TL.COMMAND_CHECKPOINT_SET); + return; + } else { + fme.msg(TL.COMMAND_CHECKPOINT_INVALIDLOCATION); + return; + } + } + if (fme.getFaction().getCheckpoint() == null) { + fme.msg(TL.COMMAND_CHECKPOINT_NOT_SET); + return; + } + FLocation checkLocation = new FLocation(fme.getFaction().getCheckpoint()); + Faction checkfaction = Board.getInstance().getFactionAt(checkLocation); - if (checkfaction.getId().equals(Factions.getInstance().getWilderness().getId()) || checkfaction.getId().equals(fme.getFaction().getId())) { - fme.msg(TL.COMMAND_CHECKPOINT_GO); - this.doWarmUp(WarmUpUtil.Warmup.CHECKPOINT, TL.WARMUPS_NOTIFY_TELEPORT, "Checkpoint", new Runnable() { - @Override - public void run() { - fme.getPlayer().teleport(fme.getFaction().getCheckpoint()); - } - }, this.p.getConfig().getLong("warmups.f-checkpoint", 0)); - } else { - fme.msg(TL.COMMAND_CHECKPOINT_CLAIMED); - } + if (checkfaction.getId().equals(Factions.getInstance().getWilderness().getId()) || checkfaction.getId().equals(fme.getFaction().getId())) { + fme.msg(TL.COMMAND_CHECKPOINT_GO); + this.doWarmUp(WarmUpUtil.Warmup.CHECKPOINT, TL.WARMUPS_NOTIFY_TELEPORT, "Checkpoint", new Runnable() { + @Override + public void run() { + fme.getPlayer().teleport(fme.getFaction().getCheckpoint()); + } + }, this.p.getConfig().getLong("warmups.f-checkpoint", 0)); + } else { + fme.msg(TL.COMMAND_CHECKPOINT_CLAIMED); + } - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CHECKPOINT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CHECKPOINT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdChest.java b/src/main/java/com/massivecraft/factions/cmd/CmdChest.java index f007b99b..8fcb0d7a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdChest.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdChest.java @@ -9,47 +9,47 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdChest extends FCommand { - public CmdChest() { - this.aliases.add("chest"); - this.aliases.add("pv"); + public CmdChest() { + this.aliases.add("chest"); + this.aliases.add("pv"); - //this.requiredArgs.add(""); + //this.requiredArgs.add(""); - this.permission = Permission.CHEST.node; - this.disableOnLock = false; + this.permission = Permission.CHEST.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { + @Override + public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fchest.Enabled")) { - fme.sendMessage("This command is disabled!"); - return; - } - // This permission check is way too explicit but it's clean - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.CHEST); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "access chest"); - return; - } - } + if (!SavageFactions.plugin.getConfig().getBoolean("fchest.Enabled")) { + fme.sendMessage("This command is disabled!"); + return; + } + // This permission check is way too explicit but it's clean + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.CHEST); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "access chest"); + return; + } + } - me.openInventory(fme.getFaction().getChestInventory()); + me.openInventory(fme.getFaction().getChestInventory()); - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_VAULT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VAULT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java index f0e4077d..9fa20093 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdClaim.java @@ -14,82 +14,82 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdClaim extends FCommand { - public CmdClaim() { - super(); - this.aliases.add("claim"); + public CmdClaim() { + super(); + this.aliases.add("claim"); - //this.requiredArgs.add(""); - this.optionalArgs.put("radius", "1"); - this.optionalArgs.put("faction", "your"); + //this.requiredArgs.add(""); + this.optionalArgs.put("radius", "1"); + this.optionalArgs.put("faction", "your"); - this.permission = Permission.CLAIM.node; - this.disableOnLock = true; + this.permission = Permission.CLAIM.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // Read and validate input - int radius = this.argAsInt(0, 1); // Default to 1 - final Faction forFaction = this.argAsFaction(1, myFaction); // Default to own + @Override + public void perform() { + // Read and validate input + int radius = this.argAsInt(0, 1); // Default to 1 + final Faction forFaction = this.argAsFaction(1, myFaction); // Default to own - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.TERRITORY); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "change faction territory"); - return; - } - } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.TERRITORY); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "change faction territory"); + return; + } + } - if (forFaction.isWilderness()) { - CmdUnclaim cmdUnclaim = SavageFactions.plugin.cmdBase.cmdUnclaim; - cmdUnclaim.execute(sender, args.size() > 1 ? args.subList(0, 1) : args); - return; - } + if (forFaction.isWilderness()) { + CmdUnclaim cmdUnclaim = SavageFactions.plugin.cmdBase.cmdUnclaim; + cmdUnclaim.execute(sender, args.size() > 1 ? args.subList(0, 1) : args); + return; + } - if (radius < 1) { - msg(TL.COMMAND_CLAIM_INVALIDRADIUS); - return; - } + if (radius < 1) { + msg(TL.COMMAND_CLAIM_INVALIDRADIUS); + return; + } - if (radius < 2) { - // single chunk - fme.attemptClaim(forFaction, me.getLocation(), true); - } else { - // radius claim - if (!Permission.CLAIM_RADIUS.has(sender, false)) { - msg(TL.COMMAND_CLAIM_DENIED); - return; - } + if (radius < 2) { + // single chunk + fme.attemptClaim(forFaction, me.getLocation(), true); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(sender, false)) { + msg(TL.COMMAND_CLAIM_DENIED); + return; + } - new SpiralTask(new FLocation(me), radius) { - private final int limit = Conf.radiusClaimFailureLimit - 1; - private int failCount = 0; + new SpiralTask(new FLocation(me), radius) { + private final int limit = Conf.radiusClaimFailureLimit - 1; + private int failCount = 0; - @Override - public boolean work() { - boolean success = fme.attemptClaim(forFaction, this.currentLocation(), true); - if (success) { - failCount = 0; - } else if (failCount++ >= limit) { - this.stop(); - return false; - } + @Override + public boolean work() { + boolean success = fme.attemptClaim(forFaction, this.currentLocation(), true); + if (success) { + failCount = 0; + } else if (failCount++ >= limit) { + this.stop(); + return false; + } - return true; - } - }; - } - } + return true; + } + }; + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CLAIM_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIM_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdClaimAt.java b/src/main/java/com/massivecraft/factions/cmd/CmdClaimAt.java index feee8c76..2b2bf2b3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdClaimAt.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdClaimAt.java @@ -6,35 +6,35 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdClaimAt extends FCommand { - public CmdClaimAt() { - super(); - this.aliases.add("claimat"); + public CmdClaimAt() { + super(); + this.aliases.add("claimat"); - this.requiredArgs.add("world"); - this.requiredArgs.add("x"); - this.requiredArgs.add("z"); + this.requiredArgs.add("world"); + this.requiredArgs.add("x"); + this.requiredArgs.add("z"); - this.permission = Permission.CLAIMAT.node; - this.disableOnLock = true; + this.permission = Permission.CLAIMAT.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - int x = argAsInt(1); - int z = argAsInt(2); - FLocation location = new FLocation(argAsString(0), x, z); - fme.attemptClaim(myFaction, location, true); - } + @Override + public void perform() { + int x = argAsInt(1); + int z = argAsInt(2); + FLocation location = new FLocation(argAsString(0), x, z); + fme.attemptClaim(myFaction, location, true); + } - @Override - public TL getUsageTranslation() { - return null; - } + @Override + public TL getUsageTranslation() { + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdClaimLine.java b/src/main/java/com/massivecraft/factions/cmd/CmdClaimLine.java index e3507db5..fad5124f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdClaimLine.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdClaimLine.java @@ -9,70 +9,70 @@ import org.bukkit.block.BlockFace; public class CmdClaimLine extends FCommand { - public static final BlockFace[] axis = {BlockFace.SOUTH, BlockFace.WEST, BlockFace.NORTH, BlockFace.EAST}; + public static final BlockFace[] axis = {BlockFace.SOUTH, BlockFace.WEST, BlockFace.NORTH, BlockFace.EAST}; - public CmdClaimLine() { + public CmdClaimLine() { - // Aliases - this.aliases.add("claimline"); - this.aliases.add("cl"); + // Aliases + this.aliases.add("claimline"); + this.aliases.add("cl"); - // Args - this.optionalArgs.put("amount", "1"); - this.optionalArgs.put("direction", "facing"); - this.optionalArgs.put("faction", "you"); + // Args + this.optionalArgs.put("amount", "1"); + this.optionalArgs.put("direction", "facing"); + this.optionalArgs.put("faction", "you"); - this.permission = Permission.CLAIM_LINE.node; - this.disableOnLock = true; + this.permission = Permission.CLAIM_LINE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // Args - Integer amount = this.argAsInt(0, 1); // Default to 1 + @Override + public void perform() { + // Args + Integer amount = this.argAsInt(0, 1); // Default to 1 - if (amount > Conf.lineClaimLimit) { - fme.msg(TL.COMMAND_CLAIMLINE_ABOVEMAX, Conf.lineClaimLimit); - return; - } + if (amount > Conf.lineClaimLimit) { + fme.msg(TL.COMMAND_CLAIMLINE_ABOVEMAX, Conf.lineClaimLimit); + return; + } - String direction = this.argAsString(1); - BlockFace blockFace; + String direction = this.argAsString(1); + BlockFace blockFace; - if (direction == null) { - blockFace = axis[Math.round(me.getLocation().getYaw() / 90f) & 0x3]; - } else if (direction.equalsIgnoreCase("north")) { - blockFace = BlockFace.NORTH; - } else if (direction.equalsIgnoreCase("east")) { - blockFace = BlockFace.EAST; - } else if (direction.equalsIgnoreCase("south")) { - blockFace = BlockFace.SOUTH; - } else if (direction.equalsIgnoreCase("west")) { - blockFace = BlockFace.WEST; - } else { - fme.msg(TL.COMMAND_CLAIMLINE_NOTVALID, direction); - return; - } + if (direction == null) { + blockFace = axis[Math.round(me.getLocation().getYaw() / 90f) & 0x3]; + } else if (direction.equalsIgnoreCase("north")) { + blockFace = BlockFace.NORTH; + } else if (direction.equalsIgnoreCase("east")) { + blockFace = BlockFace.EAST; + } else if (direction.equalsIgnoreCase("south")) { + blockFace = BlockFace.SOUTH; + } else if (direction.equalsIgnoreCase("west")) { + blockFace = BlockFace.WEST; + } else { + fme.msg(TL.COMMAND_CLAIMLINE_NOTVALID, direction); + return; + } - final Faction forFaction = this.argAsFaction(2, myFaction); - Location location = me.getLocation(); + final Faction forFaction = this.argAsFaction(2, myFaction); + Location location = me.getLocation(); - // TODO: make this a task like claiming a radius? - for (int i = 0; i < amount; i++) { - fme.attemptClaim(forFaction, location, true); - location = location.add(blockFace.getModX() * 16, 0, blockFace.getModZ() * 16); - } - } + // TODO: make this a task like claiming a radius? + for (int i = 0; i < amount; i++) { + fme.attemptClaim(forFaction, location, true); + location = location.add(blockFace.getModX() * 16, 0, blockFace.getModZ() * 16); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CLAIMLINE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CLAIMLINE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java b/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java index f1aaefca..926df953 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdColeader.java @@ -10,82 +10,82 @@ import mkremins.fanciful.FancyMessage; import org.bukkit.ChatColor; public class CmdColeader extends FCommand { - public CmdColeader() { - super(); - this.aliases.add("co"); - this.aliases.add("setcoleader"); - this.aliases.add("coleader"); - this.aliases.add("setco"); + public CmdColeader() { + super(); + this.aliases.add("co"); + this.aliases.add("setcoleader"); + this.aliases.add("coleader"); + this.aliases.add("setco"); - this.optionalArgs.put("player name", "name"); - //this.optionalArgs.put("", ""); + this.optionalArgs.put("player name", "name"); + //this.optionalArgs.put("", ""); - this.permission = Permission.COLEADER.node; - this.disableOnLock = true; + this.permission = Permission.COLEADER.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = true; - } + senderMustBePlayer = false; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = true; + } - @Override - public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_COLEADER_CANDIDATES.toString()).color(ChatColor.GOLD); - for (FPlayer player : myFaction.getFPlayersWhereRole(Role.NORMAL)) { - String s = player.getName(); - msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " coleader " + s); - } - for (FPlayer player : myFaction.getFPlayersWhereRole(Role.MODERATOR)) { - String s = player.getName(); - msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " coleader " + s); - } + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_COLEADER_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : myFaction.getFPlayersWhereRole(Role.NORMAL)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " coleader " + s); + } + for (FPlayer player : myFaction.getFPlayersWhereRole(Role.MODERATOR)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " coleader " + s); + } - sendFancyMessage(msg); - return; - } + sendFancyMessage(msg); + return; + } - boolean permAny = Permission.COLEADER_ANY.has(sender, false); - Faction targetFaction = you.getFaction(); + boolean permAny = Permission.COLEADER_ANY.has(sender, false); + Faction targetFaction = you.getFaction(); - if (targetFaction != myFaction && !permAny) { - msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(fme, true)); - return; - } + if (targetFaction != myFaction && !permAny) { + msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(fme, true)); + return; + } - if (fme != null && fme.getRole() != Role.LEADER && !permAny) { - msg(TL.COMMAND_COLEADER_NOTADMIN); - return; - } + if (fme != null && fme.getRole() != Role.LEADER && !permAny) { + msg(TL.COMMAND_COLEADER_NOTADMIN); + return; + } - if (you == fme && !permAny) { - msg(TL.COMMAND_COLEADER_SELF); - return; - } + if (you == fme && !permAny) { + msg(TL.COMMAND_COLEADER_SELF); + return; + } - if (you.getRole() == Role.LEADER) { - msg(TL.COMMAND_COLEADER_TARGETISADMIN); - return; - } + if (you.getRole() == Role.LEADER) { + msg(TL.COMMAND_COLEADER_TARGETISADMIN); + return; + } - if (you.getRole() == Role.COLEADER) { - // Revoke - you.setRole(Role.MODERATOR); - targetFaction.msg(TL.COMMAND_COLEADER_REVOKED, you.describeTo(targetFaction, true)); - msg(TL.COMMAND_COLEADER_REVOKES, you.describeTo(fme, true)); - } else { - // Give - you.setRole(Role.COLEADER); - targetFaction.msg(TL.COMMAND_COLEADER_PROMOTED, you.describeTo(targetFaction, true)); - msg(TL.COMMAND_COLEADER_PROMOTES, you.describeTo(fme, true)); - } - } + if (you.getRole() == Role.COLEADER) { + // Revoke + you.setRole(Role.MODERATOR); + targetFaction.msg(TL.COMMAND_COLEADER_REVOKED, you.describeTo(targetFaction, true)); + msg(TL.COMMAND_COLEADER_REVOKES, you.describeTo(fme, true)); + } else { + // Give + you.setRole(Role.COLEADER); + targetFaction.msg(TL.COMMAND_COLEADER_PROMOTED, you.describeTo(targetFaction, true)); + msg(TL.COMMAND_COLEADER_PROMOTES, you.describeTo(fme, true)); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_COLEADER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_COLEADER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java index 6717b53e..3d65283e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdConfig.java @@ -16,234 +16,234 @@ import java.util.Set; public class CmdConfig extends FCommand { - private static HashMap properFieldNames = new HashMap<>(); + private static HashMap properFieldNames = new HashMap<>(); - public CmdConfig() { - super(); - this.aliases.add("config"); + public CmdConfig() { + super(); + this.aliases.add("config"); - this.requiredArgs.add("setting"); - this.requiredArgs.add("value"); - this.errorOnToManyArgs = false; + this.requiredArgs.add("setting"); + this.requiredArgs.add("value"); + this.errorOnToManyArgs = false; - this.permission = Permission.CONFIG.node; - this.disableOnLock = true; + this.permission = Permission.CONFIG.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // store a lookup map of lowercase field names paired with proper capitalization field names - // that way, if the person using this command messes up the capitalization, we can fix that - if (properFieldNames.isEmpty()) { - Field[] fields = Conf.class.getDeclaredFields(); - for (Field field : fields) { - properFieldNames.put(field.getName().toLowerCase(), field.getName()); - } - } + @Override + public void perform() { + // store a lookup map of lowercase field names paired with proper capitalization field names + // that way, if the person using this command messes up the capitalization, we can fix that + if (properFieldNames.isEmpty()) { + Field[] fields = Conf.class.getDeclaredFields(); + for (Field field : fields) { + properFieldNames.put(field.getName().toLowerCase(), field.getName()); + } + } - String field = this.argAsString(0).toLowerCase(); - if (field.startsWith("\"") && field.endsWith("\"")) { - field = field.substring(1, field.length() - 1); - } - String fieldName = properFieldNames.get(field); + String field = this.argAsString(0).toLowerCase(); + if (field.startsWith("\"") && field.endsWith("\"")) { + field = field.substring(1, field.length() - 1); + } + String fieldName = properFieldNames.get(field); - if (fieldName == null || fieldName.isEmpty()) { - msg(TL.COMMAND_CONFIG_NOEXIST, field); - return; - } + if (fieldName == null || fieldName.isEmpty()) { + msg(TL.COMMAND_CONFIG_NOEXIST, field); + return; + } - String success; + String success; - StringBuilder value = new StringBuilder(args.get(1)); - for (int i = 2; i < args.size(); i++) { - value.append(' ').append(args.get(i)); - } + StringBuilder value = new StringBuilder(args.get(1)); + for (int i = 2; i < args.size(); i++) { + value.append(' ').append(args.get(i)); + } - try { - Field target = Conf.class.getField(fieldName); + try { + Field target = Conf.class.getField(fieldName); - // boolean - if (target.getType() == boolean.class) { - boolean targetValue = this.strAsBool(value.toString()); - target.setBoolean(null, targetValue); + // boolean + if (target.getType() == boolean.class) { + boolean targetValue = this.strAsBool(value.toString()); + target.setBoolean(null, targetValue); - if (targetValue) { - success = "\"" + fieldName + TL.COMMAND_CONFIG_SET_TRUE.toString(); - } else { - success = "\"" + fieldName + TL.COMMAND_CONFIG_SET_FALSE.toString(); - } - } + if (targetValue) { + success = "\"" + fieldName + TL.COMMAND_CONFIG_SET_TRUE.toString(); + } else { + success = "\"" + fieldName + TL.COMMAND_CONFIG_SET_FALSE.toString(); + } + } - // int - else if (target.getType() == int.class) { - try { - int intVal = Integer.parseInt(value.toString()); - target.setInt(null, intVal); - success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + intVal + "."; - } catch (NumberFormatException ex) { - sendMessage(TL.COMMAND_CONFIG_INTREQUIRED.format(fieldName)); - return; - } - } + // int + else if (target.getType() == int.class) { + try { + int intVal = Integer.parseInt(value.toString()); + target.setInt(null, intVal); + success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + intVal + "."; + } catch (NumberFormatException ex) { + sendMessage(TL.COMMAND_CONFIG_INTREQUIRED.format(fieldName)); + return; + } + } - // long - else if (target.getType() == long.class) { - try { - long longVal = Long.parseLong(value.toString()); - target.setLong(null, longVal); - success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + longVal + "."; - } catch (NumberFormatException ex) { - sendMessage(TL.COMMAND_CONFIG_LONGREQUIRED.format(fieldName)); - return; - } - } + // long + else if (target.getType() == long.class) { + try { + long longVal = Long.parseLong(value.toString()); + target.setLong(null, longVal); + success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + longVal + "."; + } catch (NumberFormatException ex) { + sendMessage(TL.COMMAND_CONFIG_LONGREQUIRED.format(fieldName)); + return; + } + } - // double - else if (target.getType() == double.class) { - try { - double doubleVal = Double.parseDouble(value.toString()); - target.setDouble(null, doubleVal); - success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + doubleVal + "."; - } catch (NumberFormatException ex) { - sendMessage(TL.COMMAND_CONFIG_DOUBLEREQUIRED.format(fieldName)); - return; - } - } + // double + else if (target.getType() == double.class) { + try { + double doubleVal = Double.parseDouble(value.toString()); + target.setDouble(null, doubleVal); + success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + doubleVal + "."; + } catch (NumberFormatException ex) { + sendMessage(TL.COMMAND_CONFIG_DOUBLEREQUIRED.format(fieldName)); + return; + } + } - // float - else if (target.getType() == float.class) { - try { - float floatVal = Float.parseFloat(value.toString()); - target.setFloat(null, floatVal); - success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + floatVal + "."; - } catch (NumberFormatException ex) { - sendMessage(TL.COMMAND_CONFIG_FLOATREQUIRED.format(fieldName)); - return; - } - } + // float + else if (target.getType() == float.class) { + try { + float floatVal = Float.parseFloat(value.toString()); + target.setFloat(null, floatVal); + success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + floatVal + "."; + } catch (NumberFormatException ex) { + sendMessage(TL.COMMAND_CONFIG_FLOATREQUIRED.format(fieldName)); + return; + } + } - // String - else if (target.getType() == String.class) { - target.set(null, value.toString()); - success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + value + "\"."; - } + // String + else if (target.getType() == String.class) { + target.set(null, value.toString()); + success = "\"" + fieldName + TL.COMMAND_CONFIG_OPTIONSET.toString() + value + "\"."; + } - // ChatColor - else if (target.getType() == ChatColor.class) { - ChatColor newColor = null; - try { - newColor = ChatColor.valueOf(value.toString().toUpperCase()); - } catch (IllegalArgumentException ex) { + // ChatColor + else if (target.getType() == ChatColor.class) { + ChatColor newColor = null; + try { + newColor = ChatColor.valueOf(value.toString().toUpperCase()); + } catch (IllegalArgumentException ex) { - } - if (newColor == null) { - sendMessage(TL.COMMAND_CONFIG_INVALID_COLOUR.format(fieldName, value.toString().toUpperCase())); - return; - } - target.set(null, newColor); - success = "\"" + fieldName + TL.COMMAND_CONFIG_COLOURSET.toString() + value.toString().toUpperCase() + "\"."; - } + } + if (newColor == null) { + sendMessage(TL.COMMAND_CONFIG_INVALID_COLOUR.format(fieldName, value.toString().toUpperCase())); + return; + } + target.set(null, newColor); + success = "\"" + fieldName + TL.COMMAND_CONFIG_COLOURSET.toString() + value.toString().toUpperCase() + "\"."; + } - // Set or other parameterized collection - else if (target.getGenericType() instanceof ParameterizedType) { - ParameterizedType targSet = (ParameterizedType) target.getGenericType(); - Type innerType = targSet.getActualTypeArguments()[0]; + // Set or other parameterized collection + else if (target.getGenericType() instanceof ParameterizedType) { + ParameterizedType targSet = (ParameterizedType) target.getGenericType(); + Type innerType = targSet.getActualTypeArguments()[0]; - // not a Set, somehow, and that should be the only collection we're using in Conf.java - if (targSet.getRawType() != Set.class) { - sendMessage(TL.COMMAND_CONFIG_INVALID_COLLECTION.format(fieldName)); - return; - } + // not a Set, somehow, and that should be the only collection we're using in Conf.java + if (targSet.getRawType() != Set.class) { + sendMessage(TL.COMMAND_CONFIG_INVALID_COLLECTION.format(fieldName)); + return; + } - // Set - else if (innerType == Material.class) { - Material newMat = null; - try { - newMat = Material.valueOf(value.toString().toUpperCase()); - } catch (IllegalArgumentException ex) { + // Set + else if (innerType == Material.class) { + Material newMat = null; + try { + newMat = Material.valueOf(value.toString().toUpperCase()); + } catch (IllegalArgumentException ex) { - } - if (newMat == null) { - sendMessage(TL.COMMAND_CONFIG_INVALID_MATERIAL.format(fieldName, value.toString().toUpperCase())); - return; - } + } + if (newMat == null) { + sendMessage(TL.COMMAND_CONFIG_INVALID_MATERIAL.format(fieldName, value.toString().toUpperCase())); + return; + } - @SuppressWarnings("unchecked") Set matSet = (Set) target.get(null); + @SuppressWarnings("unchecked") Set matSet = (Set) target.get(null); - // Material already present, so remove it - if (matSet.contains(newMat)) { - matSet.remove(newMat); - target.set(null, matSet); - success = TL.COMMAND_CONFIG_MATERIAL_REMOVED.format(fieldName, value.toString().toUpperCase()); - } - // Material not present yet, add it - else { - matSet.add(newMat); - target.set(null, matSet); - success = TL.COMMAND_CONFIG_MATERIAL_ADDED.format(fieldName, value.toString().toUpperCase()); - } - } + // Material already present, so remove it + if (matSet.contains(newMat)) { + matSet.remove(newMat); + target.set(null, matSet); + success = TL.COMMAND_CONFIG_MATERIAL_REMOVED.format(fieldName, value.toString().toUpperCase()); + } + // Material not present yet, add it + else { + matSet.add(newMat); + target.set(null, matSet); + success = TL.COMMAND_CONFIG_MATERIAL_ADDED.format(fieldName, value.toString().toUpperCase()); + } + } - // Set - else if (innerType == String.class) { - @SuppressWarnings("unchecked") Set stringSet = (Set) target.get(null); + // Set + else if (innerType == String.class) { + @SuppressWarnings("unchecked") Set stringSet = (Set) target.get(null); - // String already present, so remove it - if (stringSet.contains(value.toString())) { - stringSet.remove(value.toString()); - target.set(null, stringSet); - success = TL.COMMAND_CONFIG_SET_REMOVED.format(fieldName, value.toString()); - } - // String not present yet, add it - else { - stringSet.add(value.toString()); - target.set(null, stringSet); - success = TL.COMMAND_CONFIG_SET_ADDED.format(fieldName, value.toString()); - } - } + // String already present, so remove it + if (stringSet.contains(value.toString())) { + stringSet.remove(value.toString()); + target.set(null, stringSet); + success = TL.COMMAND_CONFIG_SET_REMOVED.format(fieldName, value.toString()); + } + // String not present yet, add it + else { + stringSet.add(value.toString()); + target.set(null, stringSet); + success = TL.COMMAND_CONFIG_SET_ADDED.format(fieldName, value.toString()); + } + } - // Set of unknown type - else { - sendMessage(TL.COMMAND_CONFIG_INVALID_TYPESET.format(fieldName)); - return; - } - } + // Set of unknown type + else { + sendMessage(TL.COMMAND_CONFIG_INVALID_TYPESET.format(fieldName)); + return; + } + } - // unknown type - else { - sendMessage(TL.COMMAND_CONFIG_ERROR_TYPE.format(fieldName, target.getClass().getName())); - return; - } - } catch (NoSuchFieldException ex) { - sendMessage(TL.COMMAND_CONFIG_ERROR_MATCHING.format(fieldName)); - return; - } catch (IllegalAccessException ex) { - sendMessage(TL.COMMAND_CONFIG_ERROR_SETTING.format(fieldName, value.toString())); - return; - } + // unknown type + else { + sendMessage(TL.COMMAND_CONFIG_ERROR_TYPE.format(fieldName, target.getClass().getName())); + return; + } + } catch (NoSuchFieldException ex) { + sendMessage(TL.COMMAND_CONFIG_ERROR_MATCHING.format(fieldName)); + return; + } catch (IllegalAccessException ex) { + sendMessage(TL.COMMAND_CONFIG_ERROR_SETTING.format(fieldName, value.toString())); + return; + } - if (!success.isEmpty()) { - if (sender instanceof Player) { - sendMessage(success); - SavageFactions.plugin.log(success + TL.COMMAND_CONFIG_LOG.format((Player) sender)); - } else // using SavageFactions.plugin.log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log - { - SavageFactions.plugin.log(success); - } - } - // save change to disk - Conf.save(); - } + if (!success.isEmpty()) { + if (sender instanceof Player) { + sendMessage(success); + SavageFactions.plugin.log(success + TL.COMMAND_CONFIG_LOG.format((Player) sender)); + } else // using SavageFactions.plugin.log() instead of sendMessage if run from server console so that "[Factions v#.#.#]" is prepended in server log + { + SavageFactions.plugin.log(success); + } + } + // save change to disk + Conf.save(); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CONFIG_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CONFIG_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdConvert.java b/src/main/java/com/massivecraft/factions/cmd/CmdConvert.java index bc923ec6..caf90c96 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdConvert.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdConvert.java @@ -9,39 +9,39 @@ import org.bukkit.command.ConsoleCommandSender; public class CmdConvert extends FCommand { - public CmdConvert() { - this.aliases.add("convert"); + public CmdConvert() { + this.aliases.add("convert"); - this.permission = Permission.CONVERT.node; + this.permission = Permission.CONVERT.node; - this.requiredArgs.add("[MYSQL|JSON]"); - } + this.requiredArgs.add("[MYSQL|JSON]"); + } - @Override - public void perform() { - if (!(this.sender instanceof ConsoleCommandSender)) { - this.sender.sendMessage(TL.GENERIC_CONSOLEONLY.toString()); - } - Backend nb = Backend.valueOf(this.argAsString(0).toUpperCase()); - if (nb == Conf.backEnd) { - this.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_RUNNING.toString()); - return; - } - switch (nb) { - case JSON: - FactionsJSON.convertTo(); - break; - default: - this.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_INVALID.toString()); - return; + @Override + public void perform() { + if (!(this.sender instanceof ConsoleCommandSender)) { + this.sender.sendMessage(TL.GENERIC_CONSOLEONLY.toString()); + } + Backend nb = Backend.valueOf(this.argAsString(0).toUpperCase()); + if (nb == Conf.backEnd) { + this.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_RUNNING.toString()); + return; + } + switch (nb) { + case JSON: + FactionsJSON.convertTo(); + break; + default: + this.sender.sendMessage(TL.COMMAND_CONVERT_BACKEND_INVALID.toString()); + return; - } - Conf.backEnd = nb; - } + } + Conf.backEnd = nb; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CONVERT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CONVERT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java b/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java index e6b3bad3..506ad1b0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCoords.java @@ -7,36 +7,36 @@ import org.bukkit.Location; public class CmdCoords extends FCommand { - public CmdCoords() { - super(); - this.aliases.add("coords"); - this.aliases.add("coord"); + public CmdCoords() { + super(); + this.aliases.add("coords"); + this.aliases.add("coord"); - this.permission = Permission.COORD.node; - this.disableOnLock = true; + this.permission = Permission.COORD.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Location location = fme.getPlayer().getLocation(); - String message = TL.COMMAND_COORDS_MESSAGE.toString().replace("{player}", fme.getPlayer().getDisplayName()).replace("{x}", (int) location.getX() + "") - .replace("{y}", (int) location.getY() + "").replace("{z}", (int) location.getZ() + "").replace("{world}", location.getWorld().getName()); - for (FPlayer fPlayer : fme.getFaction().getFPlayers()) { - fPlayer.sendMessage(message); - } - } + @Override + public void perform() { + Location location = fme.getPlayer().getLocation(); + String message = TL.COMMAND_COORDS_MESSAGE.toString().replace("{player}", fme.getPlayer().getDisplayName()).replace("{x}", (int) location.getX() + "") + .replace("{y}", (int) location.getY() + "").replace("{z}", (int) location.getZ() + "").replace("{world}", location.getWorld().getName()); + for (FPlayer fPlayer : fme.getFaction().getFPlayers()) { + fPlayer.sendMessage(message); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_COORDS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_COORDS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java index ad7455b1..48140931 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdCreate.java @@ -14,105 +14,105 @@ import java.util.ArrayList; public class CmdCreate extends FCommand { - public CmdCreate() { - super(); - this.aliases.add("create"); + public CmdCreate() { + super(); + this.aliases.add("create"); - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); - this.permission = Permission.CREATE.node; - this.disableOnLock = true; + this.permission = Permission.CREATE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - String tag = this.argAsString(0); + @Override + public void perform() { + String tag = this.argAsString(0); - if (fme.hasFaction()) { - msg(TL.COMMAND_CREATE_MUSTLEAVE); - return; - } + if (fme.hasFaction()) { + msg(TL.COMMAND_CREATE_MUSTLEAVE); + return; + } - if (Factions.getInstance().isTagTaken(tag)) { - msg(TL.COMMAND_CREATE_INUSE); - return; - } + if (Factions.getInstance().isTagTaken(tag)) { + msg(TL.COMMAND_CREATE_INUSE); + return; + } - ArrayList tagValidationErrors = MiscUtil.validateTag(tag); - if (tagValidationErrors.size() > 0) { - sendMessage(tagValidationErrors); - return; - } + ArrayList tagValidationErrors = MiscUtil.validateTag(tag); + if (tagValidationErrors.size() > 0) { + sendMessage(tagValidationErrors); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if (!canAffordCommand(Conf.econCostCreate, TL.COMMAND_CREATE_TOCREATE.toString())) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!canAffordCommand(Conf.econCostCreate, TL.COMMAND_CREATE_TOCREATE.toString())) { + return; + } - // trigger the faction creation event (cancellable) - FactionCreateEvent createEvent = new FactionCreateEvent(me, tag); - Bukkit.getServer().getPluginManager().callEvent(createEvent); - if (createEvent.isCancelled()) { - return; - } + // trigger the faction creation event (cancellable) + FactionCreateEvent createEvent = new FactionCreateEvent(me, tag); + Bukkit.getServer().getPluginManager().callEvent(createEvent); + if (createEvent.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (!payForCommand(Conf.econCostCreate, TL.COMMAND_CREATE_TOCREATE, TL.COMMAND_CREATE_FORCREATE)) { - return; - } + // then make 'em pay (if applicable) + if (!payForCommand(Conf.econCostCreate, TL.COMMAND_CREATE_TOCREATE, TL.COMMAND_CREATE_FORCREATE)) { + return; + } - Faction faction = Factions.getInstance().createFaction(); + Faction faction = Factions.getInstance().createFaction(); - // TODO: Why would this even happen??? Auto increment clash?? - if (faction == null) { - msg(TL.COMMAND_CREATE_ERROR); - return; - } + // TODO: Why would this even happen??? Auto increment clash?? + if (faction == null) { + msg(TL.COMMAND_CREATE_ERROR); + return; + } - // finish setting up the Faction - faction.setTag(tag); + // finish setting up the Faction + faction.setTag(tag); - // trigger the faction join event for the creator - FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(me), faction, FPlayerJoinEvent.PlayerJoinReason.CREATE); - Bukkit.getServer().getPluginManager().callEvent(joinEvent); - // join event cannot be cancelled or you'll have an empty faction + // trigger the faction join event for the creator + FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(me), faction, FPlayerJoinEvent.PlayerJoinReason.CREATE); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + // join event cannot be cancelled or you'll have an empty faction - // finish setting up the FPlayer - fme.setFaction(faction); - // We should consider adding the role just AFTER joining the faction. - // That way we don't have to mess up deleting more stuff. - // And prevent the user from being returned to NORMAL after deleting his old faction. - fme.setRole(Role.LEADER); - if (SavageFactions.plugin.getConfig().getBoolean("faction-creation-broadcast", true)) { - for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { - follower.msg(TL.COMMAND_CREATE_CREATED, fme.describeTo(follower, true), faction.getTag(follower)); - } - } - msg(TL.COMMAND_CREATE_YOUSHOULD, p.cmdBase.cmdDescription.getUseageTemplate()); + // finish setting up the FPlayer + fme.setFaction(faction); + // We should consider adding the role just AFTER joining the faction. + // That way we don't have to mess up deleting more stuff. + // And prevent the user from being returned to NORMAL after deleting his old faction. + fme.setRole(Role.LEADER); + if (SavageFactions.plugin.getConfig().getBoolean("faction-creation-broadcast", true)) { + for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { + follower.msg(TL.COMMAND_CREATE_CREATED, fme.describeTo(follower, true), faction.getTag(follower)); + } + } + msg(TL.COMMAND_CREATE_YOUSHOULD, p.cmdBase.cmdDescription.getUseageTemplate()); - if (Conf.logFactionCreate) { - SavageFactions.plugin.log(fme.getName() + TL.COMMAND_CREATE_CREATEDLOG.toString() + tag); - } - if (SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { - this.fme.msg(TL.COMMAND_PAYPALSET_CREATED); - } - if (Conf.useCustomDefaultPermissions) { - faction.setDefaultPerms(); - if (Conf.usePermissionHints) - this.fme.msg(TL.COMMAND_HINT_PERMISSION); - } - } + if (Conf.logFactionCreate) { + SavageFactions.plugin.log(fme.getName() + TL.COMMAND_CREATE_CREATEDLOG.toString() + tag); + } + if (SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { + this.fme.msg(TL.COMMAND_PAYPALSET_CREATED); + } + if (Conf.useCustomDefaultPermissions) { + faction.setDefaultPerms(); + if (Conf.usePermissionHints) + this.fme.msg(TL.COMMAND_HINT_PERMISSION); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_CREATE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_CREATE_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java index 62c2b72e..51948c2c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDeinvite.java @@ -13,62 +13,62 @@ import org.bukkit.ChatColor; public class CmdDeinvite extends FCommand { - public CmdDeinvite() { - super(); - this.aliases.add("deinvite"); - this.aliases.add("deinv"); + public CmdDeinvite() { + super(); + this.aliases.add("deinvite"); + this.aliases.add("deinv"); - this.optionalArgs.put("player name", "name"); - //this.optionalArgs.put("", ""); + this.optionalArgs.put("player name", "name"); + //this.optionalArgs.put("", ""); - this.permission = Permission.DEINVITE.node; - this.disableOnLock = true; + this.permission = Permission.DEINVITE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.INVITE); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); - return; - } - } - if (you == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); - for (String id : myFaction.getInvites()) { - FPlayer fp = FPlayers.getInstance().getById(id); - String name = fp != null ? fp.getName() : id; - msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_DEINVITE_CLICKTODEINVITE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name); - } - sendFancyMessage(msg); - return; - } + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.INVITE); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); + return; + } + } + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_DEINVITE_CANDEINVITE.toString()).color(ChatColor.GOLD); + for (String id : myFaction.getInvites()) { + FPlayer fp = FPlayers.getInstance().getById(id); + String name = fp != null ? fp.getName() : id; + msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_DEINVITE_CLICKTODEINVITE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name); + } + sendFancyMessage(msg); + return; + } - if (you.getFaction() == myFaction) { - msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), myFaction.getTag()); - msg(TL.COMMAND_DEINVITE_MIGHTWANT, p.cmdBase.cmdKick.getUseageTemplate(false)); - return; - } + if (you.getFaction() == myFaction) { + msg(TL.COMMAND_DEINVITE_ALREADYMEMBER, you.getName(), myFaction.getTag()); + msg(TL.COMMAND_DEINVITE_MIGHTWANT, p.cmdBase.cmdKick.getUseageTemplate(false)); + return; + } - myFaction.deinvite(you); + myFaction.deinvite(you); - you.msg(TL.COMMAND_DEINVITE_REVOKED, fme.describeTo(you), myFaction.describeTo(you)); + you.msg(TL.COMMAND_DEINVITE_REVOKED, fme.describeTo(you), myFaction.describeTo(you)); - myFaction.msg(TL.COMMAND_DEINVITE_REVOKES, fme.describeTo(myFaction), you.describeTo(myFaction)); - } + myFaction.msg(TL.COMMAND_DEINVITE_REVOKES, fme.describeTo(myFaction), you.describeTo(myFaction)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_DEINVITE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DEINVITE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDelFWarp.java b/src/main/java/com/massivecraft/factions/cmd/CmdDelFWarp.java index 6f592b3f..1249266f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDelFWarp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDelFWarp.java @@ -7,39 +7,39 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdDelFWarp extends FCommand { - public CmdDelFWarp() { - super(); - this.aliases.add("delwarp"); - this.aliases.add("dw"); - this.aliases.add("deletewarp"); - this.requiredArgs.add("warp name"); - this.senderMustBeMember = true; - this.senderMustBeModerator = true; - this.senderMustBePlayer = true; - this.permission = Permission.SETWARP.node; + public CmdDelFWarp() { + super(); + this.aliases.add("delwarp"); + this.aliases.add("dw"); + this.aliases.add("deletewarp"); + this.requiredArgs.add("warp name"); + this.senderMustBeMember = true; + this.senderMustBeModerator = true; + this.senderMustBePlayer = true; + this.permission = Permission.SETWARP.node; - } + } - @Override - public void perform() { - String warp = argAsString(0); - if (myFaction.isWarp(warp)) { - if (!transact(fme)) { - return; - } - myFaction.removeWarp(warp); - fme.msg(TL.COMMAND_DELFWARP_DELETED, warp); - } else { - fme.msg(TL.COMMAND_DELFWARP_INVALID, warp); - } - } + @Override + public void perform() { + String warp = argAsString(0); + if (myFaction.isWarp(warp)) { + if (!transact(fme)) { + return; + } + myFaction.removeWarp(warp); + fme.msg(TL.COMMAND_DELFWARP_DELETED, warp); + } else { + fme.msg(TL.COMMAND_DELFWARP_INVALID, warp); + } + } - private boolean transact(FPlayer player) { - return !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || payForCommand(SavageFactions.plugin.getConfig().getDouble("warp-cost.delwarp", 5), TL.COMMAND_DELFWARP_TODELETE.toString(), TL.COMMAND_DELFWARP_FORDELETE.toString()); - } + private boolean transact(FPlayer player) { + return !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || payForCommand(SavageFactions.plugin.getConfig().getDouble("warp-cost.delwarp", 5), TL.COMMAND_DELFWARP_TODELETE.toString(), TL.COMMAND_DELFWARP_FORDELETE.toString()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_DELFWARP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DELFWARP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDemote.java b/src/main/java/com/massivecraft/factions/cmd/CmdDemote.java index 2890d2f5..0378de1c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDemote.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDemote.java @@ -2,8 +2,8 @@ package com.massivecraft.factions.cmd; public class CmdDemote extends FPromoteCommand { - public CmdDemote() { - aliases.add("demote"); - this.relative = -1; - } + public CmdDemote() { + aliases.add("demote"); + this.relative = -1; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java index a0e6d00a..fe272298 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDescription.java @@ -9,53 +9,53 @@ import com.massivecraft.factions.zcore.util.TextUtil; public class CmdDescription extends FCommand { - public CmdDescription() { - super(); - this.aliases.add("desc"); - this.aliases.add("description"); + public CmdDescription() { + super(); + this.aliases.add("desc"); + this.aliases.add("description"); - this.requiredArgs.add("desc"); - this.errorOnToManyArgs = false; - //this.optionalArgs + this.requiredArgs.add("desc"); + this.errorOnToManyArgs = false; + //this.optionalArgs - this.permission = Permission.DESCRIPTION.node; - this.disableOnLock = true; + this.permission = Permission.DESCRIPTION.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostDesc, TL.COMMAND_DESCRIPTION_TOCHANGE, TL.COMMAND_DESCRIPTION_FORCHANGE)) { - return; - } + @Override + public void perform() { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostDesc, TL.COMMAND_DESCRIPTION_TOCHANGE, TL.COMMAND_DESCRIPTION_FORCHANGE)) { + return; + } - // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up - // And replace all the % because it messes with string formatting and this is easy way around that. - myFaction.setDescription(TextUtil.implode(args, " ").replaceAll("%", "").replaceAll("(&([a-f0-9klmnor]))", "& $2")); + // since "&" color tags seem to work even through plain old FPlayer.sendMessage() for some reason, we need to break those up + // And replace all the % because it messes with string formatting and this is easy way around that. + myFaction.setDescription(TextUtil.implode(args, " ").replaceAll("%", "").replaceAll("(&([a-f0-9klmnor]))", "& $2")); - if (!Conf.broadcastDescriptionChanges) { - fme.msg(TL.COMMAND_DESCRIPTION_CHANGED, myFaction.describeTo(fme)); - fme.sendMessage(myFaction.getDescription()); - return; - } + if (!Conf.broadcastDescriptionChanges) { + fme.msg(TL.COMMAND_DESCRIPTION_CHANGED, myFaction.describeTo(fme)); + fme.sendMessage(myFaction.getDescription()); + return; + } - // Broadcast the description to everyone - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg(TL.COMMAND_DESCRIPTION_CHANGES, myFaction.describeTo(fplayer)); - fplayer.sendMessage(myFaction.getDescription()); // players can inject "&" or "`" or "" or whatever in their description; &k is particularly interesting looking - } - } + // Broadcast the description to everyone + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.COMMAND_DESCRIPTION_CHANGES, myFaction.describeTo(fplayer)); + fplayer.sendMessage(myFaction.getDescription()); // players can inject "&" or "`" or "" or whatever in their description; &k is particularly interesting looking + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_DESCRIPTION_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DESCRIPTION_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java index 2ad00c4d..2f806816 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdDisband.java @@ -16,99 +16,99 @@ import java.util.HashMap; public class CmdDisband extends FCommand { - private static HashMap disbandMap = new HashMap<>(); + private static HashMap disbandMap = new HashMap<>(); - public CmdDisband() { - super(); - this.aliases.add("disband"); + public CmdDisband() { + super(); + this.aliases.add("disband"); - //this.requiredArgs.add(""); - this.optionalArgs.put("faction tag", "yours"); + //this.requiredArgs.add(""); + this.optionalArgs.put("faction tag", "yours"); - this.permission = Permission.DISBAND.node; - this.disableOnLock = true; + this.permission = Permission.DISBAND.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - // The faction, default to your own.. but null if console sender. - Faction faction = this.argAsFaction(0, fme == null ? null : myFaction); - if (faction == null) { - return; - } + @Override + public void perform() { + // The faction, default to your own.. but null if console sender. + Faction faction = this.argAsFaction(0, fme == null ? null : myFaction); + if (faction == null) { + return; + } - boolean isMyFaction = fme != null && faction == myFaction; + boolean isMyFaction = fme != null && faction == myFaction; - if (isMyFaction) { - if (!assertMinRole(Role.LEADER)) { - return; - } - } else { - if (!Permission.DISBAND_ANY.has(sender, true)) { - return; - } - } + if (isMyFaction) { + if (!assertMinRole(Role.LEADER)) { + return; + } + } else { + if (!Permission.DISBAND_ANY.has(sender, true)) { + return; + } + } - if (!fme.isAdminBypassing()) { - Access access = faction.getAccess(fme, PermissableAction.DISBAND); - if (fme.getRole() != Role.LEADER && faction.getFPlayerLeader() != fme && access != Access.ALLOW) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); - return; - } - } + if (!fme.isAdminBypassing()) { + Access access = faction.getAccess(fme, PermissableAction.DISBAND); + if (fme.getRole() != Role.LEADER && faction.getFPlayerLeader() != fme && access != Access.ALLOW) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "disband " + faction.getTag()); + return; + } + } - if (!faction.isNormal()) { - msg(TL.COMMAND_DISBAND_IMMUTABLE.toString()); - return; - } - if (faction.isPermanent()) { - msg(TL.COMMAND_DISBAND_MARKEDPERMANENT.toString()); - return; - } + if (!faction.isNormal()) { + msg(TL.COMMAND_DISBAND_IMMUTABLE.toString()); + return; + } + if (faction.isPermanent()) { + msg(TL.COMMAND_DISBAND_MARKEDPERMANENT.toString()); + return; + } - // check for tnt before disbanding. + // check for tnt before disbanding. - if (!disbandMap.containsKey(me.getUniqueId().toString()) && faction.getTnt() > 0) { - msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + "")); - disbandMap.put(me.getUniqueId().toString(), faction.getId()); - Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - disbandMap.remove(me.getUniqueId().toString()); - } - }, 200L); - } else if (faction.getId().equals(disbandMap.get(me.getUniqueId().toString())) || faction.getTnt() == 0) { - if (SavageFactions.plugin.getConfig().getBoolean("faction-disband-broadcast", true)) { - for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { - String amountString = senderIsConsole ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(follower); - UtilFly.checkFly(this.fme, Board.getInstance().getFactionAt(new FLocation(follower))); - if (follower.getFaction() == faction) { - follower.msg(TL.COMMAND_DISBAND_BROADCAST_YOURS, amountString); - } else { - follower.msg(TL.COMMAND_DISBAND_BROADCAST_NOTYOURS, amountString, faction.getTag(follower)); - } - } - faction.disband(me, PlayerDisbandReason.COMMAND); - } else { - faction.disband(me, PlayerDisbandReason.COMMAND); - me.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); - } - } - } + if (!disbandMap.containsKey(me.getUniqueId().toString()) && faction.getTnt() > 0) { + msg(TL.COMMAND_DISBAND_CONFIRM.toString().replace("{tnt}", faction.getTnt() + "")); + disbandMap.put(me.getUniqueId().toString(), faction.getId()); + Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + disbandMap.remove(me.getUniqueId().toString()); + } + }, 200L); + } else if (faction.getId().equals(disbandMap.get(me.getUniqueId().toString())) || faction.getTnt() == 0) { + if (SavageFactions.plugin.getConfig().getBoolean("faction-disband-broadcast", true)) { + for (FPlayer follower : FPlayers.getInstance().getOnlinePlayers()) { + String amountString = senderIsConsole ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(follower); + UtilFly.checkFly(this.fme, Board.getInstance().getFactionAt(new FLocation(follower))); + if (follower.getFaction() == faction) { + follower.msg(TL.COMMAND_DISBAND_BROADCAST_YOURS, amountString); + } else { + follower.msg(TL.COMMAND_DISBAND_BROADCAST_NOTYOURS, amountString, faction.getTag(follower)); + } + } + faction.disband(me, PlayerDisbandReason.COMMAND); + } else { + faction.disband(me, PlayerDisbandReason.COMMAND); + me.sendMessage(String.valueOf(TL.COMMAND_DISBAND_PLAYER)); + } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_DISBAND_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_DISBAND_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java b/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java index 21a4bac4..de8c13cc 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFWarp.java @@ -16,78 +16,78 @@ import java.util.UUID; public class CmdFWarp extends FCommand { - public CmdFWarp() { - super(); - this.aliases.add("warp"); - this.aliases.add("warps"); - this.optionalArgs.put("warpname", "warpname"); - this.optionalArgs.put("password", "password"); + public CmdFWarp() { + super(); + this.aliases.add("warp"); + this.aliases.add("warps"); + this.optionalArgs.put("warpname", "warpname"); + this.optionalArgs.put("password", "password"); - this.permission = Permission.WARP.node; - this.senderMustBeMember = true; - this.senderMustBeModerator = false; - } + this.permission = Permission.WARP.node; + this.senderMustBeMember = true; + this.senderMustBeModerator = false; + } - @Override - public void perform() { - //TODO: check if in combat. - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.WARP); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "use warps"); - return; - } - } + @Override + public void perform() { + //TODO: check if in combat. + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.WARP); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "use warps"); + return; + } + } - if (args.size() == 0) { - WarpGUI warpGUI = new WarpGUI(fme); - warpGUI.build(); + if (args.size() == 0) { + WarpGUI warpGUI = new WarpGUI(fme); + warpGUI.build(); - me.openInventory(warpGUI.getInventory()); - } else if (args.size() > 2) { - fme.msg(TL.COMMAND_FWARP_COMMANDFORMAT); - } else { - final String warpName = argAsString(0); - final String passwordAttempt = argAsString(1); + me.openInventory(warpGUI.getInventory()); + } else if (args.size() > 2) { + fme.msg(TL.COMMAND_FWARP_COMMANDFORMAT); + } else { + final String warpName = argAsString(0); + final String passwordAttempt = argAsString(1); - if (myFaction.isWarp(argAsString(0))) { + if (myFaction.isWarp(argAsString(0))) { - // Check if requires password and if so, check if valid. CASE SENSITIVE - if (myFaction.hasWarpPassword(warpName) && !myFaction.isWarpPassword(warpName, passwordAttempt)) { - fme.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); - return; - } + // Check if requires password and if so, check if valid. CASE SENSITIVE + if (myFaction.hasWarpPassword(warpName) && !myFaction.isWarpPassword(warpName, passwordAttempt)) { + fme.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); + return; + } - // Check transaction AFTER password check. - if (!transact(fme)) { - return; - } - final FPlayer fPlayer = fme; - final UUID uuid = fme.getPlayer().getUniqueId(); - this.doWarmUp(WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warpName, new Runnable() { - @Override - public void run() { - Player player = Bukkit.getPlayer(uuid); - if (player != null) { - player.teleport(fPlayer.getFaction().getWarp(warpName).getLocation()); - fPlayer.msg(TL.COMMAND_FWARP_WARPED, warpName); - } - } - }, this.p.getConfig().getLong("warmups.f-warp", 0)); - } else { - fme.msg(TL.COMMAND_FWARP_INVALID_WARP, warpName); - } - } - } + // Check transaction AFTER password check. + if (!transact(fme)) { + return; + } + final FPlayer fPlayer = fme; + final UUID uuid = fme.getPlayer().getUniqueId(); + this.doWarmUp(WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warpName, new Runnable() { + @Override + public void run() { + Player player = Bukkit.getPlayer(uuid); + if (player != null) { + player.teleport(fPlayer.getFaction().getWarp(warpName).getLocation()); + fPlayer.msg(TL.COMMAND_FWARP_WARPED, warpName); + } + } + }, this.p.getConfig().getLong("warmups.f-warp", 0)); + } else { + fme.msg(TL.COMMAND_FWARP_INVALID_WARP, warpName); + } + } + } - private boolean transact(FPlayer player) { - return !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || payForCommand(SavageFactions.plugin.getConfig().getDouble("warp-cost.warp", 5), TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); - } + private boolean transact(FPlayer player) { + return !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || payForCommand(SavageFactions.plugin.getConfig().getDouble("warp-cost.warp", 5), TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_FWARP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_FWARP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFly.java b/src/main/java/com/massivecraft/factions/cmd/CmdFly.java index b9f737b6..d5072e82 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFly.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFly.java @@ -22,230 +22,230 @@ import java.util.concurrent.ConcurrentHashMap; public class CmdFly extends FCommand { - public static ConcurrentHashMap flyMap = new ConcurrentHashMap(); - public static int id = -1; - public static int flyid = -1; + public static ConcurrentHashMap flyMap = new ConcurrentHashMap(); + public static int id = -1; + public static int flyid = -1; - public CmdFly() { - super(); - this.aliases.add("fly"); + public CmdFly() { + super(); + this.aliases.add("fly"); - this.optionalArgs.put("on/off", "flip"); + this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.FLY.node; - this.senderMustBeMember = true; - this.senderMustBeModerator = false; - } + this.permission = Permission.FLY.node; + this.senderMustBeMember = true; + this.senderMustBeModerator = false; + } - public static void startParticles() { - // Just a secondary check. - if (!SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enabled")) { - return; - } + public static void startParticles() { + // Just a secondary check. + if (!SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enabled")) { + return; + } - id = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - for (String name : flyMap.keySet()) { - Player player = Bukkit.getPlayer(name); - if (player == null) { - continue; - } - if (!player.isFlying()) { - continue; - } - if (!SavageFactions.plugin.mc17) { - if (player.getGameMode() == GameMode.SPECTATOR) { - continue; - } - } + id = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + for (String name : flyMap.keySet()) { + Player player = Bukkit.getPlayer(name); + if (player == null) { + continue; + } + if (!player.isFlying()) { + continue; + } + if (!SavageFactions.plugin.mc17) { + if (player.getGameMode() == GameMode.SPECTATOR) { + continue; + } + } - if (FPlayers.getInstance().getByPlayer(player).isVanished()) { - // Actually, vanished players (such as admins) should not display particles to prevent others from knowing their vanished assistance for moderation. - // But we can keep it as a config. - if (SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enable-While-Vanished")) { - return; - } - continue; - } - if (SavageFactions.plugin.useNonPacketParticles) { - // 1.9+ based servers will use the built in particleAPI instead of packet based. - // any particle amount higher than 0 made them go everywhere, and the offset at 0 was not working. - // So setting the amount to 0 spawns 1 in the precise location - player.getWorld().spawnParticle(Particle.CLOUD, player.getLocation().add(0, -0.35, 0), 0); - } else { - ParticleEffect.CLOUD.display((float) 0, (float) 0, (float) 0, (float) 0, 3, player.getLocation().add(0, -0.35, 0), 16); - } + if (FPlayers.getInstance().getByPlayer(player).isVanished()) { + // Actually, vanished players (such as admins) should not display particles to prevent others from knowing their vanished assistance for moderation. + // But we can keep it as a config. + if (SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enable-While-Vanished")) { + return; + } + continue; + } + if (SavageFactions.plugin.useNonPacketParticles) { + // 1.9+ based servers will use the built in particleAPI instead of packet based. + // any particle amount higher than 0 made them go everywhere, and the offset at 0 was not working. + // So setting the amount to 0 spawns 1 in the precise location + player.getWorld().spawnParticle(Particle.CLOUD, player.getLocation().add(0, -0.35, 0), 0); + } else { + ParticleEffect.CLOUD.display((float) 0, (float) 0, (float) 0, (float) 0, 3, player.getLocation().add(0, -0.35, 0), 16); + } - } - if (flyMap.keySet().size() == 0) { - Bukkit.getScheduler().cancelTask(id); - id = -1; - } - } - }, 10L, 3L); - } + } + if (flyMap.keySet().size() == 0) { + Bukkit.getScheduler().cancelTask(id); + id = -1; + } + } + }, 10L, 3L); + } - public static void startFlyCheck() { - flyid = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() throws ConcurrentModificationException { //threw the exception for now, until I recode fly :( Cringe. - checkTaskState(); - if (flyMap.keySet().size() != 0) { - for (String name : flyMap.keySet()) { - if (name == null) { - continue; - } - Player player = Bukkit.getPlayer(name); - if (player == null) { - continue; - } - if (!player.isFlying()) { - continue; - } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - if (fPlayer == null) { - continue; - } - if (player.getGameMode() == GameMode.CREATIVE) { - continue; - } - if (!SavageFactions.plugin.mc17 && player.getGameMode() == GameMode.SPECTATOR) { - continue; - } - Faction myFaction = fPlayer.getFaction(); - if (myFaction.isWilderness()) { - fPlayer.setFlying(false); - flyMap.remove(name); - continue; - } - if (fPlayer.checkIfNearbyEnemies()) { - continue; - } - FLocation myFloc = new FLocation(player.getLocation()); - Faction toFac = Board.getInstance().getFactionAt(myFloc); - if (Board.getInstance().getFactionAt(myFloc) != myFaction) { - if (!checkBypassPerms(fPlayer, player, toFac)) { - fPlayer.setFlying(false); - flyMap.remove(name); - continue; - } - } + public static void startFlyCheck() { + flyid = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() throws ConcurrentModificationException { //threw the exception for now, until I recode fly :( Cringe. + checkTaskState(); + if (flyMap.keySet().size() != 0) { + for (String name : flyMap.keySet()) { + if (name == null) { + continue; + } + Player player = Bukkit.getPlayer(name); + if (player == null) { + continue; + } + if (!player.isFlying()) { + continue; + } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (fPlayer == null) { + continue; + } + if (player.getGameMode() == GameMode.CREATIVE) { + continue; + } + if (!SavageFactions.plugin.mc17 && player.getGameMode() == GameMode.SPECTATOR) { + continue; + } + Faction myFaction = fPlayer.getFaction(); + if (myFaction.isWilderness()) { + fPlayer.setFlying(false); + flyMap.remove(name); + continue; + } + if (fPlayer.checkIfNearbyEnemies()) { + continue; + } + FLocation myFloc = new FLocation(player.getLocation()); + Faction toFac = Board.getInstance().getFactionAt(myFloc); + if (Board.getInstance().getFactionAt(myFloc) != myFaction) { + if (!checkBypassPerms(fPlayer, player, toFac)) { + fPlayer.setFlying(false); + flyMap.remove(name); + continue; + } + } - } - } + } + } - } - }, 20L, 20L); - } + } + }, 20L, 20L); + } - private static boolean checkBypassPerms(FPlayer fme, Player me, Faction toFac) { - if (toFac != fme.getFaction()) { - if (!me.hasPermission("factions.fly.wilderness") && toFac.isWilderness() || !me.hasPermission("factions.fly.safezone") && toFac.isSafeZone() || !me.hasPermission("factions.fly.warzone") && toFac.isWarZone()) { - fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); - return false; - } - Access access = toFac.getAccess(fme, PermissableAction.FLY); - if ((!(me.hasPermission("factions.fly.enemy") || access == Access.ALLOW)) && toFac.getRelationTo(fme.getFaction()) == Relation.ENEMY) { - fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); - return false; - } - if (!(me.hasPermission("factions.fly.ally") || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.ALLY) { - fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); - return false; - } - if (!(me.hasPermission("factions.fly.truce") || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.TRUCE) { - fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); - return false; - } + private static boolean checkBypassPerms(FPlayer fme, Player me, Faction toFac) { + if (toFac != fme.getFaction()) { + if (!me.hasPermission("factions.fly.wilderness") && toFac.isWilderness() || !me.hasPermission("factions.fly.safezone") && toFac.isSafeZone() || !me.hasPermission("factions.fly.warzone") && toFac.isWarZone()) { + fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + return false; + } + Access access = toFac.getAccess(fme, PermissableAction.FLY); + if ((!(me.hasPermission("factions.fly.enemy") || access == Access.ALLOW)) && toFac.getRelationTo(fme.getFaction()) == Relation.ENEMY) { + fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + return false; + } + if (!(me.hasPermission("factions.fly.ally") || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.ALLY) { + fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + return false; + } + if (!(me.hasPermission("factions.fly.truce") || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.TRUCE) { + fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + return false; + } - if (!(me.hasPermission("factions.fly.neutral") || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.NEUTRAL && !isSystemFaction(toFac)) { - fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); - return false; - } - return me.hasPermission("factions.fly") && access != Access.DENY; - } - return true; - } + if (!(me.hasPermission("factions.fly.neutral") || access == Access.ALLOW) && toFac.getRelationTo(fme.getFaction()) == Relation.NEUTRAL && !isSystemFaction(toFac)) { + fme.msg(TL.COMMAND_FLY_NO_ACCESS, toFac.getTag(fme)); + return false; + } + return me.hasPermission("factions.fly") && access != Access.DENY; + } + return true; + } - public static Boolean isSystemFaction(Faction faction) { - return faction.isSafeZone() || - faction.isWarZone() || - faction.isWilderness(); - } + public static Boolean isSystemFaction(Faction faction) { + return faction.isSafeZone() || + faction.isWarZone() || + faction.isWilderness(); + } - public static void checkTaskState() { - if (flyMap.keySet().size() == 0) { - Bukkit.getScheduler().cancelTask(flyid); - flyid = -1; - } - } + public static void checkTaskState() { + if (flyMap.keySet().size() == 0) { + Bukkit.getScheduler().cancelTask(flyid); + flyid = -1; + } + } - public boolean isInFlightChecker(Player player) { - return flyMap.containsKey(player.getName()); - } + public boolean isInFlightChecker(Player player) { + return flyMap.containsKey(player.getName()); + } - @Override - public void perform() { - // Disabled by default. - if (!SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight", false)) { - fme.msg(TL.COMMAND_FLY_DISABLED); - return; - } + @Override + public void perform() { + // Disabled by default. + if (!SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight", false)) { + fme.msg(TL.COMMAND_FLY_DISABLED); + return; + } - FLocation myfloc = new FLocation(me.getLocation()); - Faction toFac = Board.getInstance().getFactionAt(myfloc); - if (!checkBypassPerms(fme, me, toFac)) return; - List entities = this.me.getNearbyEntities(16.0D, 256.0D, 16.0D); + FLocation myfloc = new FLocation(me.getLocation()); + Faction toFac = Board.getInstance().getFactionAt(myfloc); + if (!checkBypassPerms(fme, me, toFac)) return; + List entities = this.me.getNearbyEntities(16.0D, 256.0D, 16.0D); - for (int i = 0; i <= entities.size() - 1; ++i) { - if (entities.get(i) instanceof Player) { - Player eplayer = (Player) entities.get(i); - FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); - if (efplayer.getRelationTo(this.fme) == Relation.ENEMY && !efplayer.isStealthEnabled()) { - this.fme.msg(TL.COMMAND_FLY_CHECK_ENEMY); - return; - } - } - } + for (int i = 0; i <= entities.size() - 1; ++i) { + if (entities.get(i) instanceof Player) { + Player eplayer = (Player) entities.get(i); + FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); + if (efplayer.getRelationTo(this.fme) == Relation.ENEMY && !efplayer.isStealthEnabled()) { + this.fme.msg(TL.COMMAND_FLY_CHECK_ENEMY); + return; + } + } + } - if (args.size() == 0) { - toggleFlight(!fme.isFlying(), me); - } else if (args.size() == 1) { - toggleFlight(argAsBool(0), me); - } - } + if (args.size() == 0) { + toggleFlight(!fme.isFlying(), me); + } else if (args.size() == 1) { + toggleFlight(argAsBool(0), me); + } + } - private void toggleFlight(final boolean toggle, final Player player) { - if (!toggle) { - fme.setFlying(false); - flyMap.remove(player.getName()); - return; - } + private void toggleFlight(final boolean toggle, final Player player) { + if (!toggle) { + fme.setFlying(false); + flyMap.remove(player.getName()); + return; + } - if (fme.canFlyAtLocation()) + if (fme.canFlyAtLocation()) - this.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", new Runnable() { - @Override - public void run() { - fme.setFlying(true); - flyMap.put(player.getName(), true); - if (id == -1) { - if (SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enabled")) { - startParticles(); - } - } - if (flyid == -1) { - startFlyCheck(); - } - } - }, this.p.getConfig().getLong("warmups.f-fly", 0)); - } + this.doWarmUp(WarmUpUtil.Warmup.FLIGHT, TL.WARMUPS_NOTIFY_FLIGHT, "Fly", new Runnable() { + @Override + public void run() { + fme.setFlying(true); + flyMap.put(player.getName(), true); + if (id == -1) { + if (SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enabled")) { + startParticles(); + } + } + if (flyid == -1) { + startFlyCheck(); + } + } + }, this.p.getConfig().getLong("warmups.f-fly", 0)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_FLY_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_FLY_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdFocus.java b/src/main/java/com/massivecraft/factions/cmd/CmdFocus.java index b01ceb6e..09d8e105 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdFocus.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdFocus.java @@ -7,48 +7,48 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdFocus - extends FCommand { - public CmdFocus() { - aliases.add("focus"); + extends FCommand { + public CmdFocus() { + aliases.add("focus"); - requiredArgs.add("player"); + requiredArgs.add("player"); - permission = Permission.FOCUS.node; + permission = Permission.FOCUS.node; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("ffocus.Enabled")) { - fme.msg(TL.GENERIC_DISABLED); - return; - } - FPlayer target = argAsFPlayer(0); - if (target == null) { - return; - } - if (target.getFaction().getId().equalsIgnoreCase(myFaction.getId())) { - fme.msg(TL.COMMAND_FOCUS_SAMEFACTION); - return; - } - if ((myFaction.getFocused() != null) && (myFaction.getFocused().equalsIgnoreCase(target.getName()))) { - myFaction.setFocused(null); - myFaction.msg(TL.COMMAND_FOCUS_NO_LONGER, target.getName()); - FTeamWrapper.updatePrefixes(target.getFaction()); - return; - } - myFaction.msg(TL.COMMAND_FOCUS_FOCUSING, target.getName()); - myFaction.setFocused(target.getName()); - FTeamWrapper.updatePrefixes(target.getFaction()); - } + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("ffocus.Enabled")) { + fme.msg(TL.GENERIC_DISABLED); + return; + } + FPlayer target = argAsFPlayer(0); + if (target == null) { + return; + } + if (target.getFaction().getId().equalsIgnoreCase(myFaction.getId())) { + fme.msg(TL.COMMAND_FOCUS_SAMEFACTION); + return; + } + if ((myFaction.getFocused() != null) && (myFaction.getFocused().equalsIgnoreCase(target.getName()))) { + myFaction.setFocused(null); + myFaction.msg(TL.COMMAND_FOCUS_NO_LONGER, target.getName()); + FTeamWrapper.updatePrefixes(target.getFaction()); + return; + } + myFaction.msg(TL.COMMAND_FOCUS_FOCUSING, target.getName()); + myFaction.setFocused(target.getName()); + FTeamWrapper.updatePrefixes(target.getFaction()); + } - public TL getUsageTranslation() { - return TL.COMMAND_FOCUS_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_FOCUS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdGetVault.java b/src/main/java/com/massivecraft/factions/cmd/CmdGetVault.java index a2029688..a1a73848 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdGetVault.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdGetVault.java @@ -9,70 +9,70 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class CmdGetVault extends FCommand { - public CmdGetVault() { - super(); + public CmdGetVault() { + super(); - this.aliases.add("getvault"); + this.aliases.add("getvault"); - this.permission = Permission.GETVAULT.node; - this.disableOnLock = true; + this.permission = Permission.GETVAULT.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fvault.Enabled")) { - fme.sendMessage("This command is disabled!"); - return; - } - Location vaultLocation = fme.getFaction().getVault(); - ItemStack vault = SavageFactions.plugin.createItem(Material.CHEST, 1, (short) 0, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fvault.Item.Name")), SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fvault.Item.Lore"))); + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fvault.Enabled")) { + fme.sendMessage("This command is disabled!"); + return; + } + Location vaultLocation = fme.getFaction().getVault(); + ItemStack vault = SavageFactions.plugin.createItem(Material.CHEST, 1, (short) 0, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fvault.Item.Name")), SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fvault.Item.Lore"))); - //check if vault is set - if (vaultLocation != null) { - fme.msg(TL.COMMAND_GETVAULT_ALREADYSET); - return; - } + //check if vault is set + if (vaultLocation != null) { + fme.msg(TL.COMMAND_GETVAULT_ALREADYSET); + return; + } - //has enough money? - int amount = SavageFactions.plugin.getConfig().getInt("fvault.Price"); - if (!fme.hasMoney(amount)) { - return; - } + //has enough money? + int amount = SavageFactions.plugin.getConfig().getInt("fvault.Price"); + if (!fme.hasMoney(amount)) { + return; + } - //success :) - fme.takeMoney(amount); - me.getInventory().addItem(vault); - fme.msg(TL.COMMAND_GETVAULT_RECEIVE); + //success :) + fme.takeMoney(amount); + me.getInventory().addItem(vault); + fme.msg(TL.COMMAND_GETVAULT_RECEIVE); - } + } - public boolean inventoryContains(Inventory inventory, ItemStack item) { - int count = 0; - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - count += items[i].getAmount(); - } - if (count >= item.getAmount()) { - return true; - } - } - return false; - } + public boolean inventoryContains(Inventory inventory, ItemStack item) { + int count = 0; + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + count += items[i].getAmount(); + } + if (count >= item.getAmount()) { + return true; + } + } + return false; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_GETVAULT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_GETVAULT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java index e46084f5..5b7bd34b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHelp.java @@ -13,207 +13,207 @@ import java.util.List; public class CmdHelp extends FCommand { - public ArrayList> helpPages; + public ArrayList> helpPages; - public CmdHelp() { - super(); - this.aliases.add("help"); - this.aliases.add("h"); - this.aliases.add("?"); + public CmdHelp() { + super(); + this.aliases.add("help"); + this.aliases.add("h"); + this.aliases.add("?"); - //this.requiredArgs.add(""); - this.optionalArgs.put("page", "1"); + //this.requiredArgs.add(""); + this.optionalArgs.put("page", "1"); - this.permission = Permission.HELP.node; - this.disableOnLock = false; + this.permission = Permission.HELP.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - //----------------------------------------------// - // Build the help pages - //----------------------------------------------// + //----------------------------------------------// + // Build the help pages + //----------------------------------------------// - @Override - public void perform() { - if (SavageFactions.plugin.getConfig().getBoolean("use-old-help", true)) { - if (helpPages == null) { - updateHelp(); - } + @Override + public void perform() { + if (SavageFactions.plugin.getConfig().getBoolean("use-old-help", true)) { + if (helpPages == null) { + updateHelp(); + } - int page = this.argAsInt(0, 1); - sendMessage(p.txt.titleize("Factions Help (" + page + "/" + helpPages.size() + ")")); + int page = this.argAsInt(0, 1); + sendMessage(p.txt.titleize("Factions Help (" + page + "/" + helpPages.size() + ")")); - page -= 1; + page -= 1; - if (page < 0 || page >= helpPages.size()) { - msg(TL.COMMAND_HELP_404.format(String.valueOf(page))); - return; - } - sendMessage(helpPages.get(page)); - return; - } - ConfigurationSection help = SavageFactions.plugin.getConfig().getConfigurationSection("help"); - if (help == null) { - help = SavageFactions.plugin.getConfig().createSection("help"); // create new help section - List error = new ArrayList<>(); - error.add("&cUpdate help messages in config.yml!"); - error.add("&cSet use-old-help for legacy help messages"); - help.set("'1'", error); // add default error messages - } - String pageArg = this.argAsString(0, "1"); - List page = help.getStringList(pageArg); - if (page == null || page.isEmpty()) { - msg(TL.COMMAND_HELP_404.format(pageArg)); - return; - } - for (String helpLine : page) { - sendMessage(SavageFactions.plugin.txt.parse(helpLine)); - } - } + if (page < 0 || page >= helpPages.size()) { + msg(TL.COMMAND_HELP_404.format(String.valueOf(page))); + return; + } + sendMessage(helpPages.get(page)); + return; + } + ConfigurationSection help = SavageFactions.plugin.getConfig().getConfigurationSection("help"); + if (help == null) { + help = SavageFactions.plugin.getConfig().createSection("help"); // create new help section + List error = new ArrayList<>(); + error.add("&cUpdate help messages in config.yml!"); + error.add("&cSet use-old-help for legacy help messages"); + help.set("'1'", error); // add default error messages + } + String pageArg = this.argAsString(0, "1"); + List page = help.getStringList(pageArg); + if (page == null || page.isEmpty()) { + msg(TL.COMMAND_HELP_404.format(pageArg)); + return; + } + for (String helpLine : page) { + sendMessage(SavageFactions.plugin.txt.parse(helpLine)); + } + } - public void updateHelp() { - helpPages = new ArrayList<>(); - ArrayList pageLines; + public void updateHelp() { + helpPages = new ArrayList<>(); + ArrayList pageLines; - pageLines = new ArrayList<>(); - pageLines.add(p.cmdBase.cmdHelp.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdList.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdShow.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdPower.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdJoin.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdLeave.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdChat.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdToggleAllianceChat.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdHome.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_NEXTCREATE.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.cmdBase.cmdHelp.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdList.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdShow.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPower.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdJoin.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdLeave.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdChat.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdToggleAllianceChat.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdHome.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_NEXTCREATE.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.cmdBase.cmdCreate.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdDescription.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdTag.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_INVITATIONS.toString())); - pageLines.add(p.cmdBase.cmdOpen.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdInvite.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdDeinvite.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_HOME.toString())); - pageLines.add(p.cmdBase.cmdSethome.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.cmdBase.cmdCreate.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdDescription.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdTag.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_INVITATIONS.toString())); + pageLines.add(p.cmdBase.cmdOpen.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdInvite.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdDeinvite.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_HOME.toString())); + pageLines.add(p.cmdBase.cmdSethome.getUseageTemplate(true)); + helpPages.add(pageLines); - if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) { - pageLines = new ArrayList<>(); - pageLines.add(""); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_BANK_1.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_BANK_2.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_BANK_3.toString())); - pageLines.add(""); - pageLines.add(p.cmdBase.cmdMoney.getUseageTemplate(true)); - pageLines.add(""); - pageLines.add(""); - pageLines.add(""); - helpPages.add(pageLines); - } + if (Econ.isSetup() && Conf.econEnabled && Conf.bankEnabled) { + pageLines = new ArrayList<>(); + pageLines.add(""); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_BANK_1.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_BANK_2.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_BANK_3.toString())); + pageLines.add(""); + pageLines.add(p.cmdBase.cmdMoney.getUseageTemplate(true)); + pageLines.add(""); + pageLines.add(""); + pageLines.add(""); + helpPages.add(pageLines); + } - pageLines = new ArrayList<>(); - pageLines.add(p.cmdBase.cmdClaim.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdAutoClaim.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdUnclaim.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdUnclaimall.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdKick.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdMod.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdAdmin.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdTitle.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdSB.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdSeeChunk.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdStatus.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PLAYERTITLES.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.cmdBase.cmdClaim.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdAutoClaim.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdUnclaim.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdUnclaimall.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdKick.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdMod.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdAdmin.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdTitle.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdSB.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdSeeChunk.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdStatus.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PLAYERTITLES.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.cmdBase.cmdMap.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdBoom.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdOwner.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdOwnerList.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_OWNERSHIP_1.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_OWNERSHIP_2.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_OWNERSHIP_3.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.cmdBase.cmdMap.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdBoom.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdOwner.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdOwnerList.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_OWNERSHIP_1.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_OWNERSHIP_2.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_OWNERSHIP_3.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.cmdBase.cmdDisband.getUseageTemplate(true)); - pageLines.add(""); - pageLines.add(p.cmdBase.cmdRelationAlly.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdRelationNeutral.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdRelationEnemy.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_1.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_2.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_3.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_4.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.cmdBase.cmdDisband.getUseageTemplate(true)); + pageLines.add(""); + pageLines.add(p.cmdBase.cmdRelationAlly.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdRelationNeutral.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdRelationEnemy.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_1.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_2.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_3.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_4.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_5.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_6.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_7.toString())); - pageLines.add(TL.COMMAND_HELP_RELATIONS_8.toString()); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_9.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_10.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_11.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_12.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_13.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_5.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_6.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_7.toString())); + pageLines.add(TL.COMMAND_HELP_RELATIONS_8.toString()); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_9.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_10.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_11.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_12.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_RELATIONS_13.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_1.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_2.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_3.toString())); - pageLines.add(TL.COMMAND_HELP_PERMISSIONS_4.toString()); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_5.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_6.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_7.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_8.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_9.toString())); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_1.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_2.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_3.toString())); + pageLines.add(TL.COMMAND_HELP_PERMISSIONS_4.toString()); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_5.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_6.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_7.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_8.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_PERMISSIONS_9.toString())); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(TL.COMMAND_HELP_MOAR_1.toString()); - pageLines.add(p.cmdBase.cmdBypass.getUseageTemplate(true)); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_ADMIN_1.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_ADMIN_2.toString())); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_ADMIN_3.toString())); - pageLines.add(p.cmdBase.cmdSafeunclaimall.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdWarunclaimall.getUseageTemplate(true)); - //TODO:TL - pageLines.add(p.txt.parse("Note: " + p.cmdBase.cmdUnclaim.getUseageTemplate(false) + SavageFactions.plugin.txt.parse("") + " works on safe/war zones as well.")); - pageLines.add(p.cmdBase.cmdPeaceful.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(TL.COMMAND_HELP_MOAR_1.toString()); + pageLines.add(p.cmdBase.cmdBypass.getUseageTemplate(true)); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_ADMIN_1.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_ADMIN_2.toString())); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_ADMIN_3.toString())); + pageLines.add(p.cmdBase.cmdSafeunclaimall.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdWarunclaimall.getUseageTemplate(true)); + //TODO:TL + pageLines.add(p.txt.parse("Note: " + p.cmdBase.cmdUnclaim.getUseageTemplate(false) + SavageFactions.plugin.txt.parse("") + " works on safe/war zones as well.")); + pageLines.add(p.cmdBase.cmdPeaceful.getUseageTemplate(true)); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_MOAR_2.toString())); - pageLines.add(p.cmdBase.cmdChatSpy.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdPermanent.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdPermanentPower.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdPowerBoost.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdConfig.getUseageTemplate(true)); - helpPages.add(pageLines); + pageLines = new ArrayList<>(); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_MOAR_2.toString())); + pageLines.add(p.cmdBase.cmdChatSpy.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPermanent.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPermanentPower.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdPowerBoost.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdConfig.getUseageTemplate(true)); + helpPages.add(pageLines); - pageLines = new ArrayList<>(); - pageLines.add(p.txt.parse(TL.COMMAND_HELP_MOAR_3.toString())); - pageLines.add(p.cmdBase.cmdLock.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdReload.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdSaveAll.getUseageTemplate(true)); - pageLines.add(p.cmdBase.cmdVersion.getUseageTemplate(true)); - helpPages.add(pageLines); - } + pageLines = new ArrayList<>(); + pageLines.add(p.txt.parse(TL.COMMAND_HELP_MOAR_3.toString())); + pageLines.add(p.cmdBase.cmdLock.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdReload.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdSaveAll.getUseageTemplate(true)); + pageLines.add(p.cmdBase.cmdVersion.getUseageTemplate(true)); + helpPages.add(pageLines); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_HELP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_HELP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java index 1ec5fed7..e680f552 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdHome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdHome.java @@ -20,130 +20,130 @@ import java.util.List; public class CmdHome extends FCommand { - public CmdHome() { - super(); - this.aliases.add("home"); + public CmdHome() { + super(); + this.aliases.add("home"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - this.permission = Permission.HOME.node; - this.disableOnLock = false; + this.permission = Permission.HOME.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // TODO: Hide this command on help also. - if (!Conf.homesEnabled) { - fme.msg(TL.COMMAND_HOME_DISABLED); - return; - } + @Override + public void perform() { + // TODO: Hide this command on help also. + if (!Conf.homesEnabled) { + fme.msg(TL.COMMAND_HOME_DISABLED); + return; + } - if (!Conf.homesTeleportCommandEnabled) { - fme.msg(TL.COMMAND_HOME_TELEPORTDISABLED); - return; - } - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.HOME); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "teleport home"); - return; - } - } + if (!Conf.homesTeleportCommandEnabled) { + fme.msg(TL.COMMAND_HOME_TELEPORTDISABLED); + return; + } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.HOME); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "teleport home"); + return; + } + } - if (!myFaction.hasHome()) { - fme.msg(TL.COMMAND_HOME_NOHOME.toString() + (fme.getRole().value < Role.MODERATOR.value ? TL.GENERIC_ASKYOURLEADER.toString() : TL.GENERIC_YOUSHOULD.toString())); - fme.sendMessage(p.cmdBase.cmdSethome.getUseageTemplate()); - return; - } + if (!myFaction.hasHome()) { + fme.msg(TL.COMMAND_HOME_NOHOME.toString() + (fme.getRole().value < Role.MODERATOR.value ? TL.GENERIC_ASKYOURLEADER.toString() : TL.GENERIC_YOUSHOULD.toString())); + fme.sendMessage(p.cmdBase.cmdSethome.getUseageTemplate()); + return; + } - if (!Conf.homesTeleportAllowedFromEnemyTerritory && fme.isInEnemyTerritory()) { - fme.msg(TL.COMMAND_HOME_INENEMY); - return; - } + if (!Conf.homesTeleportAllowedFromEnemyTerritory && fme.isInEnemyTerritory()) { + fme.msg(TL.COMMAND_HOME_INENEMY); + return; + } - if (!Conf.homesTeleportAllowedFromDifferentWorld && me.getWorld().getUID() != myFaction.getHome().getWorld().getUID()) { - fme.msg(TL.COMMAND_HOME_WRONGWORLD); - return; - } + if (!Conf.homesTeleportAllowedFromDifferentWorld && me.getWorld().getUID() != myFaction.getHome().getWorld().getUID()) { + fme.msg(TL.COMMAND_HOME_WRONGWORLD); + return; + } - Faction faction = Board.getInstance().getFactionAt(new FLocation(me.getLocation())); - final Location loc = me.getLocation().clone(); + Faction faction = Board.getInstance().getFactionAt(new FLocation(me.getLocation())); + final Location loc = me.getLocation().clone(); - // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby - if (Conf.homesTeleportAllowedEnemyDistance > 0 && - !faction.isSafeZone() && - (!fme.isInOwnTerritory() || (fme.isInOwnTerritory() && !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))) { - World w = loc.getWorld(); - double x = loc.getX(); - double y = loc.getY(); - double z = loc.getZ(); + // if player is not in a safe zone or their own faction territory, only allow teleport if no enemies are nearby + if (Conf.homesTeleportAllowedEnemyDistance > 0 && + !faction.isSafeZone() && + (!fme.isInOwnTerritory() || (fme.isInOwnTerritory() && !Conf.homesTeleportIgnoreEnemiesIfInOwnTerritory))) { + World w = loc.getWorld(); + double x = loc.getX(); + double y = loc.getY(); + double z = loc.getZ(); - for (Player p : me.getServer().getOnlinePlayers()) { - if (p == null || !p.isOnline() || p.isDead() || p == me || p.getWorld() != w) { - continue; - } + for (Player p : me.getServer().getOnlinePlayers()) { + if (p == null || !p.isOnline() || p.isDead() || p == me || p.getWorld() != w) { + continue; + } - FPlayer fp = FPlayers.getInstance().getByPlayer(p); - if (fme.getRelationTo(fp) != Relation.ENEMY || fp.isVanished()) { - continue; - } + FPlayer fp = FPlayers.getInstance().getByPlayer(p); + if (fme.getRelationTo(fp) != Relation.ENEMY || fp.isVanished()) { + continue; + } - Location l = p.getLocation(); - double dx = Math.abs(x - l.getX()); - double dy = Math.abs(y - l.getY()); - double dz = Math.abs(z - l.getZ()); - double max = Conf.homesTeleportAllowedEnemyDistance; + Location l = p.getLocation(); + double dx = Math.abs(x - l.getX()); + double dy = Math.abs(y - l.getY()); + double dz = Math.abs(z - l.getZ()); + double max = Conf.homesTeleportAllowedEnemyDistance; - // box-shaped distance check - if (dx > max || dy > max || dz > max) { - continue; - } + // box-shaped distance check + if (dx > max || dy > max || dz > max) { + continue; + } - fme.msg(TL.COMMAND_HOME_ENEMYNEAR, String.valueOf(Conf.homesTeleportAllowedEnemyDistance)); - return; - } - } + fme.msg(TL.COMMAND_HOME_ENEMYNEAR, String.valueOf(Conf.homesTeleportAllowedEnemyDistance)); + return; + } + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostHome, TL.COMMAND_HOME_TOTELEPORT.toString(), TL.COMMAND_HOME_FORTELEPORT.toString())) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostHome, TL.COMMAND_HOME_TOTELEPORT.toString(), TL.COMMAND_HOME_FORTELEPORT.toString())) { + return; + } - // if Essentials teleport handling is enabled and available, pass the teleport off to it (for delay and cooldown) - if (Essentials.handleTeleport(me, myFaction.getHome())) { - return; - } + // if Essentials teleport handling is enabled and available, pass the teleport off to it (for delay and cooldown) + if (Essentials.handleTeleport(me, myFaction.getHome())) { + return; + } - this.doWarmUp(WarmUpUtil.Warmup.HOME, TL.WARMUPS_NOTIFY_TELEPORT, "Home", new Runnable() { - @Override - public void run() { - // Create a smoke effect - if (Conf.homesTeleportCommandSmokeEffectEnabled) { - List smokeLocations = new ArrayList<>(); - smokeLocations.add(loc); - smokeLocations.add(loc.add(0, 1, 0)); - smokeLocations.add(CmdHome.this.myFaction.getHome()); - smokeLocations.add(CmdHome.this.myFaction.getHome().clone().add(0, 1, 0)); - SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); - } + this.doWarmUp(WarmUpUtil.Warmup.HOME, TL.WARMUPS_NOTIFY_TELEPORT, "Home", new Runnable() { + @Override + public void run() { + // Create a smoke effect + if (Conf.homesTeleportCommandSmokeEffectEnabled) { + List smokeLocations = new ArrayList<>(); + smokeLocations.add(loc); + smokeLocations.add(loc.add(0, 1, 0)); + smokeLocations.add(CmdHome.this.myFaction.getHome()); + smokeLocations.add(CmdHome.this.myFaction.getHome().clone().add(0, 1, 0)); + SmokeUtil.spawnCloudRandom(smokeLocations, Conf.homesTeleportCommandSmokeEffectThickness); + } - CmdHome.this.me.teleport(CmdHome.this.myFaction.getHome()); - } - }, this.p.getConfig().getLong("warmups.f-home", 0)); - } + CmdHome.this.me.teleport(CmdHome.this.myFaction.getHome()); + } + }, this.p.getConfig().getLong("warmups.f-home", 0)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_HOME_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_HOME_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java b/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java index 5e465e4a..4660844f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInspect.java @@ -4,37 +4,37 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdInspect extends FCommand { - public CmdInspect() { - super(); - this.aliases.add("inspect"); - this.aliases.add("ins"); + public CmdInspect() { + super(); + this.aliases.add("inspect"); + this.aliases.add("ins"); - this.permission = Permission.INSPECT.node; - this.disableOnLock = true; + this.permission = Permission.INSPECT.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (fme.isInspectMode()) { - fme.setInspectMode(false); - msg(TL.COMMAND_INSPECT_DISABLED_MSG); - } else { - fme.setInspectMode(true); - msg(TL.COMMAND_INSPECT_ENABLED); - } + @Override + public void perform() { + if (fme.isInspectMode()) { + fme.setInspectMode(false); + msg(TL.COMMAND_INSPECT_DISABLED_MSG); + } else { + fme.setInspectMode(true); + msg(TL.COMMAND_INSPECT_ENABLED); + } - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_INSPECT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_INSPECT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java index a177d8f7..00a9197e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdInvite.java @@ -12,83 +12,83 @@ import org.bukkit.ChatColor; public class CmdInvite extends FCommand { - public CmdInvite() { - super(); - this.aliases.add("invite"); - this.aliases.add("inv"); + public CmdInvite() { + super(); + this.aliases.add("invite"); + this.aliases.add("inv"); - this.requiredArgs.add("player name"); - //this.optionalArgs.put("", ""); + this.requiredArgs.add("player name"); + //this.optionalArgs.put("", ""); - this.permission = Permission.INVITE.node; - this.disableOnLock = true; + this.permission = Permission.INVITE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer target = this.argAsBestFPlayerMatch(0); - if (target == null) { - return; - } + @Override + public void perform() { + FPlayer target = this.argAsBestFPlayerMatch(0); + if (target == null) { + return; + } - if (target.getFaction() == myFaction) { - msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), myFaction.getTag()); - msg(TL.GENERIC_YOUMAYWANT.toString() + p.cmdBase.cmdKick.getUseageTemplate(false)); - return; - } + if (target.getFaction() == myFaction) { + msg(TL.COMMAND_INVITE_ALREADYMEMBER, target.getName(), myFaction.getTag()); + msg(TL.GENERIC_YOUMAYWANT.toString() + p.cmdBase.cmdKick.getUseageTemplate(false)); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostInvite, TL.COMMAND_INVITE_TOINVITE.toString(), TL.COMMAND_INVITE_FORINVITE.toString())) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostInvite, TL.COMMAND_INVITE_TOINVITE.toString(), TL.COMMAND_INVITE_FORINVITE.toString())) { + return; + } - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.INVITE); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); - return; - } - } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.INVITE); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage invites"); + return; + } + } - if (myFaction.isInvited(target)) { - fme.msg(TL.COMMAND_INVITE_ALREADYINVITED, target.getName()); - return; - } - if (myFaction.isBanned(target)) { - fme.msg(TL.COMMAND_INVITE_BANNED, target.getName()); - return; - } + if (myFaction.isInvited(target)) { + fme.msg(TL.COMMAND_INVITE_ALREADYINVITED, target.getName()); + return; + } + if (myFaction.isBanned(target)) { + fme.msg(TL.COMMAND_INVITE_BANNED, target.getName()); + return; + } - myFaction.invite(target); - // Send the invitation to the target player when online, otherwise just ignore - if (target.isOnline()) { - // Tooltips, colors, and commands only apply to the string immediately before it. - FancyMessage message = new FancyMessage(fme.describeTo(target, true)) - .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + myFaction.getTag()) - .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) - .color(ChatColor.YELLOW) - .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + myFaction.getTag()) - .then(myFaction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) - .command("/" + Conf.baseCommandAliases.get(0) + " join " + myFaction.getTag()); + myFaction.invite(target); + // Send the invitation to the target player when online, otherwise just ignore + if (target.isOnline()) { + // Tooltips, colors, and commands only apply to the string immediately before it. + FancyMessage message = new FancyMessage(fme.describeTo(target, true)) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + myFaction.getTag()) + .then(TL.COMMAND_INVITE_INVITEDYOU.toString()) + .color(ChatColor.YELLOW) + .tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + myFaction.getTag()) + .then(myFaction.describeTo(target)).tooltip(TL.COMMAND_INVITE_CLICKTOJOIN.toString()) + .command("/" + Conf.baseCommandAliases.get(0) + " join " + myFaction.getTag()); - message.send(target.getPlayer()); - } + message.send(target.getPlayer()); + } - myFaction.msg(TL.COMMAND_INVITE_INVITED, fme.describeTo(myFaction, true), target.describeTo(myFaction)); - } + myFaction.msg(TL.COMMAND_INVITE_INVITED, fme.describeTo(myFaction, true), target.describeTo(myFaction)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_INVITE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_INVITE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java index f34a2bf2..3688b2b4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdJoin.java @@ -8,120 +8,120 @@ import org.bukkit.Bukkit; public class CmdJoin extends FCommand { - public CmdJoin() { - super(); - this.aliases.add("join"); + public CmdJoin() { + super(); + this.aliases.add("join"); - this.requiredArgs.add("faction name"); - this.optionalArgs.put("player", "you"); + this.requiredArgs.add("faction name"); + this.optionalArgs.put("player", "you"); - this.permission = Permission.JOIN.node; - this.disableOnLock = true; + this.permission = Permission.JOIN.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Faction faction = this.argAsFaction(0); - if (faction == null) { - return; - } + @Override + public void perform() { + Faction faction = this.argAsFaction(0); + if (faction == null) { + return; + } - FPlayer fplayer = this.argAsBestFPlayerMatch(1, fme, false); - boolean samePlayer = fplayer == fme; + FPlayer fplayer = this.argAsBestFPlayerMatch(1, fme, false); + boolean samePlayer = fplayer == fme; - if (!samePlayer && !Permission.JOIN_OTHERS.has(sender, false)) { - msg(TL.COMMAND_JOIN_CANNOTFORCE); - return; - } + if (!samePlayer && !Permission.JOIN_OTHERS.has(sender, false)) { + msg(TL.COMMAND_JOIN_CANNOTFORCE); + return; + } - if (!faction.isNormal()) { - msg(TL.COMMAND_JOIN_SYSTEMFACTION); - return; - } + if (!faction.isNormal()) { + msg(TL.COMMAND_JOIN_SYSTEMFACTION); + return; + } - if (faction == fplayer.getFaction()) { - //TODO:TL - msg(TL.COMMAND_JOIN_ALREADYMEMBER, fplayer.describeTo(fme, true), (samePlayer ? "are" : "is"), faction.getTag(fme)); - return; - } + if (faction == fplayer.getFaction()) { + //TODO:TL + msg(TL.COMMAND_JOIN_ALREADYMEMBER, fplayer.describeTo(fme, true), (samePlayer ? "are" : "is"), faction.getTag(fme)); + return; + } - if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= Conf.factionMemberLimit) { - msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(fme), Conf.factionMemberLimit, fplayer.describeTo(fme, false)); - return; - } + if (Conf.factionMemberLimit > 0 && faction.getFPlayers().size() >= Conf.factionMemberLimit) { + msg(TL.COMMAND_JOIN_ATLIMIT, faction.getTag(fme), Conf.factionMemberLimit, fplayer.describeTo(fme, false)); + return; + } - if (fplayer.hasFaction()) { - //TODO:TL - msg(TL.COMMAND_JOIN_INOTHERFACTION, fplayer.describeTo(fme, true), (samePlayer ? "your" : "their")); - return; - } + if (fplayer.hasFaction()) { + //TODO:TL + msg(TL.COMMAND_JOIN_INOTHERFACTION, fplayer.describeTo(fme, true), (samePlayer ? "your" : "their")); + return; + } - if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) { - msg(TL.COMMAND_JOIN_NEGATIVEPOWER, fplayer.describeTo(fme, true)); - return; - } + if (!Conf.canLeaveWithNegativePower && fplayer.getPower() < 0) { + msg(TL.COMMAND_JOIN_NEGATIVEPOWER, fplayer.describeTo(fme, true)); + return; + } - if (!(faction.getOpen() || faction.isInvited(fplayer) || fme.isAdminBypassing() || Permission.JOIN_ANY.has(sender, false))) { - msg(TL.COMMAND_JOIN_REQUIRESINVITATION); - if (samePlayer) { - faction.msg(TL.COMMAND_JOIN_ATTEMPTEDJOIN, fplayer.describeTo(faction, true)); - } - return; - } + if (!(faction.getOpen() || faction.isInvited(fplayer) || fme.isAdminBypassing() || Permission.JOIN_ANY.has(sender, false))) { + msg(TL.COMMAND_JOIN_REQUIRESINVITATION); + if (samePlayer) { + faction.msg(TL.COMMAND_JOIN_ATTEMPTEDJOIN, fplayer.describeTo(faction, true)); + } + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if (samePlayer && !canAffordCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString())) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (samePlayer && !canAffordCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString())) { + return; + } - // Check for ban - if (!fme.isAdminBypassing() && faction.isBanned(fme)) { - fme.msg(TL.COMMAND_JOIN_BANNED, faction.getTag(fme)); - return; - } + // Check for ban + if (!fme.isAdminBypassing() && faction.isBanned(fme)) { + fme.msg(TL.COMMAND_JOIN_BANNED, faction.getTag(fme)); + return; + } - // trigger the join event (cancellable) - FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(me), faction, FPlayerJoinEvent.PlayerJoinReason.COMMAND); - Bukkit.getServer().getPluginManager().callEvent(joinEvent); - if (joinEvent.isCancelled()) { - return; - } + // trigger the join event (cancellable) + FPlayerJoinEvent joinEvent = new FPlayerJoinEvent(FPlayers.getInstance().getByPlayer(me), faction, FPlayerJoinEvent.PlayerJoinReason.COMMAND); + Bukkit.getServer().getPluginManager().callEvent(joinEvent); + if (joinEvent.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (samePlayer && !payForCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString(), TL.COMMAND_JOIN_FORJOIN.toString())) { - return; - } + // then make 'em pay (if applicable) + if (samePlayer && !payForCommand(Conf.econCostJoin, TL.COMMAND_JOIN_TOJOIN.toString(), TL.COMMAND_JOIN_FORJOIN.toString())) { + return; + } - fme.msg(TL.COMMAND_JOIN_SUCCESS, fplayer.describeTo(fme, true), faction.getTag(fme)); + fme.msg(TL.COMMAND_JOIN_SUCCESS, fplayer.describeTo(fme, true), faction.getTag(fme)); - if (!samePlayer) { - fplayer.msg(TL.COMMAND_JOIN_MOVED, fme.describeTo(fplayer, true), faction.getTag(fplayer)); - } - faction.msg(TL.COMMAND_JOIN_JOINED, fplayer.describeTo(faction, true)); + if (!samePlayer) { + fplayer.msg(TL.COMMAND_JOIN_MOVED, fme.describeTo(fplayer, true), faction.getTag(fplayer)); + } + faction.msg(TL.COMMAND_JOIN_JOINED, fplayer.describeTo(faction, true)); - fplayer.resetFactionData(); - fplayer.setFaction(faction); - faction.deinvite(fplayer); - fme.setRole(faction.getDefaultRole()); + fplayer.resetFactionData(); + fplayer.setFaction(faction); + faction.deinvite(fplayer); + fme.setRole(faction.getDefaultRole()); - if (Conf.logFactionJoin) { - if (samePlayer) { - SavageFactions.plugin.log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag()); - } else { - SavageFactions.plugin.log(TL.COMMAND_JOIN_MOVEDLOG.toString(), fme.getName(), fplayer.getName(), faction.getTag()); - } - } - } + if (Conf.logFactionJoin) { + if (samePlayer) { + SavageFactions.plugin.log(TL.COMMAND_JOIN_JOINEDLOG.toString(), fplayer.getName(), faction.getTag()); + } else { + SavageFactions.plugin.log(TL.COMMAND_JOIN_MOVEDLOG.toString(), fme.getName(), fplayer.getName(), faction.getTag()); + } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_JOIN_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_JOIN_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java index dcdb74ff..0cb144bb 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKick.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKick.java @@ -16,125 +16,125 @@ import org.bukkit.ChatColor; public class CmdKick extends FCommand { - public CmdKick() { - super(); - this.aliases.add("kick"); + public CmdKick() { + super(); + this.aliases.add("kick"); - this.optionalArgs.put("player name", "player name"); - //this.optionalArgs.put("", ""); + this.optionalArgs.put("player name", "player name"); + //this.optionalArgs.put("", ""); - this.permission = Permission.KICK.node; - this.disableOnLock = false; + this.permission = Permission.KICK.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer toKick = this.argIsSet(0) ? this.argAsBestFPlayerMatch(0) : null; - if (toKick == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_KICK_CANDIDATES.toString()).color(ChatColor.GOLD); - for (FPlayer player : myFaction.getFPlayersWhereRole(Role.NORMAL)) { - String s = player.getName(); - msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); - } - if (fme.getRole().isAtLeast(Role.COLEADER)) { - // For both coleader and admin, add mods. - for (FPlayer player : myFaction.getFPlayersWhereRole(Role.MODERATOR)) { - String s = player.getName(); - msg.then(s + " ").color(ChatColor.GRAY).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); - } - if (fme.getRole() == Role.LEADER) { - // Only add coleader to this for the leader. - for (FPlayer player : myFaction.getFPlayersWhereRole(Role.COLEADER)) { - String s = player.getName(); - msg.then(s + " ").color(ChatColor.RED).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); - } - } - } + @Override + public void perform() { + FPlayer toKick = this.argIsSet(0) ? this.argAsBestFPlayerMatch(0) : null; + if (toKick == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_KICK_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : myFaction.getFPlayersWhereRole(Role.NORMAL)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); + } + if (fme.getRole().isAtLeast(Role.COLEADER)) { + // For both coleader and admin, add mods. + for (FPlayer player : myFaction.getFPlayersWhereRole(Role.MODERATOR)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.GRAY).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); + } + if (fme.getRole() == Role.LEADER) { + // Only add coleader to this for the leader. + for (FPlayer player : myFaction.getFPlayersWhereRole(Role.COLEADER)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.RED).tooltip(TL.COMMAND_KICK_CLICKTOKICK.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " kick " + s); + } + } + } - sendFancyMessage(msg); - return; - } + sendFancyMessage(msg); + return; + } - if (fme == toKick) { - msg(TL.COMMAND_KICK_SELF); - msg(TL.GENERIC_YOUMAYWANT.toString() + p.cmdBase.cmdLeave.getUseageTemplate(false)); - return; - } + if (fme == toKick) { + msg(TL.COMMAND_KICK_SELF); + msg(TL.GENERIC_YOUMAYWANT.toString() + p.cmdBase.cmdLeave.getUseageTemplate(false)); + return; + } - Faction toKickFaction = toKick.getFaction(); + Faction toKickFaction = toKick.getFaction(); - if (toKickFaction.isWilderness()) { - sender.sendMessage(TL.COMMAND_KICK_NONE.toString()); - return; - } + if (toKickFaction.isWilderness()) { + sender.sendMessage(TL.COMMAND_KICK_NONE.toString()); + return; + } - // This permission check has been cleaned to be more understandable and logical - // Unless is admin, - // - Check for the kick permission. - // - Make sure the player is in the faction. - // - Make sure the kicked player has lower rank than the kicker. - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.KICK); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_NOPERMISSION, "kick"); - return; - } - if (toKickFaction != myFaction) { - msg(TL.COMMAND_KICK_NOTMEMBER, toKick.describeTo(fme, true), myFaction.describeTo(fme)); - return; - } - if (toKick.getRole().value >= fme.getRole().value) { - msg(TL.COMMAND_KICK_INSUFFICIENTRANK); - return; - } - if (!Conf.canLeaveWithNegativePower && toKick.getPower() < 0) { - msg(TL.COMMAND_KICK_NEGATIVEPOWER); - return; - } - } + // This permission check has been cleaned to be more understandable and logical + // Unless is admin, + // - Check for the kick permission. + // - Make sure the player is in the faction. + // - Make sure the kicked player has lower rank than the kicker. + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.KICK); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_NOPERMISSION, "kick"); + return; + } + if (toKickFaction != myFaction) { + msg(TL.COMMAND_KICK_NOTMEMBER, toKick.describeTo(fme, true), myFaction.describeTo(fme)); + return; + } + if (toKick.getRole().value >= fme.getRole().value) { + msg(TL.COMMAND_KICK_INSUFFICIENTRANK); + return; + } + if (!Conf.canLeaveWithNegativePower && toKick.getPower() < 0) { + msg(TL.COMMAND_KICK_NEGATIVEPOWER); + return; + } + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if (!canAffordCommand(Conf.econCostKick, TL.COMMAND_KICK_TOKICK.toString())) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!canAffordCommand(Conf.econCostKick, TL.COMMAND_KICK_TOKICK.toString())) { + return; + } - // trigger the leave event (cancellable) [reason:kicked] - FPlayerLeaveEvent event = new FPlayerLeaveEvent(toKick, toKick.getFaction(), FPlayerLeaveEvent.PlayerLeaveReason.KICKED); - Bukkit.getServer().getPluginManager().callEvent(event); - if (event.isCancelled()) { - return; - } + // trigger the leave event (cancellable) [reason:kicked] + FPlayerLeaveEvent event = new FPlayerLeaveEvent(toKick, toKick.getFaction(), FPlayerLeaveEvent.PlayerLeaveReason.KICKED); + Bukkit.getServer().getPluginManager().callEvent(event); + if (event.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (!payForCommand(Conf.econCostKick, TL.COMMAND_KICK_TOKICK.toString(), TL.COMMAND_KICK_FORKICK.toString())) { - return; - } + // then make 'em pay (if applicable) + if (!payForCommand(Conf.econCostKick, TL.COMMAND_KICK_TOKICK.toString(), TL.COMMAND_KICK_FORKICK.toString())) { + return; + } - toKickFaction.msg(TL.COMMAND_KICK_FACTION, fme.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true)); + toKickFaction.msg(TL.COMMAND_KICK_FACTION, fme.describeTo(toKickFaction, true), toKick.describeTo(toKickFaction, true)); - toKick.msg(TL.COMMAND_KICK_KICKED, fme.describeTo(toKick, true), toKickFaction.describeTo(toKick)); - if (toKickFaction != myFaction) { - fme.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(fme), toKickFaction.describeTo(fme)); - } - if (Conf.logFactionKick) { - SavageFactions.plugin.log((senderIsConsole ? "A console command" : fme.getName()) + " kicked " + toKick.getName() + " from the faction: " + toKickFaction.getTag()); - } - if (toKick.getRole() == Role.LEADER) { - toKickFaction.promoteNewLeader(); - } - toKickFaction.deinvite(toKick); - toKick.resetFactionData(); - } + toKick.msg(TL.COMMAND_KICK_KICKED, fme.describeTo(toKick, true), toKickFaction.describeTo(toKick)); + if (toKickFaction != myFaction) { + fme.msg(TL.COMMAND_KICK_KICKS, toKick.describeTo(fme), toKickFaction.describeTo(fme)); + } + if (Conf.logFactionKick) { + SavageFactions.plugin.log((senderIsConsole ? "A console command" : fme.getName()) + " kicked " + toKick.getName() + " from the faction: " + toKickFaction.getTag()); + } + if (toKick.getRole() == Role.LEADER) { + toKickFaction.promoteNewLeader(); + } + toKickFaction.deinvite(toKick); + toKick.resetFactionData(); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_KICK_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_KICK_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdKillHolograms.java b/src/main/java/com/massivecraft/factions/cmd/CmdKillHolograms.java index 0ee95a2b..4c3ec562 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdKillHolograms.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdKillHolograms.java @@ -4,32 +4,32 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdKillHolograms extends FCommand { - public CmdKillHolograms() { - super(); + public CmdKillHolograms() { + super(); - this.aliases.add("killholos"); + this.aliases.add("killholos"); - this.requiredArgs.add("radius"); + this.requiredArgs.add("radius"); - this.permission = Permission.KILLHOLOS.node; - this.disableOnLock = true; + this.permission = Permission.KILLHOLOS.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - me.sendMessage("Killing Invisible Armor Stands.."); - me.chat("/minecraft:kill @e[type=ArmorStand,r=" + argAsInt(0) + "]"); + @Override + public void perform() { + me.sendMessage("Killing Invisible Armor Stands.."); + me.chat("/minecraft:kill @e[type=ArmorStand,r=" + argAsInt(0) + "]"); - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_KILLHOLOGRAMS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_KILLHOLOGRAMS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java index b28f4ab6..8d9c5634 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLeave.java @@ -5,32 +5,32 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdLeave extends FCommand { - public CmdLeave() { - super(); - this.aliases.add("leave"); + public CmdLeave() { + super(); + this.aliases.add("leave"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - this.permission = Permission.LEAVE.node; - this.disableOnLock = true; + this.permission = Permission.LEAVE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - fme.leave(true); - } + @Override + public void perform() { + fme.leave(true); + } - @Override - public TL getUsageTranslation() { - return TL.LEAVE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.LEAVE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdList.java b/src/main/java/com/massivecraft/factions/cmd/CmdList.java index 7c6793e1..46f75b2b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdList.java @@ -13,119 +13,119 @@ import java.util.*; public class CmdList extends FCommand { - private String[] defaults = new String[3]; + private String[] defaults = new String[3]; - public CmdList() { - super(); - this.aliases.add("list"); - this.aliases.add("ls"); + public CmdList() { + super(); + this.aliases.add("list"); + this.aliases.add("ls"); - // default values in case user has old config - defaults[0] = "&e&m----------&r&e[ &2Faction List &9{pagenumber}&e/&9{pagecount} &e]&m----------"; - defaults[1] = "Factionless {factionless} online"; - defaults[2] = "{faction} {online} / {members} online, Land / Power / Maxpower: {chunks}/{power}/{maxPower}"; + // default values in case user has old config + defaults[0] = "&e&m----------&r&e[ &2Faction List &9{pagenumber}&e/&9{pagecount} &e]&m----------"; + defaults[1] = "Factionless {factionless} online"; + defaults[2] = "{faction} {online} / {members} online, Land / Power / Maxpower: {chunks}/{power}/{maxPower}"; - //this.requiredArgs.add(""); - this.optionalArgs.put("page", "1"); + //this.requiredArgs.add(""); + this.optionalArgs.put("page", "1"); - this.permission = Permission.LIST.node; - this.disableOnLock = false; + this.permission = Permission.LIST.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) - return; + @Override + public void perform() { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostList, "to list the factions", "for listing the factions")) + return; - ArrayList factionList = Factions.getInstance().getAllFactions(); - factionList.remove(Factions.getInstance().getWilderness()); - factionList.remove(Factions.getInstance().getSafeZone()); - factionList.remove(Factions.getInstance().getWarZone()); + ArrayList factionList = Factions.getInstance().getAllFactions(); + factionList.remove(Factions.getInstance().getWilderness()); + factionList.remove(Factions.getInstance().getSafeZone()); + factionList.remove(Factions.getInstance().getWarZone()); - // remove exempt factions - if (fme != null && fme.getPlayer() != null && !fme.getPlayer().hasPermission("factions.show.bypassexempt")) { - List exemptFactions = SavageFactions.plugin.getConfig().getStringList("show-exempt"); - Iterator factionIterator = factionList.iterator(); + // remove exempt factions + if (fme != null && fme.getPlayer() != null && !fme.getPlayer().hasPermission("factions.show.bypassexempt")) { + List exemptFactions = SavageFactions.plugin.getConfig().getStringList("show-exempt"); + Iterator factionIterator = factionList.iterator(); - while (factionIterator.hasNext()) { - Faction next = factionIterator.next(); - if (exemptFactions.contains(next.getTag())) - factionIterator.remove(); - } - } + while (factionIterator.hasNext()) { + Faction next = factionIterator.next(); + if (exemptFactions.contains(next.getTag())) + factionIterator.remove(); + } + } - // Sort by total followers first - Collections.sort(factionList, new Comparator() { - @Override - public int compare(Faction f1, Faction f2) { - int f1Size = f1.getFPlayers().size(); - int f2Size = f2.getFPlayers().size(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - } - }); + // Sort by total followers first + Collections.sort(factionList, new Comparator() { + @Override + public int compare(Faction f1, Faction 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 - Collections.sort(factionList, new Comparator() { - @Override - public int compare(Faction f1, Faction 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; - } - }); + // Then sort by how many members are online now + Collections.sort(factionList, new Comparator() { + @Override + public int compare(Faction f1, Faction 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<>(); + ArrayList lines = new ArrayList<>(); - factionList.add(0, Factions.getInstance().getWilderness()); + factionList.add(0, Factions.getInstance().getWilderness()); - final int pageheight = 9; - int pagenumber = this.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(); - } + final int pageheight = 9; + int pagenumber = this.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 = p.getConfig().getString("list.header", defaults[0]); - header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); - lines.add(p.txt.parse(header)); + String header = p.getConfig().getString("list.header", defaults[0]); + header = header.replace("{pagenumber}", String.valueOf(pagenumber)).replace("{pagecount}", String.valueOf(pagecount)); + lines.add(p.txt.parse(header)); - for (Faction faction : factionList.subList(start, end)) { - if (faction.isWilderness()) { - lines.add(p.txt.parse(TagUtil.parsePlain(faction, p.getConfig().getString("list.factionless", defaults[1])))); - continue; - } - lines.add(p.txt.parse(TagUtil.parsePlain(faction, fme, p.getConfig().getString("list.entry", defaults[2])))); - } - sendMessage(lines); - } + for (Faction faction : factionList.subList(start, end)) { + if (faction.isWilderness()) { + lines.add(p.txt.parse(TagUtil.parsePlain(faction, p.getConfig().getString("list.factionless", defaults[1])))); + continue; + } + lines.add(p.txt.parse(TagUtil.parsePlain(faction, fme, p.getConfig().getString("list.entry", defaults[2])))); + } + sendMessage(lines); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_LIST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LIST_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java index 37c1bdac..e8872473 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLock.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLock.java @@ -5,40 +5,40 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdLock extends FCommand { - // TODO: This solution needs refactoring. + // TODO: This solution needs refactoring. /* factions.lock: description: use the /f lock [on/off] command to temporarily lock the data files from being overwritten default: op */ - public CmdLock() { - super(); - this.aliases.add("lock"); + public CmdLock() { + super(); + this.aliases.add("lock"); - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "flip"); + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "flip"); - this.permission = Permission.LOCK.node; - this.disableOnLock = false; + this.permission = Permission.LOCK.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - p.setLocked(this.argAsBool(0, !p.getLocked())); - msg(p.getLocked() ? TL.COMMAND_LOCK_LOCKED : TL.COMMAND_LOCK_UNLOCKED); - } + @Override + public void perform() { + p.setLocked(this.argAsBool(0, !p.getLocked())); + msg(p.getLocked() ? TL.COMMAND_LOCK_LOCKED : TL.COMMAND_LOCK_UNLOCKED); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_LOCK_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LOCK_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java b/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java index b310cbd0..ca0917cb 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLogins.java @@ -5,27 +5,27 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdLogins extends FCommand { - public CmdLogins() { - super(); - this.aliases.add("login"); - this.aliases.add("logins"); - this.aliases.add("logout"); - this.aliases.add("logouts"); - this.senderMustBePlayer = true; + public CmdLogins() { + super(); + this.aliases.add("login"); + this.aliases.add("logins"); + this.aliases.add("logout"); + this.aliases.add("logouts"); + this.senderMustBePlayer = true; - this.senderMustBeMember = true; - this.permission = Permission.MONITOR_LOGINS.node; - } + this.senderMustBeMember = true; + this.permission = Permission.MONITOR_LOGINS.node; + } - @Override - public void perform() { - boolean monitor = fme.isMonitoringJoins(); - fme.msg(TL.COMMAND_LOGINS_TOGGLE, String.valueOf(!monitor)); - fme.setMonitorJoins(!monitor); - } + @Override + public void perform() { + boolean monitor = fme.isMonitoringJoins(); + fme.msg(TL.COMMAND_LOGINS_TOGGLE, String.valueOf(!monitor)); + fme.setMonitorJoins(!monitor); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_LOGINS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LOGINS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdLowPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdLowPower.java index 9d40fbe6..ac02a91f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdLowPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdLowPower.java @@ -6,38 +6,38 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdLowPower extends FCommand { - public CmdLowPower() { - super(); - this.aliases.add("lowpower"); + public CmdLowPower() { + super(); + this.aliases.add("lowpower"); - this.disableOnLock = false; + this.disableOnLock = false; - senderMustBePlayer = true; + senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; - } + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - double maxPower = Conf.powerPlayerMax; - String format = TL.COMMAND_LOWPOWER_FORMAT.toString(); - msg(TL.COMMAND_LOWPOWER_HEADER.toString().replace("{maxpower}", (int) maxPower + "")); - for (FPlayer fPlayer : fme.getFaction().getFPlayers()) { - if (fPlayer.getPower() < maxPower) { - sendMessage(format.replace("{player}", fPlayer.getName()).replace("{player_power}", (int) fPlayer.getPower() + "").replace("{maxpower}", (int) maxPower + "")); - } - } - } + @Override + public void perform() { + double maxPower = Conf.powerPlayerMax; + String format = TL.COMMAND_LOWPOWER_FORMAT.toString(); + msg(TL.COMMAND_LOWPOWER_HEADER.toString().replace("{maxpower}", (int) maxPower + "")); + for (FPlayer fPlayer : fme.getFaction().getFPlayers()) { + if (fPlayer.getPower() < maxPower) { + sendMessage(format.replace("{player}", fPlayer.getName()).replace("{player_power}", (int) fPlayer.getPower() + "").replace("{maxpower}", (int) maxPower + "")); + } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_LOWPOWER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_LOWPOWER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java index 14ec1fce..ccbaffbd 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMap.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMap.java @@ -9,62 +9,62 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdMap extends FCommand { - public CmdMap() { - super(); - this.aliases.add("map"); + public CmdMap() { + super(); + this.aliases.add("map"); - //this.requiredArgs.add(""); - this.optionalArgs.put("on/off", "once"); + //this.requiredArgs.add(""); + this.optionalArgs.put("on/off", "once"); - this.permission = Permission.MAP.node; - this.disableOnLock = false; + this.permission = Permission.MAP.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (this.argIsSet(0)) { - if (this.argAsBool(0, !fme.isMapAutoUpdating())) { - // Turn on + @Override + public void perform() { + if (this.argIsSet(0)) { + if (this.argAsBool(0, !fme.isMapAutoUpdating())) { + // Turn on - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostMap, "to show the map", "for showing the map")) { + return; + } - fme.setMapAutoUpdating(true); - msg(TL.COMMAND_MAP_UPDATE_ENABLED); + fme.setMapAutoUpdating(true); + msg(TL.COMMAND_MAP_UPDATE_ENABLED); - // And show the map once - showMap(); - } else { - // Turn off - fme.setMapAutoUpdating(false); - msg(TL.COMMAND_MAP_UPDATE_DISABLED); - } - } else { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostMap, TL.COMMAND_MAP_TOSHOW, TL.COMMAND_MAP_FORSHOW)) { - return; - } + // And show the map once + showMap(); + } else { + // Turn off + fme.setMapAutoUpdating(false); + msg(TL.COMMAND_MAP_UPDATE_DISABLED); + } + } else { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostMap, TL.COMMAND_MAP_TOSHOW, TL.COMMAND_MAP_FORSHOW)) { + return; + } - showMap(); - } - } + showMap(); + } + } - public void showMap() { - sendFancyMessage(Board.getInstance().getMap(fme, new FLocation(fme), fme.getPlayer().getLocation().getYaw())); - } + public void showMap() { + sendFancyMessage(Board.getInstance().getMap(fme, new FLocation(fme), fme.getPlayer().getLocation().getYaw())); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MAP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MAP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java b/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java index eac2f9b2..5588f828 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMapHeight.java @@ -5,36 +5,36 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdMapHeight extends FCommand { - public CmdMapHeight() { - super(); + public CmdMapHeight() { + super(); - this.aliases.add("mapheight"); - this.aliases.add("mh"); + this.aliases.add("mapheight"); + this.aliases.add("mh"); - this.optionalArgs.put("height", "height"); + this.optionalArgs.put("height", "height"); - this.permission = Permission.MAPHEIGHT.node; + this.permission = Permission.MAPHEIGHT.node; - this.senderMustBePlayer = true; - } + this.senderMustBePlayer = true; + } - @Override - public void perform() { - if (args.size() == 0) { - fme.sendMessage(TL.COMMAND_MAPHEIGHT_CURRENT.format(fme.getMapHeight())); - return; - } + @Override + public void perform() { + if (args.size() == 0) { + fme.sendMessage(TL.COMMAND_MAPHEIGHT_CURRENT.format(fme.getMapHeight())); + return; + } - int height = argAsInt(0); + int height = argAsInt(0); - fme.setMapHeight(height); - fme.sendMessage(TL.COMMAND_MAPHEIGHT_SET.format(fme.getMapHeight())); - } + fme.setMapHeight(height); + fme.sendMessage(TL.COMMAND_MAPHEIGHT_SET.format(fme.getMapHeight())); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MAPHEIGHT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MAPHEIGHT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java index 978d4428..56ab092b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMod.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMod.java @@ -11,79 +11,79 @@ import org.bukkit.ChatColor; public class CmdMod extends FCommand { - public CmdMod() { - super(); - this.aliases.add("mod"); - this.aliases.add("setmod"); - this.aliases.add("officer"); - this.aliases.add("setofficer"); + public CmdMod() { + super(); + this.aliases.add("mod"); + this.aliases.add("setmod"); + this.aliases.add("officer"); + this.aliases.add("setofficer"); - this.optionalArgs.put("player name", "name"); - //this.optionalArgs.put("", ""); + this.optionalArgs.put("player name", "name"); + //this.optionalArgs.put("", ""); - this.permission = Permission.MOD.node; - this.disableOnLock = true; + this.permission = Permission.MOD.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { - FancyMessage msg = new FancyMessage(TL.COMMAND_MOD_CANDIDATES.toString()).color(ChatColor.GOLD); - for (FPlayer player : myFaction.getFPlayersWhereRole(Role.NORMAL)) { - String s = player.getName(); - msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " mod " + s); - } + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) { + FancyMessage msg = new FancyMessage(TL.COMMAND_MOD_CANDIDATES.toString()).color(ChatColor.GOLD); + for (FPlayer player : myFaction.getFPlayersWhereRole(Role.NORMAL)) { + String s = player.getName(); + msg.then(s + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_MOD_CLICKTOPROMOTE.toString() + s).command("/" + Conf.baseCommandAliases.get(0) + " mod " + s); + } - sendFancyMessage(msg); - return; - } + sendFancyMessage(msg); + return; + } - boolean permAny = Permission.MOD_ANY.has(sender, false); - Faction targetFaction = you.getFaction(); - if (targetFaction != myFaction && !permAny) { - msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(fme, true)); - return; - } + boolean permAny = Permission.MOD_ANY.has(sender, false); + Faction targetFaction = you.getFaction(); + if (targetFaction != myFaction && !permAny) { + msg(TL.COMMAND_MOD_NOTMEMBER, you.describeTo(fme, true)); + return; + } - if (fme != null && fme.getRole() != Role.LEADER && !permAny) { - msg(TL.COMMAND_MOD_NOTADMIN); - return; - } + if (fme != null && fme.getRole() != Role.LEADER && !permAny) { + msg(TL.COMMAND_MOD_NOTADMIN); + return; + } - if (you == fme && !permAny) { - msg(TL.COMMAND_MOD_SELF); - return; - } + if (you == fme && !permAny) { + msg(TL.COMMAND_MOD_SELF); + return; + } - if (you.getRole() == Role.LEADER) { - msg(TL.COMMAND_MOD_TARGETISADMIN); - return; - } + if (you.getRole() == Role.LEADER) { + msg(TL.COMMAND_MOD_TARGETISADMIN); + return; + } - if (you.getRole() == Role.MODERATOR) { - // Revoke - you.setRole(Role.NORMAL); - targetFaction.msg(TL.COMMAND_MOD_REVOKED, you.describeTo(targetFaction, true)); - msg(TL.COMMAND_MOD_REVOKES, you.describeTo(fme, true)); - } else { - // Give - you.setRole(Role.MODERATOR); - targetFaction.msg(TL.COMMAND_MOD_PROMOTED, you.describeTo(targetFaction, true)); - msg(TL.COMMAND_MOD_PROMOTES, you.describeTo(fme, true)); - } - } + if (you.getRole() == Role.MODERATOR) { + // Revoke + you.setRole(Role.NORMAL); + targetFaction.msg(TL.COMMAND_MOD_REVOKED, you.describeTo(targetFaction, true)); + msg(TL.COMMAND_MOD_REVOKES, you.describeTo(fme, true)); + } else { + // Give + you.setRole(Role.MODERATOR); + targetFaction.msg(TL.COMMAND_MOD_PROMOTED, you.describeTo(targetFaction, true)); + msg(TL.COMMAND_MOD_PROMOTES, you.describeTo(fme, true)); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MOD_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MOD_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java index 361e632f..1720bd91 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdModifyPower.java @@ -6,45 +6,45 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdModifyPower extends FCommand { - public CmdModifyPower() { - super(); + public CmdModifyPower() { + super(); - this.aliases.add("pm"); - this.aliases.add("mp"); - this.aliases.add("modifypower"); - this.aliases.add("modpower"); + this.aliases.add("pm"); + this.aliases.add("mp"); + this.aliases.add("modifypower"); + this.aliases.add("modpower"); - this.requiredArgs.add("name"); - this.requiredArgs.add("power"); + this.requiredArgs.add("name"); + this.requiredArgs.add("power"); - this.permission = Permission.MODIFY_POWER.node; // admin only perm. + this.permission = Permission.MODIFY_POWER.node; // admin only perm. - // Let's not require anything and let console modify this as well. - this.senderMustBeAdmin = false; - this.senderMustBePlayer = false; - this.senderMustBeMember = false; - senderMustBeColeader = false; - this.senderMustBeModerator = false; - } + // Let's not require anything and let console modify this as well. + this.senderMustBeAdmin = false; + this.senderMustBePlayer = false; + this.senderMustBeMember = false; + senderMustBeColeader = false; + this.senderMustBeModerator = false; + } - @Override - public void perform() { - // /f modify # - FPlayer player = argAsBestFPlayerMatch(0); - Double number = argAsDouble(1); // returns null if not a Double. + @Override + public void perform() { + // /f modify # + FPlayer player = argAsBestFPlayerMatch(0); + Double number = argAsDouble(1); // returns null if not a Double. - if (player == null || number == null) { - sender.sendMessage(getHelpShort()); - return; - } + if (player == null || number == null) { + sender.sendMessage(getHelpShort()); + return; + } - player.alterPower(number); - int newPower = player.getPowerRounded(); // int so we don't have super long doubles. - msg(TL.COMMAND_MODIFYPOWER_ADDED, number, player.getName(), newPower); - } + player.alterPower(number); + int newPower = player.getPowerRounded(); // int so we don't have super long doubles. + msg(TL.COMMAND_MODIFYPOWER_ADDED, number, player.getName(), newPower); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MODIFYPOWER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MODIFYPOWER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java index b1cd4e19..dbce6182 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoney.java @@ -5,48 +5,48 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdMoney extends FCommand { - public CmdMoneyBalance cmdMoneyBalance = new CmdMoneyBalance(); - public CmdMoneyDeposit cmdMoneyDeposit = new CmdMoneyDeposit(); - public CmdMoneyWithdraw cmdMoneyWithdraw = new CmdMoneyWithdraw(); - public CmdMoneyTransferFf cmdMoneyTransferFf = new CmdMoneyTransferFf(); - public CmdMoneyTransferFp cmdMoneyTransferFp = new CmdMoneyTransferFp(); - public CmdMoneyTransferPf cmdMoneyTransferPf = new CmdMoneyTransferPf(); + public CmdMoneyBalance cmdMoneyBalance = new CmdMoneyBalance(); + public CmdMoneyDeposit cmdMoneyDeposit = new CmdMoneyDeposit(); + public CmdMoneyWithdraw cmdMoneyWithdraw = new CmdMoneyWithdraw(); + public CmdMoneyTransferFf cmdMoneyTransferFf = new CmdMoneyTransferFf(); + public CmdMoneyTransferFp cmdMoneyTransferFp = new CmdMoneyTransferFp(); + public CmdMoneyTransferPf cmdMoneyTransferPf = new CmdMoneyTransferPf(); - public CmdMoney() { - super(); - this.aliases.add("money"); + public CmdMoney() { + super(); + this.aliases.add("money"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("","") + //this.requiredArgs.add(""); + //this.optionalArgs.put("","") - this.isMoneyCommand = true; + this.isMoneyCommand = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - this.helpLong.add(p.txt.parseTags(TL.COMMAND_MONEY_LONG.toString())); + this.helpLong.add(p.txt.parseTags(TL.COMMAND_MONEY_LONG.toString())); - this.addSubCommand(this.cmdMoneyBalance); - this.addSubCommand(this.cmdMoneyDeposit); - this.addSubCommand(this.cmdMoneyWithdraw); - this.addSubCommand(this.cmdMoneyTransferFf); - this.addSubCommand(this.cmdMoneyTransferFp); - this.addSubCommand(this.cmdMoneyTransferPf); + this.addSubCommand(this.cmdMoneyBalance); + this.addSubCommand(this.cmdMoneyDeposit); + this.addSubCommand(this.cmdMoneyWithdraw); + this.addSubCommand(this.cmdMoneyTransferFf); + this.addSubCommand(this.cmdMoneyTransferFp); + this.addSubCommand(this.cmdMoneyTransferPf); - } + } - @Override - public void perform() { - this.commandChain.add(this); - SavageFactions.plugin.cmdAutoHelp.execute(this.sender, this.args, this.commandChain); - } + @Override + public void perform() { + this.commandChain.add(this); + SavageFactions.plugin.cmdAutoHelp.execute(this.sender, this.args, this.commandChain); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEY_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEY_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java index bce68b8a..83699a5e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyBalance.java @@ -7,46 +7,46 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdMoneyBalance extends FCommand { - public CmdMoneyBalance() { - super(); - this.aliases.add("b"); - this.aliases.add("balance"); + public CmdMoneyBalance() { + super(); + this.aliases.add("b"); + this.aliases.add("balance"); - //this.requiredArgs.add(""); - this.optionalArgs.put("faction", "yours"); + //this.requiredArgs.add(""); + this.optionalArgs.put("faction", "yours"); - this.permission = Permission.MONEY_BALANCE.node; - this.setHelpShort(TL.COMMAND_MONEYBALANCE_SHORT.toString()); + this.permission = Permission.MONEY_BALANCE.node; + this.setHelpShort(TL.COMMAND_MONEYBALANCE_SHORT.toString()); - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Faction faction = myFaction; - if (this.argIsSet(0)) { - faction = this.argAsFaction(0); - } + @Override + public void perform() { + Faction faction = myFaction; + if (this.argIsSet(0)) { + faction = this.argAsFaction(0); + } - if (faction == null) { - return; - } - if (faction != myFaction && !Permission.MONEY_BALANCE_ANY.has(sender, true)) { - return; - } + if (faction == null) { + return; + } + if (faction != myFaction && !Permission.MONEY_BALANCE_ANY.has(sender, true)) { + return; + } - if (fme != null) { - Econ.sendBalanceInfo(fme, faction); - } - } + if (fme != null) { + Econ.sendBalanceInfo(fme, faction); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEYBALANCE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYBALANCE_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java index cdf79595..331161b6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyDeposit.java @@ -11,41 +11,41 @@ import org.bukkit.ChatColor; public class CmdMoneyDeposit extends FCommand { - public CmdMoneyDeposit() { - super(); - this.aliases.add("d"); - this.aliases.add("deposit"); + public CmdMoneyDeposit() { + super(); + this.aliases.add("d"); + this.aliases.add("deposit"); - this.requiredArgs.add("amount"); - this.optionalArgs.put("faction", "yours"); + this.requiredArgs.add("amount"); + this.optionalArgs.put("faction", "yours"); - this.permission = Permission.MONEY_DEPOSIT.node; + this.permission = Permission.MONEY_DEPOSIT.node; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator faction = this.argAsFaction(1, myFaction); - if (faction == null) { - return; - } - boolean success = Econ.transferMoney(fme, fme, faction, amount); + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator faction = this.argAsFaction(1, myFaction); + if (faction == null) { + return; + } + boolean success = Econ.transferMoney(fme, fme, faction, amount); - if (success && Conf.logMoneyTransactions) { - SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYDEPOSIT_DEPOSITED.toString(), fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYDEPOSIT_DEPOSITED.toString(), fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEYDEPOSIT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYDEPOSIT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java index 75d5884d..27274da4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFf.java @@ -12,47 +12,47 @@ import org.bukkit.entity.Player; public class CmdMoneyTransferFf extends FCommand { - public CmdMoneyTransferFf() { - this.aliases.add("ff"); + public CmdMoneyTransferFf() { + this.aliases.add("ff"); - this.requiredArgs.add("amount"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("faction"); + this.requiredArgs.add("amount"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("faction"); - //this.optionalArgs.put("", ""); + //this.optionalArgs.put("", ""); - this.permission = Permission.MONEY_F2F.node; + this.permission = Permission.MONEY_F2F.node; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsFaction(1); - if (from == null) { - return; - } - EconomyParticipator to = this.argAsFaction(2); - if (to == null) { - return; - } + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator from = this.argAsFaction(1); + if (from == null) { + return; + } + EconomyParticipator to = this.argAsFaction(2); + if (to == null) { + return; + } - boolean success = Econ.transferMoney(fme, from, to, amount); + boolean success = Econ.transferMoney(fme, from, to, amount); - if (success && Conf.logMoneyTransactions) { - String name = sender instanceof Player ? fme.getName() : sender.getName(); - SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYTRANSFERFF_TRANSFER.toString(), name, Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + String name = sender instanceof Player ? fme.getName() : sender.getName(); + SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYTRANSFERFF_TRANSFER.toString(), name, Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEYTRANSFERFF_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYTRANSFERFF_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java index 17eb50bb..e743ea9e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferFp.java @@ -11,46 +11,46 @@ import org.bukkit.ChatColor; public class CmdMoneyTransferFp extends FCommand { - public CmdMoneyTransferFp() { - this.aliases.add("fp"); + public CmdMoneyTransferFp() { + this.aliases.add("fp"); - this.requiredArgs.add("amount"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("player"); + this.requiredArgs.add("amount"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("player"); - //this.optionalArgs.put("", ""); + //this.optionalArgs.put("", ""); - this.permission = Permission.MONEY_F2P.node; + this.permission = Permission.MONEY_F2P.node; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsFaction(1); - if (from == null) { - return; - } - EconomyParticipator to = this.argAsBestFPlayerMatch(2); - if (to == null) { - return; - } + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator from = this.argAsFaction(1); + if (from == null) { + return; + } + EconomyParticipator to = this.argAsBestFPlayerMatch(2); + if (to == null) { + return; + } - boolean success = Econ.transferMoney(fme, from, to, amount); + boolean success = Econ.transferMoney(fme, from, to, amount); - if (success && Conf.logMoneyTransactions) { - SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYTRANSFERFP_TRANSFER.toString(), fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYTRANSFERFP_TRANSFER.toString(), fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEYTRANSFERFP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYTRANSFERFP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java index 474cb70e..f245e4d5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyTransferPf.java @@ -11,46 +11,46 @@ import org.bukkit.ChatColor; public class CmdMoneyTransferPf extends FCommand { - public CmdMoneyTransferPf() { - this.aliases.add("pf"); + public CmdMoneyTransferPf() { + this.aliases.add("pf"); - this.requiredArgs.add("amount"); - this.requiredArgs.add("player"); - this.requiredArgs.add("faction"); + this.requiredArgs.add("amount"); + this.requiredArgs.add("player"); + this.requiredArgs.add("faction"); - //this.optionalArgs.put("", ""); + //this.optionalArgs.put("", ""); - this.permission = Permission.MONEY_P2F.node; + this.permission = Permission.MONEY_P2F.node; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator from = this.argAsBestFPlayerMatch(1); - if (from == null) { - return; - } - EconomyParticipator to = this.argAsFaction(2); - if (to == null) { - return; - } + @Override + public void perform() { + double amount = this.argAsDouble(0, 0d); + EconomyParticipator from = this.argAsBestFPlayerMatch(1); + if (from == null) { + return; + } + EconomyParticipator to = this.argAsFaction(2); + if (to == null) { + return; + } - boolean success = Econ.transferMoney(fme, from, to, amount); + boolean success = Econ.transferMoney(fme, from, to, amount); - if (success && Conf.logMoneyTransactions) { - SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYTRANSFERPF_TRANSFER.toString(), fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYTRANSFERPF_TRANSFER.toString(), fme.getName(), Econ.moneyString(amount), from.describeTo(null), to.describeTo(null)))); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEYTRANSFERPF_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYTRANSFERPF_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java index 32f4e07e..e08791d7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdMoneyWithdraw.java @@ -13,47 +13,47 @@ import org.bukkit.ChatColor; public class CmdMoneyWithdraw extends FCommand { - public CmdMoneyWithdraw() { - this.aliases.add("w"); - this.aliases.add("withdraw"); + public CmdMoneyWithdraw() { + this.aliases.add("w"); + this.aliases.add("withdraw"); - this.requiredArgs.add("amount"); - this.optionalArgs.put("faction", "yours"); + this.requiredArgs.add("amount"); + this.optionalArgs.put("faction", "yours"); - this.permission = Permission.MONEY_WITHDRAW.node; + this.permission = Permission.MONEY_WITHDRAW.node; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { + @Override + public void perform() { - double amount = this.argAsDouble(0, 0d); - EconomyParticipator faction = this.argAsFaction(1, myFaction); - if (faction == null) { - return; - } + double amount = this.argAsDouble(0, 0d); + EconomyParticipator faction = this.argAsFaction(1, myFaction); + if (faction == null) { + return; + } - Access access = myFaction.getAccess(fme, PermissableAction.WITHDRAW); - if (access == Access.DENY) { - fme.msg(TL.GENERIC_NOPERMISSION, "withdraw"); - return; - } + Access access = myFaction.getAccess(fme, PermissableAction.WITHDRAW); + if (access == Access.DENY) { + fme.msg(TL.GENERIC_NOPERMISSION, "withdraw"); + return; + } - boolean success = Econ.transferMoney(fme, faction, fme, amount); + boolean success = Econ.transferMoney(fme, faction, fme, amount); - if (success && Conf.logMoneyTransactions) { - SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); - } - } + if (success && Conf.logMoneyTransactions) { + SavageFactions.plugin.log(ChatColor.stripColor(SavageFactions.plugin.txt.parse(TL.COMMAND_MONEYWITHDRAW_WITHDRAW.toString(), fme.getName(), Econ.moneyString(amount), faction.describeTo(null)))); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_MONEYWITHDRAW_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_MONEYWITHDRAW_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdNear.java b/src/main/java/com/massivecraft/factions/cmd/CmdNear.java index 0a6208c8..eeae4895 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdNear.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdNear.java @@ -8,47 +8,47 @@ import org.bukkit.entity.Entity; import org.bukkit.entity.Player; public class CmdNear extends FCommand { - public CmdNear() { - super(); + public CmdNear() { + super(); - this.aliases.add("near"); - this.aliases.add("nearby"); + this.aliases.add("near"); + this.aliases.add("nearby"); - this.disableOnLock = true; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fnear.Enabled")) { - fme.msg(TL.COMMAND_NEAR_DISABLED_MSG); - return; - } + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fnear.Enabled")) { + fme.msg(TL.COMMAND_NEAR_DISABLED_MSG); + return; + } - double range = SavageFactions.plugin.getConfig().getInt("fnear.Radius"); - String format = TL.COMMAND_NEAR_FORMAT.toString(); - fme.msg(TL.COMMAND_NEAR_USE_MSG); - for (Entity e : me.getNearbyEntities(range, 255, range)) { - if (e instanceof Player) { - Player player = (((Player) e).getPlayer()); - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fme.getFaction() == fplayer.getFaction()) { - double distance = me.getLocation().distance(player.getLocation()); - fme.sendMessage(format.replace("{playername}", player.getDisplayName()).replace("{distance}", (int) distance + "")); - } - } + double range = SavageFactions.plugin.getConfig().getInt("fnear.Radius"); + String format = TL.COMMAND_NEAR_FORMAT.toString(); + fme.msg(TL.COMMAND_NEAR_USE_MSG); + for (Entity e : me.getNearbyEntities(range, 255, range)) { + if (e instanceof Player) { + Player player = (((Player) e).getPlayer()); + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fme.getFaction() == fplayer.getFaction()) { + double distance = me.getLocation().distance(player.getLocation()); + fme.sendMessage(format.replace("{playername}", player.getDisplayName()).replace("{distance}", (int) distance + "")); + } + } - } - } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_NEAR_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_NEAR_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java index 0d3dabe3..ba0c8f6b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOpen.java @@ -8,48 +8,48 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdOpen extends FCommand { - public CmdOpen() { - super(); - this.aliases.add("open"); + public CmdOpen() { + super(); + this.aliases.add("open"); - //this.requiredArgs.add(""); - this.optionalArgs.put("yes/no", "flip"); + //this.requiredArgs.add(""); + this.optionalArgs.put("yes/no", "flip"); - this.permission = Permission.OPEN.node; - this.disableOnLock = false; + this.permission = Permission.OPEN.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostOpen, TL.COMMAND_OPEN_TOOPEN, TL.COMMAND_OPEN_FOROPEN)) { - return; - } + @Override + public void perform() { + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostOpen, TL.COMMAND_OPEN_TOOPEN, TL.COMMAND_OPEN_FOROPEN)) { + return; + } - myFaction.setOpen(this.argAsBool(0, !myFaction.getOpen())); + myFaction.setOpen(this.argAsBool(0, !myFaction.getOpen())); - String open = myFaction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); + String open = myFaction.getOpen() ? TL.COMMAND_OPEN_OPEN.toString() : TL.COMMAND_OPEN_CLOSED.toString(); - // Inform - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (fplayer.getFactionId().equals(myFaction.getId())) { - fplayer.msg(TL.COMMAND_OPEN_CHANGES, fme.getName(), open); - continue; - } - fplayer.msg(TL.COMMAND_OPEN_CHANGED, myFaction.getTag(fplayer.getFaction()), open); - } - } + // Inform + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.getFactionId().equals(myFaction.getId())) { + fplayer.msg(TL.COMMAND_OPEN_CHANGES, fme.getName(), open); + continue; + } + fplayer.msg(TL.COMMAND_OPEN_CHANGED, myFaction.getTag(fplayer.getFaction()), open); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_OPEN_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OPEN_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java index 9811f02c..beb69334 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwner.java @@ -8,100 +8,100 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdOwner extends FCommand { - public CmdOwner() { - super(); - this.aliases.add("owner"); + public CmdOwner() { + super(); + this.aliases.add("owner"); - //this.requiredArgs.add(""); - this.optionalArgs.put("player name", "you"); + //this.requiredArgs.add(""); + this.optionalArgs.put("player name", "you"); - this.permission = Permission.OWNER.node; - this.disableOnLock = true; + this.permission = Permission.OWNER.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - // TODO: Fix colors! + // TODO: Fix colors! - @Override - public void perform() { - boolean hasBypass = fme.isAdminBypassing(); + @Override + public void perform() { + boolean hasBypass = fme.isAdminBypassing(); - if (!hasBypass && !assertHasFaction()) { - return; - } + if (!hasBypass && !assertHasFaction()) { + return; + } - if (!Conf.ownedAreasEnabled) { - fme.msg(TL.COMMAND_OWNER_DISABLED); - return; - } + if (!Conf.ownedAreasEnabled) { + fme.msg(TL.COMMAND_OWNER_DISABLED); + return; + } - if (!hasBypass && Conf.ownedAreasLimitPerFaction > 0 && myFaction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) { - fme.msg(TL.COMMAND_OWNER_LIMIT, Conf.ownedAreasLimitPerFaction); - return; - } + if (!hasBypass && Conf.ownedAreasLimitPerFaction > 0 && myFaction.getCountOfClaimsWithOwners() >= Conf.ownedAreasLimitPerFaction) { + fme.msg(TL.COMMAND_OWNER_LIMIT, Conf.ownedAreasLimitPerFaction); + return; + } - if (!hasBypass && !assertMinRole(Conf.ownedAreasModeratorsCanSet ? Role.MODERATOR : Role.LEADER)) { - return; - } + if (!hasBypass && !assertMinRole(Conf.ownedAreasModeratorsCanSet ? Role.MODERATOR : Role.LEADER)) { + return; + } - FLocation flocation = new FLocation(fme); + FLocation flocation = new FLocation(fme); - Faction factionHere = Board.getInstance().getFactionAt(flocation); - if (factionHere != myFaction) { - if (!factionHere.isNormal()) { - fme.msg(TL.COMMAND_OWNER_NOTCLAIMED); - return; - } + Faction factionHere = Board.getInstance().getFactionAt(flocation); + if (factionHere != myFaction) { + if (!factionHere.isNormal()) { + fme.msg(TL.COMMAND_OWNER_NOTCLAIMED); + return; + } - if (!hasBypass) { - fme.msg(TL.COMMAND_OWNER_WRONGFACTION); - return; - } - } + if (!hasBypass) { + fme.msg(TL.COMMAND_OWNER_WRONGFACTION); + return; + } + } - FPlayer target = this.argAsBestFPlayerMatch(0, fme); - if (target == null) { - return; - } + FPlayer target = this.argAsBestFPlayerMatch(0, fme); + if (target == null) { + return; + } - String playerName = target.getName(); + String playerName = target.getName(); - if (target.getFaction() != myFaction) { - fme.msg(TL.COMMAND_OWNER_NOTMEMBER, playerName); - return; - } + if (target.getFaction() != myFaction) { + fme.msg(TL.COMMAND_OWNER_NOTMEMBER, playerName); + return; + } - // if no player name was passed, and this claim does already have owners set, clear them - if (args.isEmpty() && myFaction.doesLocationHaveOwnersSet(flocation)) { - myFaction.clearClaimOwnership(flocation); - fme.msg(TL.COMMAND_OWNER_CLEARED); - return; - } + // if no player name was passed, and this claim does already have owners set, clear them + if (args.isEmpty() && myFaction.doesLocationHaveOwnersSet(flocation)) { + myFaction.clearClaimOwnership(flocation); + fme.msg(TL.COMMAND_OWNER_CLEARED); + return; + } - if (myFaction.isPlayerInOwnerList(target, flocation)) { - myFaction.removePlayerAsOwner(target, flocation); - fme.msg(TL.COMMAND_OWNER_REMOVED, playerName); - return; - } + if (myFaction.isPlayerInOwnerList(target, flocation)) { + myFaction.removePlayerAsOwner(target, flocation); + fme.msg(TL.COMMAND_OWNER_REMOVED, playerName); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostOwner, TL.COMMAND_OWNER_TOSET, TL.COMMAND_OWNER_FORSET)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostOwner, TL.COMMAND_OWNER_TOSET, TL.COMMAND_OWNER_FORSET)) { + return; + } - myFaction.setPlayerAsOwner(target, flocation); + myFaction.setPlayerAsOwner(target, flocation); - fme.msg(TL.COMMAND_OWNER_ADDED, playerName); - } + fme.msg(TL.COMMAND_OWNER_ADDED, playerName); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_OWNER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OWNER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java index ee49571e..4d0f77d1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdOwnerList.java @@ -9,64 +9,64 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdOwnerList extends FCommand { - public CmdOwnerList() { - super(); - this.aliases.add("ownerlist"); + public CmdOwnerList() { + super(); + this.aliases.add("ownerlist"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - this.permission = Permission.OWNERLIST.node; - this.disableOnLock = false; + this.permission = Permission.OWNERLIST.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - boolean hasBypass = fme.isAdminBypassing(); + @Override + public void perform() { + boolean hasBypass = fme.isAdminBypassing(); - if (!hasBypass && !assertHasFaction()) { - return; - } + if (!hasBypass && !assertHasFaction()) { + return; + } - if (!Conf.ownedAreasEnabled) { - fme.msg(TL.COMMAND_OWNERLIST_DISABLED); - return; - } + if (!Conf.ownedAreasEnabled) { + fme.msg(TL.COMMAND_OWNERLIST_DISABLED); + return; + } - FLocation flocation = new FLocation(fme); + FLocation flocation = new FLocation(fme); - if (Board.getInstance().getFactionAt(flocation) != myFaction) { - if (!hasBypass) { - fme.msg(TL.COMMAND_OWNERLIST_WRONGFACTION); - return; - } - //TODO: This code won't ever be called. - myFaction = Board.getInstance().getFactionAt(flocation); - if (!myFaction.isNormal()) { - fme.msg(TL.COMMAND_OWNERLIST_NOTCLAIMED); - return; - } - } + if (Board.getInstance().getFactionAt(flocation) != myFaction) { + if (!hasBypass) { + fme.msg(TL.COMMAND_OWNERLIST_WRONGFACTION); + return; + } + //TODO: This code won't ever be called. + myFaction = Board.getInstance().getFactionAt(flocation); + if (!myFaction.isNormal()) { + fme.msg(TL.COMMAND_OWNERLIST_NOTCLAIMED); + return; + } + } - String owners = myFaction.getOwnerListString(flocation); + String owners = myFaction.getOwnerListString(flocation); - if (owners == null || owners.isEmpty()) { - fme.msg(TL.COMMAND_OWNERLIST_NONE); - return; - } + if (owners == null || owners.isEmpty()) { + fme.msg(TL.COMMAND_OWNERLIST_NONE); + return; + } - fme.msg(TL.COMMAND_OWNERLIST_OWNERS, owners); - } + fme.msg(TL.COMMAND_OWNERLIST_OWNERS, owners); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_OWNERLIST_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_OWNERLIST_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java index ade8d076..29a789fe 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSee.java @@ -6,44 +6,44 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdPaypalSee extends FCommand { - public CmdPaypalSee() { - aliases.add("seepaypal"); - aliases.add("getpaypal"); - requiredArgs.add("faction"); - permission = Permission.ADMIN.node; - disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + public CmdPaypalSee() { + aliases.add("seepaypal"); + aliases.add("getpaypal"); + requiredArgs.add("faction"); + permission = Permission.ADMIN.node; + disableOnLock = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { - fme.msg(TL.GENERIC_DISABLED); - } else { - Faction faction = argAsFaction(0); + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { + fme.msg(TL.GENERIC_DISABLED); + } else { + Faction faction = argAsFaction(0); - if (faction != null) { - if (!faction.isWilderness() && !faction.isSafeZone() && !faction.isWarZone()) { - if (faction.getPaypal() != null) { - fme.msg(TL.COMMAND_PAYPALSEE_FACTION_PAYPAL.toString(), faction.getTag(), faction.getPaypal()); - } else { - fme.msg(TL.COMMAND_PAYPALSEE_FACTION_NOTSET.toString(), faction.getTag(), faction.getPaypal()); - } + if (faction != null) { + if (!faction.isWilderness() && !faction.isSafeZone() && !faction.isWarZone()) { + if (faction.getPaypal() != null) { + fme.msg(TL.COMMAND_PAYPALSEE_FACTION_PAYPAL.toString(), faction.getTag(), faction.getPaypal()); + } else { + fme.msg(TL.COMMAND_PAYPALSEE_FACTION_NOTSET.toString(), faction.getTag(), faction.getPaypal()); + } - } else { - fme.msg(TL.COMMAND_PAYPALSEE_FACTION_NOFACTION.toString(), me.getName()); - } - } - } - } + } else { + fme.msg(TL.COMMAND_PAYPALSEE_FACTION_NOFACTION.toString(), me.getName()); + } + } + } + } - public TL getUsageTranslation() { - return TL.COMMAND_PAYPALSEE_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_PAYPALSEE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSet.java b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSet.java index 35456fbd..02b1b3a4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSet.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPaypalSet.java @@ -6,34 +6,34 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPaypalSet extends FCommand { - public CmdPaypalSet() { - this.aliases.add("setpaypal"); - this.aliases.add("paypal"); - this.requiredArgs.add("email"); - this.permission = Permission.PAYPALSET.node; - this.disableOnLock = false; - this.senderMustBePlayer = true; - this.senderMustBeMember = false; - this.senderMustBeModerator = false; - this.senderMustBeColeader = true; - this.senderMustBeAdmin = false; + public CmdPaypalSet() { + this.aliases.add("setpaypal"); + this.aliases.add("paypal"); + this.requiredArgs.add("email"); + this.permission = Permission.PAYPALSET.node; + this.disableOnLock = false; + this.senderMustBePlayer = true; + this.senderMustBeMember = false; + this.senderMustBeModerator = false; + this.senderMustBeColeader = true; + this.senderMustBeAdmin = false; - } + } - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { - fme.msg(TL.GENERIC_DISABLED); - } else { - String paypal = argAsString(0); - if (paypal != null) { - myFaction.paypalSet(paypal); - fme.msg(TL.COMMAND_PAYPALSET_SUCCESSFUL, paypal); - } - } - } + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { + fme.msg(TL.GENERIC_DISABLED); + } else { + String paypal = argAsString(0); + if (paypal != null) { + myFaction.paypalSet(paypal); + fme.msg(TL.COMMAND_PAYPALSET_SUCCESSFUL, paypal); + } + } + } - public TL getUsageTranslation() { - return TL.COMMAND_PAYPALSET_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_PAYPALSET_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java index 02f6bb29..58151f98 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPeaceful.java @@ -8,55 +8,55 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPeaceful extends FCommand { - public CmdPeaceful() { - super(); - this.aliases.add("peaceful"); + public CmdPeaceful() { + super(); + this.aliases.add("peaceful"); - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); - this.permission = Permission.SET_PEACEFUL.node; - this.disableOnLock = true; + this.permission = Permission.SET_PEACEFUL.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - Faction faction = this.argAsFaction(0); - if (faction == null) { - return; - } + @Override + public void perform() { + Faction faction = this.argAsFaction(0); + if (faction == null) { + return; + } - String change; - if (faction.isPeaceful()) { - change = TL.COMMAND_PEACEFUL_REVOKE.toString(); - faction.setPeaceful(false); - } else { - change = TL.COMMAND_PEACEFUL_GRANT.toString(); - faction.setPeaceful(true); - } + String change; + if (faction.isPeaceful()) { + change = TL.COMMAND_PEACEFUL_REVOKE.toString(); + faction.setPeaceful(false); + } else { + change = TL.COMMAND_PEACEFUL_GRANT.toString(); + faction.setPeaceful(true); + } - // Inform all players - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - String blame = (fme == null ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true)); - if (fplayer.getFaction() == faction) { - fplayer.msg(TL.COMMAND_PEACEFUL_YOURS, blame, change); - } else { - fplayer.msg(TL.COMMAND_PEACEFUL_OTHER, blame, change, faction.getTag(fplayer)); - } - } + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + String blame = (fme == null ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true)); + if (fplayer.getFaction() == faction) { + fplayer.msg(TL.COMMAND_PEACEFUL_YOURS, blame, change); + } else { + fplayer.msg(TL.COMMAND_PEACEFUL_OTHER, blame, change, faction.getTag(fplayer)); + } + } - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PEACEFUL_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PEACEFUL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java b/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java index 6c942012..6c3f6541 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPerm.java @@ -16,111 +16,111 @@ import java.util.Set; public class CmdPerm extends FCommand { - public CmdPerm() { - super(); - this.aliases.add("perm"); - this.aliases.add("perms"); - this.aliases.add("permission"); - this.aliases.add("permissions"); + public CmdPerm() { + super(); + this.aliases.add("perm"); + this.aliases.add("perms"); + this.aliases.add("permission"); + this.aliases.add("permissions"); - this.optionalArgs.put("relation", "relation"); - this.optionalArgs.put("action", "action"); - this.optionalArgs.put("access", "access"); + this.optionalArgs.put("relation", "relation"); + this.optionalArgs.put("action", "action"); + this.optionalArgs.put("access", "access"); - this.disableOnLock = true; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = true; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = true; - } + } - @Override - public void perform() { - if (args.size() == 0) { - PermissableRelationGUI gui = new PermissableRelationGUI(fme); - gui.build(); + @Override + public void perform() { + if (args.size() == 0) { + PermissableRelationGUI gui = new PermissableRelationGUI(fme); + gui.build(); - me.openInventory(gui.getInventory()); - return; - } else if (args.size() == 1 && getPermissable(argAsString(0)) != null) { - PermissableActionGUI gui = new PermissableActionGUI(fme, getPermissable(argAsString(0))); - gui.build(); + me.openInventory(gui.getInventory()); + return; + } else if (args.size() == 1 && getPermissable(argAsString(0)) != null) { + PermissableActionGUI gui = new PermissableActionGUI(fme, getPermissable(argAsString(0))); + gui.build(); - me.openInventory(gui.getInventory()); - return; - } + me.openInventory(gui.getInventory()); + return; + } - // If not opening GUI, then setting the permission manually. - if (args.size() != 3) { - fme.msg(TL.COMMAND_PERM_DESCRIPTION); - return; - } + // If not opening GUI, then setting the permission manually. + if (args.size() != 3) { + fme.msg(TL.COMMAND_PERM_DESCRIPTION); + return; + } - Set permissables = new HashSet<>(); - Set permissableActions = new HashSet<>(); + Set permissables = new HashSet<>(); + Set permissableActions = new HashSet<>(); - boolean allRelations = argAsString(0).equalsIgnoreCase("all"); - boolean allActions = argAsString(1).equalsIgnoreCase("all"); + boolean allRelations = argAsString(0).equalsIgnoreCase("all"); + boolean allActions = argAsString(1).equalsIgnoreCase("all"); - if (allRelations) { - permissables.addAll(myFaction.getPermissions().keySet()); - } else { - Permissable permissable = getPermissable(argAsString(0)); + if (allRelations) { + permissables.addAll(myFaction.getPermissions().keySet()); + } else { + Permissable permissable = getPermissable(argAsString(0)); - if (permissable == null) { - fme.msg(TL.COMMAND_PERM_INVALID_RELATION); - return; - } + if (permissable == null) { + fme.msg(TL.COMMAND_PERM_INVALID_RELATION); + return; + } - permissables.add(permissable); - } + permissables.add(permissable); + } - if (allActions) { - permissableActions.addAll(Arrays.asList(PermissableAction.values())); - } else { - PermissableAction permissableAction = PermissableAction.fromString(argAsString(1)); - if (permissableAction == null) { - fme.msg(TL.COMMAND_PERM_INVALID_ACTION); - return; - } + if (allActions) { + permissableActions.addAll(Arrays.asList(PermissableAction.values())); + } else { + PermissableAction permissableAction = PermissableAction.fromString(argAsString(1)); + if (permissableAction == null) { + fme.msg(TL.COMMAND_PERM_INVALID_ACTION); + return; + } - permissableActions.add(permissableAction); - } + permissableActions.add(permissableAction); + } - Access access = Access.fromString(argAsString(2)); + Access access = Access.fromString(argAsString(2)); - if (access == null) { - fme.msg(TL.COMMAND_PERM_INVALID_ACCESS); - return; - } + if (access == null) { + fme.msg(TL.COMMAND_PERM_INVALID_ACCESS); + return; + } - for (Permissable permissable : permissables) { - for (PermissableAction permissableAction : permissableActions) { - fme.getFaction().setPermission(permissable, permissableAction, access); - } - } + for (Permissable permissable : permissables) { + for (PermissableAction permissableAction : permissableActions) { + fme.getFaction().setPermission(permissable, permissableAction, access); + } + } - fme.msg(TL.COMMAND_PERM_SET, argAsString(1), access.name(), argAsString(0)); - SavageFactions.plugin.log(String.format(TL.COMMAND_PERM_SET.toString(), argAsString(1), access.name(), argAsString(0)) + " for faction " + fme.getTag()); - } + fme.msg(TL.COMMAND_PERM_SET, argAsString(1), access.name(), argAsString(0)); + SavageFactions.plugin.log(String.format(TL.COMMAND_PERM_SET.toString(), argAsString(1), access.name(), argAsString(0)) + " for faction " + fme.getTag()); + } - private Permissable getPermissable(String name) { - if (Role.fromString(name.toUpperCase()) != null) { - return Role.fromString(name.toUpperCase()); - } else if (Relation.fromString(name.toUpperCase()) != null) { - return Relation.fromString(name.toUpperCase()); - } else { - return null; - } - } + private Permissable getPermissable(String name) { + if (Role.fromString(name.toUpperCase()) != null) { + return Role.fromString(name.toUpperCase()); + } else if (Relation.fromString(name.toUpperCase()) != null) { + return Relation.fromString(name.toUpperCase()); + } else { + return null; + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PERM_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PERM_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java index 369b8415..54e71cd0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanent.java @@ -1,63 +1,63 @@ -package com.massivecraft.factions.cmd; - -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.SavageFactions; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.zcore.util.TL; - - -public class CmdPermanent extends FCommand { - - public CmdPermanent() { - super(); - this.aliases.add("permanent"); - - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); - - this.permission = Permission.SET_PERMANENT.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() { - Faction faction = this.argAsFaction(0); - if (faction == null) { - return; - } - - String change; - if (faction.isPermanent()) { - change = TL.COMMAND_PERMANENT_REVOKE.toString(); - faction.setPermanent(false); - } else { - change = TL.COMMAND_PERMANENT_GRANT.toString(); - faction.setPermanent(true); - } - - SavageFactions.plugin.log((fme == null ? "A server admin" : fme.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); - - // Inform all players - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - String blame = (fme == null ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true)); - if (fplayer.getFaction() == faction) { - fplayer.msg(TL.COMMAND_PERMANENT_YOURS, blame, change); - } else { - fplayer.msg(TL.COMMAND_PERMANENT_OTHER, blame, change, faction.getTag(fplayer)); - } - } - } - - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PERMANENT_DESCRIPTION; - } -} +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.SavageFactions; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.zcore.util.TL; + + +public class CmdPermanent extends FCommand { + + public CmdPermanent() { + super(); + this.aliases.add("permanent"); + + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); + + this.permission = Permission.SET_PERMANENT.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction faction = this.argAsFaction(0); + if (faction == null) { + return; + } + + String change; + if (faction.isPermanent()) { + change = TL.COMMAND_PERMANENT_REVOKE.toString(); + faction.setPermanent(false); + } else { + change = TL.COMMAND_PERMANENT_GRANT.toString(); + faction.setPermanent(true); + } + + SavageFactions.plugin.log((fme == null ? "A server admin" : fme.getName()) + " " + change + " the faction \"" + faction.getTag() + "\"."); + + // Inform all players + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + String blame = (fme == null ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true)); + if (fplayer.getFaction() == faction) { + fplayer.msg(TL.COMMAND_PERMANENT_YOURS, blame, change); + } else { + fplayer.msg(TL.COMMAND_PERMANENT_OTHER, blame, change, faction.getTag(fplayer)); + } + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PERMANENT_DESCRIPTION; + } +} diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java index 5e0018d5..5e985ea1 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPermanentPower.java @@ -1,59 +1,59 @@ -package com.massivecraft.factions.cmd; - -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.zcore.util.TL; - -public class CmdPermanentPower extends FCommand { - public CmdPermanentPower() { - super(); - this.aliases.add("permanentpower"); - - this.requiredArgs.add("faction"); - this.requiredArgs.add("power"); - - this.permission = Permission.SET_PERMANENTPOWER.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() { - Faction targetFaction = this.argAsFaction(0); - if (targetFaction == null) { - return; - } - - Integer targetPower = this.argAsInt(1); - - targetFaction.setPermanentPower(targetPower); - - String change = TL.COMMAND_PERMANENTPOWER_REVOKE.toString(); - if (targetFaction.hasPermanentPower()) { - change = TL.COMMAND_PERMANENTPOWER_GRANT.toString(); - } - - // Inform sender - msg(TL.COMMAND_PERMANENTPOWER_SUCCESS, change, targetFaction.describeTo(fme)); - - // Inform all other players - for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) { - if (fplayer == fme) { - continue; - } - String blame = (fme == null ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true)); - fplayer.msg(TL.COMMAND_PERMANENTPOWER_FACTION, blame, change); - } - } - - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PERMANENTPOWER_DESCRIPTION; - } -} +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.zcore.util.TL; + +public class CmdPermanentPower extends FCommand { + public CmdPermanentPower() { + super(); + this.aliases.add("permanentpower"); + + this.requiredArgs.add("faction"); + this.requiredArgs.add("power"); + + this.permission = Permission.SET_PERMANENTPOWER.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + Faction targetFaction = this.argAsFaction(0); + if (targetFaction == null) { + return; + } + + Integer targetPower = this.argAsInt(1); + + targetFaction.setPermanentPower(targetPower); + + String change = TL.COMMAND_PERMANENTPOWER_REVOKE.toString(); + if (targetFaction.hasPermanentPower()) { + change = TL.COMMAND_PERMANENTPOWER_GRANT.toString(); + } + + // Inform sender + msg(TL.COMMAND_PERMANENTPOWER_SUCCESS, change, targetFaction.describeTo(fme)); + + // Inform all other players + for (FPlayer fplayer : targetFaction.getFPlayersWhereOnline(true)) { + if (fplayer == fme) { + continue; + } + String blame = (fme == null ? TL.GENERIC_SERVERADMIN.toString() : fme.describeTo(fplayer, true)); + fplayer.msg(TL.COMMAND_PERMANENTPOWER_FACTION, blame, change); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PERMANENTPOWER_DESCRIPTION; + } +} diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java index 985d8770..755ddbe0 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPower.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPower.java @@ -7,50 +7,50 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdPower extends FCommand { - public CmdPower() { - super(); - this.aliases.add("power"); - this.aliases.add("pow"); + public CmdPower() { + super(); + this.aliases.add("power"); + this.aliases.add("pow"); - //this.requiredArgs.add("faction tag"); - this.optionalArgs.put("player name", "you"); + //this.requiredArgs.add("faction tag"); + this.optionalArgs.put("player name", "you"); - this.permission = Permission.POWER.node; - this.disableOnLock = false; + this.permission = Permission.POWER.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - FPlayer target = this.argAsBestFPlayerMatch(0, fme); - if (target == null) { - return; - } + @Override + public void perform() { + FPlayer target = this.argAsBestFPlayerMatch(0, fme); + if (target == null) { + return; + } - if (target != fme && !Permission.POWER_ANY.has(sender, true)) { - return; - } + if (target != fme && !Permission.POWER_ANY.has(sender, true)) { + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostPower, TL.COMMAND_POWER_TOSHOW, TL.COMMAND_POWER_FORSHOW)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostPower, TL.COMMAND_POWER_TOSHOW, TL.COMMAND_POWER_FORSHOW)) { + return; + } - double powerBoost = target.getPowerBoost(); - String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_POWER_BONUS.toString() : TL.COMMAND_POWER_PENALTY.toString()) + powerBoost + ")"; - msg(TL.COMMAND_POWER_POWER, target.describeTo(fme, true), target.getPowerRounded(), target.getPowerMaxRounded(), boost); - } + double powerBoost = target.getPowerBoost(); + String boost = (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_POWER_BONUS.toString() : TL.COMMAND_POWER_PENALTY.toString()) + powerBoost + ")"; + msg(TL.COMMAND_POWER_POWER, target.describeTo(fme, true), target.getPowerRounded(), target.getPowerMaxRounded(), boost); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_POWER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_POWER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java index 53290afe..54a4d3b7 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPowerBoost.java @@ -1,88 +1,88 @@ -package com.massivecraft.factions.cmd; - -import com.massivecraft.factions.FPlayer; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.SavageFactions; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.zcore.util.TL; - -public class CmdPowerBoost extends FCommand { - - public CmdPowerBoost() { - super(); - this.aliases.add("powerboost"); - - this.requiredArgs.add("plugin|f|player|faction"); - this.requiredArgs.add("name"); - this.requiredArgs.add("# or reset"); - - this.permission = Permission.POWERBOOST.node; - this.disableOnLock = true; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() { - String type = this.argAsString(0).toLowerCase(); - boolean doPlayer = true; - if (type.equals("f") || type.equals("faction")) { - doPlayer = false; - } else if (!type.equals("plugin") && !type.equals("player")) { - msg(TL.COMMAND_POWERBOOST_HELP_1); - msg(TL.COMMAND_POWERBOOST_HELP_2); - return; - } - - Double targetPower = this.argAsDouble(2); - if (targetPower == null) { - if (this.argAsString(2).equalsIgnoreCase("reset")) { - targetPower = 0D; - } else { - msg(TL.COMMAND_POWERBOOST_INVALIDNUM); - return; - } - } - - String target; - - if (doPlayer) { - FPlayer targetPlayer = this.argAsBestFPlayerMatch(1); - if (targetPlayer == null) { - return; - } - - if (targetPower != 0) { - targetPower += targetPlayer.getPowerBoost(); - } - targetPlayer.setPowerBoost(targetPower); - target = TL.COMMAND_POWERBOOST_PLAYER.format(targetPlayer.getName()); - } else { - Faction targetFaction = this.argAsFaction(1); - if (targetFaction == null) { - return; - } - - if (targetPower != 0) { - targetPower += targetFaction.getPowerBoost(); - } - targetFaction.setPowerBoost(targetPower); - target = TL.COMMAND_POWERBOOST_FACTION.format(targetFaction.getTag()); - } - - int roundedPower = (int) Math.round(targetPower); - msg(TL.COMMAND_POWERBOOST_BOOST, target, roundedPower); - if (!senderIsConsole) { - SavageFactions.plugin.log(TL.COMMAND_POWERBOOST_BOOSTLOG.toString(), fme.getName(), target, roundedPower); - } - } - - @Override - public TL getUsageTranslation() { - return TL.COMMAND_POWERBOOST_DESCRIPTION; - } -} +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.FPlayer; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.SavageFactions; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.zcore.util.TL; + +public class CmdPowerBoost extends FCommand { + + public CmdPowerBoost() { + super(); + this.aliases.add("powerboost"); + + this.requiredArgs.add("plugin|f|player|faction"); + this.requiredArgs.add("name"); + this.requiredArgs.add("# or reset"); + + this.permission = Permission.POWERBOOST.node; + this.disableOnLock = true; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + String type = this.argAsString(0).toLowerCase(); + boolean doPlayer = true; + if (type.equals("f") || type.equals("faction")) { + doPlayer = false; + } else if (!type.equals("plugin") && !type.equals("player")) { + msg(TL.COMMAND_POWERBOOST_HELP_1); + msg(TL.COMMAND_POWERBOOST_HELP_2); + return; + } + + Double targetPower = this.argAsDouble(2); + if (targetPower == null) { + if (this.argAsString(2).equalsIgnoreCase("reset")) { + targetPower = 0D; + } else { + msg(TL.COMMAND_POWERBOOST_INVALIDNUM); + return; + } + } + + String target; + + if (doPlayer) { + FPlayer targetPlayer = this.argAsBestFPlayerMatch(1); + if (targetPlayer == null) { + return; + } + + if (targetPower != 0) { + targetPower += targetPlayer.getPowerBoost(); + } + targetPlayer.setPowerBoost(targetPower); + target = TL.COMMAND_POWERBOOST_PLAYER.format(targetPlayer.getName()); + } else { + Faction targetFaction = this.argAsFaction(1); + if (targetFaction == null) { + return; + } + + if (targetPower != 0) { + targetPower += targetFaction.getPowerBoost(); + } + targetFaction.setPowerBoost(targetPower); + target = TL.COMMAND_POWERBOOST_FACTION.format(targetFaction.getTag()); + } + + int roundedPower = (int) Math.round(targetPower); + msg(TL.COMMAND_POWERBOOST_BOOST, target, roundedPower); + if (!senderIsConsole) { + SavageFactions.plugin.log(TL.COMMAND_POWERBOOST_BOOSTLOG.toString(), fme.getName(), target, roundedPower); + } + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_POWERBOOST_DESCRIPTION; + } +} diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdPromote.java b/src/main/java/com/massivecraft/factions/cmd/CmdPromote.java index 699e740d..9bb67d32 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdPromote.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdPromote.java @@ -2,9 +2,9 @@ package com.massivecraft.factions.cmd; public class CmdPromote extends FPromoteCommand { - public CmdPromote() { - aliases.add("promote"); - aliases.add("promo"); - this.relative = 1; - } + public CmdPromote() { + aliases.add("promote"); + aliases.add("promo"); + this.relative = 1; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java index 2520994f..c66d907c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationAlly.java @@ -4,8 +4,8 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationAlly extends FRelationCommand { - public CmdRelationAlly() { - aliases.add("ally"); - targetRelation = Relation.ALLY; - } + public CmdRelationAlly() { + aliases.add("ally"); + targetRelation = Relation.ALLY; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java index 720f0efe..0da925c3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationEnemy.java @@ -4,8 +4,8 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationEnemy extends FRelationCommand { - public CmdRelationEnemy() { - aliases.add("enemy"); - targetRelation = Relation.ENEMY; - } + public CmdRelationEnemy() { + aliases.add("enemy"); + targetRelation = Relation.ENEMY; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java index 4dba5c03..104186e6 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationNeutral.java @@ -4,8 +4,8 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationNeutral extends FRelationCommand { - public CmdRelationNeutral() { - aliases.add("neutral"); - targetRelation = Relation.NEUTRAL; - } + public CmdRelationNeutral() { + aliases.add("neutral"); + targetRelation = Relation.NEUTRAL; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRelationTruce.java b/src/main/java/com/massivecraft/factions/cmd/CmdRelationTruce.java index 8136b22c..6cbe2a1e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRelationTruce.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRelationTruce.java @@ -4,8 +4,8 @@ import com.massivecraft.factions.struct.Relation; public class CmdRelationTruce extends FRelationCommand { - public CmdRelationTruce() { - aliases.add("truce"); - targetRelation = Relation.TRUCE; - } + public CmdRelationTruce() { + aliases.add("truce"); + targetRelation = Relation.TRUCE; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java index 7cf4b193..682fd9a3 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdReload.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdReload.java @@ -8,41 +8,41 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdReload extends FCommand { - public CmdReload() { - super(); - this.aliases.add("reload"); + public CmdReload() { + super(); + this.aliases.add("reload"); - this.permission = Permission.RELOAD.node; - this.disableOnLock = false; + this.permission = Permission.RELOAD.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - long timeInitStart = System.currentTimeMillis(); - Conf.load(); - Conf.save(); - SavageFactions.plugin.reloadConfig(); - SavageFactions.plugin.changeItemIDSInConfig(); - SavageFactions.plugin.loadLang(); - int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); + @Override + public void perform() { + long timeInitStart = System.currentTimeMillis(); + Conf.load(); + Conf.save(); + SavageFactions.plugin.reloadConfig(); + SavageFactions.plugin.changeItemIDSInConfig(); + SavageFactions.plugin.loadLang(); + int version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); - if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { - SavageFactions.plugin.factionsFlight = true; - } - long timeReload = (System.currentTimeMillis() - timeInitStart); + if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { + SavageFactions.plugin.factionsFlight = true; + } + long timeReload = (System.currentTimeMillis() - timeInitStart); - msg(TL.COMMAND_RELOAD_TIME, timeReload); - } + msg(TL.COMMAND_RELOAD_TIME, timeReload); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_RELOAD_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RELOAD_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdRules.java b/src/main/java/com/massivecraft/factions/cmd/CmdRules.java index d0c75666..9f4df0d5 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdRules.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdRules.java @@ -8,84 +8,84 @@ import java.util.HashMap; import java.util.List; public class CmdRules extends FCommand { - public CmdRules() { - super(); - aliases.add("r"); - aliases.add("rule"); - aliases.add("rules"); + public CmdRules() { + super(); + aliases.add("r"); + aliases.add("rule"); + aliases.add("rules"); - this.optionalArgs.put("add/remove/set/clear", ""); - this.errorOnToManyArgs = false; + this.optionalArgs.put("add/remove/set/clear", ""); + this.errorOnToManyArgs = false; - permission = Permission.RULES.node; + permission = Permission.RULES.node; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = true; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("frules.Enabled")) { - fme.msg(TL.COMMAND_RULES_DISABLED_MSG); - return; - } - if (this.args.size() == 0) { - HashMap rules = fme.getFaction().getRulesMap(); - if (rules.size() == 0) { - List ruleList = SavageFactions.plugin.getConfig().getStringList("frules.default-rules"); - fme.sendMessage(SavageFactions.plugin.colorList(ruleList)); + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("frules.Enabled")) { + fme.msg(TL.COMMAND_RULES_DISABLED_MSG); + return; + } + if (this.args.size() == 0) { + HashMap rules = fme.getFaction().getRulesMap(); + if (rules.size() == 0) { + List ruleList = SavageFactions.plugin.getConfig().getStringList("frules.default-rules"); + fme.sendMessage(SavageFactions.plugin.colorList(ruleList)); - } else { - for (int i = 0; i <= rules.size() - 1; i++) { - fme.sendMessage(SavageFactions.plugin.color(rules.get(i))); - } - } + } else { + for (int i = 0; i <= rules.size() - 1; i++) { + fme.sendMessage(SavageFactions.plugin.color(rules.get(i))); + } + } - } - if (this.args.size() == 1) { - if (args.get(0).equalsIgnoreCase("add")) { - fme.msg(TL.COMMAND_RULES_ADD_INVALIDARGS); - } - if (args.get(0).equalsIgnoreCase("set")) { - fme.msg(TL.COMMAND_RULES_SET_INVALIDARGS); - } - if (args.get(0).equalsIgnoreCase("remove")) { - fme.msg(TL.COMMAND_RULES_REMOVE_INVALIDARGS); - } - if (args.get(0).equalsIgnoreCase("clear")) { - fme.getFaction().clearRules(); - fme.msg(TL.COMMAND_RULES_CLEAR_SUCCESS); - } + } + if (this.args.size() == 1) { + if (args.get(0).equalsIgnoreCase("add")) { + fme.msg(TL.COMMAND_RULES_ADD_INVALIDARGS); + } + if (args.get(0).equalsIgnoreCase("set")) { + fme.msg(TL.COMMAND_RULES_SET_INVALIDARGS); + } + if (args.get(0).equalsIgnoreCase("remove")) { + fme.msg(TL.COMMAND_RULES_REMOVE_INVALIDARGS); + } + if (args.get(0).equalsIgnoreCase("clear")) { + fme.getFaction().clearRules(); + fme.msg(TL.COMMAND_RULES_CLEAR_SUCCESS); + } - } - if (this.args.size() >= 2) { - if (args.get(0).equalsIgnoreCase("add")) { - String message = ""; - StringBuilder string = new StringBuilder(message); - for (int i = 1; i <= args.size() - 1; i++) { - string.append(" " + args.get(i)); - } - fme.getFaction().addRule(string.toString()); - fme.msg(TL.COMMAND_RULES_ADD_SUCCESS); - } + } + if (this.args.size() >= 2) { + if (args.get(0).equalsIgnoreCase("add")) { + String message = ""; + StringBuilder string = new StringBuilder(message); + for (int i = 1; i <= args.size() - 1; i++) { + string.append(" " + args.get(i)); + } + fme.getFaction().addRule(string.toString()); + fme.msg(TL.COMMAND_RULES_ADD_SUCCESS); + } - if (this.args.size() == 2) { - if (args.get(0).equalsIgnoreCase("remove")) { - int index = argAsInt(1); - fme.getFaction().removeRule(index - 1); - fme.msg(TL.COMMAND_RULES_REMOVE_SUCCESS); - } - } + if (this.args.size() == 2) { + if (args.get(0).equalsIgnoreCase("remove")) { + int index = argAsInt(1); + fme.getFaction().removeRule(index - 1); + fme.msg(TL.COMMAND_RULES_REMOVE_SUCCESS); + } + } - } - } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_RULES_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RULES_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSB.java b/src/main/java/com/massivecraft/factions/cmd/CmdSB.java index e0f18a3b..dedbfd9d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSB.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSB.java @@ -6,28 +6,28 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSB extends FCommand { - public CmdSB() { - this.aliases.add("sb"); - this.aliases.add("scoreboard"); - this.permission = Permission.SCOREBOARD.node; - this.senderMustBePlayer = true; - } + public CmdSB() { + this.aliases.add("sb"); + this.aliases.add("scoreboard"); + this.permission = Permission.SCOREBOARD.node; + this.senderMustBePlayer = true; + } - @Override - public void perform() { - boolean toggleTo = !fme.showScoreboard(); - FScoreboard board = FScoreboard.get(fme); - if (board == null) { - me.sendMessage(TL.COMMAND_TOGGLESB_DISABLED.toString()); - } else { - me.sendMessage(TL.TOGGLE_SB.toString().replace("{value}", String.valueOf(toggleTo))); - board.setSidebarVisibility(toggleTo); - } - fme.setShowScoreboard(toggleTo); - } + @Override + public void perform() { + boolean toggleTo = !fme.showScoreboard(); + FScoreboard board = FScoreboard.get(fme); + if (board == null) { + me.sendMessage(TL.COMMAND_TOGGLESB_DISABLED.toString()); + } else { + me.sendMessage(TL.TOGGLE_SB.toString().replace("{value}", String.valueOf(toggleTo))); + board.setSidebarVisibility(toggleTo); + } + fme.setShowScoreboard(toggleTo); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SCOREBOARD_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SCOREBOARD_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java index 520708f0..705b957c 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSafeunclaimall.java @@ -11,52 +11,52 @@ import org.bukkit.World; public class CmdSafeunclaimall extends FCommand { - public CmdSafeunclaimall() { - this.aliases.add("safeunclaimall"); - this.aliases.add("safedeclaimall"); + public CmdSafeunclaimall() { + this.aliases.add("safeunclaimall"); + this.aliases.add("safedeclaimall"); - //this.requiredArgs.add(""); - this.optionalArgs.put("world", "all"); + //this.requiredArgs.add(""); + this.optionalArgs.put("world", "all"); - this.permission = Permission.MANAGE_SAFE_ZONE.node; - this.disableOnLock = true; + this.permission = Permission.MANAGE_SAFE_ZONE.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - String worldName = argAsString(0); - World world = null; + @Override + public void perform() { + String worldName = argAsString(0); + World world = null; - if (worldName != null) { - world = Bukkit.getWorld(worldName); - } + if (worldName != null) { + world = Bukkit.getWorld(worldName); + } - String id = Factions.getInstance().getSafeZone().getId(); + String id = Factions.getInstance().getSafeZone().getId(); - if (world == null) { - Board.getInstance().unclaimAll(id); - } else { - Board.getInstance().unclaimAllInWorld(id, world); - } + if (world == null) { + Board.getInstance().unclaimAll(id); + } else { + Board.getInstance().unclaimAllInWorld(id, world); + } - msg(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMED); + msg(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMED); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG.format(sender.getName())); - } - } + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG.format(sender.getName())); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SAFEUNCLAIMALL_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SAFEUNCLAIMALL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java index 98c23bb1..1d0e27b9 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSaveAll.java @@ -1,44 +1,44 @@ -package com.massivecraft.factions.cmd; - -import com.massivecraft.factions.Board; -import com.massivecraft.factions.Conf; -import com.massivecraft.factions.FPlayers; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.struct.Permission; -import com.massivecraft.factions.zcore.util.TL; - -public class CmdSaveAll extends FCommand { - - public CmdSaveAll() { - super(); - this.aliases.add("saveall"); - this.aliases.add("save"); - - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); - - this.permission = Permission.SAVE.node; - this.disableOnLock = false; - - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } - - @Override - public void perform() { - FPlayers.getInstance().forceSave(false); - Factions.getInstance().forceSave(false); - Board.getInstance().forceSave(false); - Conf.save(); - msg(TL.COMMAND_SAVEALL_SUCCESS); - } - - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SAVEALL_DESCRIPTION; - } - +package com.massivecraft.factions.cmd; + +import com.massivecraft.factions.Board; +import com.massivecraft.factions.Conf; +import com.massivecraft.factions.FPlayers; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.struct.Permission; +import com.massivecraft.factions.zcore.util.TL; + +public class CmdSaveAll extends FCommand { + + public CmdSaveAll() { + super(); + this.aliases.add("saveall"); + this.aliases.add("save"); + + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); + + this.permission = Permission.SAVE.node; + this.disableOnLock = false; + + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } + + @Override + public void perform() { + FPlayers.getInstance().forceSave(false); + Factions.getInstance().forceSave(false); + Board.getInstance().forceSave(false); + Conf.save(); + msg(TL.COMMAND_SAVEALL_SUCCESS); + } + + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SAVEALL_DESCRIPTION; + } + } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java b/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java index 72327d6e..a32d1f38 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSeeChunk.java @@ -15,137 +15,137 @@ import java.util.Iterator; public class CmdSeeChunk extends FCommand { - //Used a hashmap cuz imma make a particle selection gui later, will store it where the boolean is rn. - public static HashMap seeChunkMap = new HashMap<>(); - Long interval = 10L; - private boolean useParticles; - private int length; - private ParticleEffect effect; - private int taskID = -1; + //Used a hashmap cuz imma make a particle selection gui later, will store it where the boolean is rn. + public static HashMap seeChunkMap = new HashMap<>(); + Long interval = 10L; + private boolean useParticles; + private int length; + private ParticleEffect effect; + private int taskID = -1; - //I remade it cause of people getting mad that I had the same seechunk as drtshock + //I remade it cause of people getting mad that I had the same seechunk as drtshock - public CmdSeeChunk() { - super(); - aliases.add("seechunk"); - aliases.add("sc"); + public CmdSeeChunk() { + super(); + aliases.add("seechunk"); + aliases.add("sc"); - permission = Permission.SEECHUNK.node; + permission = Permission.SEECHUNK.node; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; - this.useParticles = p.getConfig().getBoolean("see-chunk.particles", true); - interval = SavageFactions.plugin.getConfig().getLong("see-chunk.interval", 10L); - if (effect == null) { - effect = ParticleEffect.REDSTONE; - } + this.useParticles = p.getConfig().getBoolean("see-chunk.particles", true); + interval = SavageFactions.plugin.getConfig().getLong("see-chunk.interval", 10L); + if (effect == null) { + effect = ParticleEffect.REDSTONE; + } - } + } - @Override - public void perform() { - if (seeChunkMap.containsKey(me.getName())) { - seeChunkMap.remove(me.getName()); - msg(TL.COMMAND_SEECHUNK_DISABLED); - } else { - seeChunkMap.put(me.getName(), true); - msg(TL.COMMAND_SEECHUNK_ENABLED); - manageTask(); - } - } + @Override + public void perform() { + if (seeChunkMap.containsKey(me.getName())) { + seeChunkMap.remove(me.getName()); + msg(TL.COMMAND_SEECHUNK_DISABLED); + } else { + seeChunkMap.put(me.getName(), true); + msg(TL.COMMAND_SEECHUNK_ENABLED); + manageTask(); + } + } - private void manageTask() { - if (taskID != -1) { - if (seeChunkMap.keySet().size() == 0) { - Bukkit.getScheduler().cancelTask(taskID); - taskID = -1; - } - } else { - startTask(); - } - } + private void manageTask() { + if (taskID != -1) { + if (seeChunkMap.keySet().size() == 0) { + Bukkit.getScheduler().cancelTask(taskID); + taskID = -1; + } + } else { + startTask(); + } + } - private void startTask() { - taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - Iterator itr = seeChunkMap.keySet().iterator(); - while (itr.hasNext()) { - Object nameObject = itr.next(); - String name = nameObject + ""; - Player player = Bukkit.getPlayer(name); - showBorders(player); - } - manageTask(); - } - }, 0, interval); - } + private void startTask() { + taskID = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + Iterator itr = seeChunkMap.keySet().iterator(); + while (itr.hasNext()) { + Object nameObject = itr.next(); + String name = nameObject + ""; + Player player = Bukkit.getPlayer(name); + showBorders(player); + } + manageTask(); + } + }, 0, interval); + } - private void showBorders(Player me) { - World world = me.getWorld(); - FLocation flocation = new FLocation(me); - int chunkX = (int) flocation.getX(); - int chunkZ = (int) flocation.getZ(); + private void showBorders(Player me) { + World world = me.getWorld(); + FLocation flocation = new FLocation(me); + int chunkX = (int) flocation.getX(); + int chunkZ = (int) flocation.getZ(); - int blockX; - int blockZ; + int blockX; + int blockZ; - blockX = chunkX * 16; - blockZ = chunkZ * 16; - showPillar(me, world, blockX, blockZ); + blockX = chunkX * 16; + blockZ = chunkZ * 16; + showPillar(me, world, blockX, blockZ); - blockX = chunkX * 16 + 15; - blockZ = chunkZ * 16; - showPillar(me, world, blockX, blockZ); + blockX = chunkX * 16 + 15; + blockZ = chunkZ * 16; + showPillar(me, world, blockX, blockZ); - blockX = chunkX * 16; - blockZ = chunkZ * 16 + 15; - showPillar(me, world, blockX, blockZ); + blockX = chunkX * 16; + blockZ = chunkZ * 16 + 15; + showPillar(me, world, blockX, blockZ); - blockX = chunkX * 16 + 15; - blockZ = chunkZ * 16 + 15; - showPillar(me, world, blockX, blockZ); - } + blockX = chunkX * 16 + 15; + blockZ = chunkZ * 16 + 15; + showPillar(me, world, blockX, blockZ); + } - private void showPillar(Player player, World world, int blockX, int blockZ) { - for (int blockY = 0; blockY < player.getLocation().getBlockY() + 30; blockY++) { - Location loc = new Location(world, blockX, blockY, blockZ).add(0.5, 0, 0.5); - if (loc.getBlock().getType() != Material.AIR) { - continue; - } - if (useParticles) { - if (SavageFactions.plugin.useNonPacketParticles) { - // Dust options only exists in the 1.13 API, so we use an - // alternative method to achieve this in lower versions. - if (SavageFactions.plugin.mc113) { - player.spawnParticle(Particle.REDSTONE, loc, 0, new Particle.DustOptions(Color.RED, 1)); - } else { - player.getWorld().spawnParticle(Particle.REDSTONE, loc, 0, 255, 0, 0, 1); - } + private void showPillar(Player player, World world, int blockX, int blockZ) { + for (int blockY = 0; blockY < player.getLocation().getBlockY() + 30; blockY++) { + Location loc = new Location(world, blockX, blockY, blockZ).add(0.5, 0, 0.5); + if (loc.getBlock().getType() != Material.AIR) { + continue; + } + if (useParticles) { + if (SavageFactions.plugin.useNonPacketParticles) { + // Dust options only exists in the 1.13 API, so we use an + // alternative method to achieve this in lower versions. + if (SavageFactions.plugin.mc113) { + player.spawnParticle(Particle.REDSTONE, loc, 0, new Particle.DustOptions(Color.RED, 1)); + } else { + player.getWorld().spawnParticle(Particle.REDSTONE, loc, 0, 255, 0, 0, 1); + } - } else { - this.effect.display(0, 0, 0, 0, 1, loc, player); - } + } else { + this.effect.display(0, 0, 0, 0, 1, loc, player); + } - } else { - Material type = blockY % 5 == 0 ? SavageFactions.plugin.REDSTONE_LAMP_ON : SavageFactions.plugin.STAINED_GLASS; - VisualizeUtil.addLocation(player, loc, type); - } - } - } + } else { + Material type = blockY % 5 == 0 ? SavageFactions.plugin.REDSTONE_LAMP_ON : SavageFactions.plugin.STAINED_GLASS; + VisualizeUtil.addLocation(player, loc, type); + } + } + } - @Override - public TL getUsageTranslation() { - return TL.GENERIC_PLACEHOLDER; - } + @Override + public TL getUsageTranslation() { + return TL.GENERIC_PLACEHOLDER; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSetBanner.java b/src/main/java/com/massivecraft/factions/cmd/CmdSetBanner.java index 1558b54d..ed4e0249 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetBanner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetBanner.java @@ -5,35 +5,35 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSetBanner extends FCommand { - public CmdSetBanner() { - super(); - aliases.add("setbanner"); + public CmdSetBanner() { + super(); + aliases.add("setbanner"); - permission = Permission.BANNER.node; + permission = Permission.BANNER.node; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = true; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = true; - } + } - public void perform() { - if (!me.getItemInHand().getType().toString().contains("BANNER")) { - fme.msg(TL.COMMAND_SETBANNER_NOTBANNER); - return; - } + public void perform() { + if (!me.getItemInHand().getType().toString().contains("BANNER")) { + fme.msg(TL.COMMAND_SETBANNER_NOTBANNER); + return; + } - fme.getFaction().setBannerPattern(me.getItemInHand()); - fme.msg(TL.COMMAND_SETBANNER_SUCCESS); + fme.getFaction().setBannerPattern(me.getItemInHand()); + fme.msg(TL.COMMAND_SETBANNER_SUCCESS); - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SETBANNER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETBANNER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java b/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java index 9735f1c0..8bd5a49d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetDefaultRole.java @@ -6,43 +6,43 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSetDefaultRole extends FCommand { - public CmdSetDefaultRole() { - super(); + public CmdSetDefaultRole() { + super(); - this.aliases.add("defaultrole"); - this.aliases.add("defaultrank"); - this.aliases.add("default"); - this.aliases.add("def"); - this.requiredArgs.add("role"); + this.aliases.add("defaultrole"); + this.aliases.add("defaultrank"); + this.aliases.add("default"); + this.aliases.add("def"); + this.requiredArgs.add("role"); - this.senderMustBeAdmin = true; - this.senderMustBePlayer = true; - senderMustBeColeader = false; + this.senderMustBeAdmin = true; + this.senderMustBePlayer = true; + senderMustBeColeader = false; - this.permission = Permission.DEFAULTRANK.node; - } + this.permission = Permission.DEFAULTRANK.node; + } - @Override - public void perform() { - Role target = Role.fromString(argAsString(0).toUpperCase()); - if (target == null) { - msg(TL.COMMAND_SETDEFAULTROLE_INVALIDROLE, argAsString(0)); - return; - } + @Override + public void perform() { + Role target = Role.fromString(argAsString(0).toUpperCase()); + if (target == null) { + msg(TL.COMMAND_SETDEFAULTROLE_INVALIDROLE, argAsString(0)); + return; + } - if (target == Role.LEADER) { - msg(TL.COMMAND_SETDEFAULTROLE_NOTTHATROLE, argAsString(0)); - return; - } + if (target == Role.LEADER) { + msg(TL.COMMAND_SETDEFAULTROLE_NOTTHATROLE, argAsString(0)); + return; + } - myFaction.setDefaultRole(target); - msg(TL.COMMAND_SETDEFAULTROLE_SUCCESS, target.nicename); - } + myFaction.setDefaultRole(target); + msg(TL.COMMAND_SETDEFAULTROLE_SUCCESS, target.nicename); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SETDEFAULTROLE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETDEFAULTROLE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSetFWarp.java b/src/main/java/com/massivecraft/factions/cmd/CmdSetFWarp.java index 6914ac0b..f60d5770 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetFWarp.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetFWarp.java @@ -12,72 +12,72 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSetFWarp extends FCommand { - public CmdSetFWarp() { - super(); + public CmdSetFWarp() { + super(); - this.aliases.add("setwarp"); - this.aliases.add("sw"); + this.aliases.add("setwarp"); + this.aliases.add("sw"); - this.requiredArgs.add("warp name"); - this.optionalArgs.put("password", "password"); + this.requiredArgs.add("warp name"); + this.optionalArgs.put("password", "password"); - this.senderMustBeMember = true; - this.senderMustBeModerator = false; + this.senderMustBeMember = true; + this.senderMustBeModerator = false; - this.senderMustBePlayer = true; + this.senderMustBePlayer = true; - this.permission = Permission.SETWARP.node; - } + this.permission = Permission.SETWARP.node; + } - @Override - public void perform() { - if (!(fme.getRelationToLocation() == Relation.MEMBER)) { - fme.msg(TL.COMMAND_SETFWARP_NOTCLAIMED); - return; - } + @Override + public void perform() { + if (!(fme.getRelationToLocation() == Relation.MEMBER)) { + fme.msg(TL.COMMAND_SETFWARP_NOTCLAIMED); + return; + } - // This statement allows us to check if they've specifically denied it, or default to - // the old setting of allowing moderators to set warps. - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.SETWARP); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "set warps"); - return; - } - } + // This statement allows us to check if they've specifically denied it, or default to + // the old setting of allowing moderators to set warps. + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.SETWARP); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "set warps"); + return; + } + } - String warp = argAsString(0); + String warp = argAsString(0); - // Checks if warp with same name already exists and ignores maxWarp check if it does. - boolean warpExists = myFaction.isWarp(warp); + // Checks if warp with same name already exists and ignores maxWarp check if it does. + boolean warpExists = myFaction.isWarp(warp); - int maxWarps = SavageFactions.plugin.getConfig().getInt("max-warps", 5); - boolean tooManyWarps = maxWarps <= myFaction.getWarps().size(); - if (tooManyWarps && !warpExists) { - fme.msg(TL.COMMAND_SETFWARP_LIMIT, maxWarps); - return; - } + int maxWarps = SavageFactions.plugin.getConfig().getInt("max-warps", 5); + boolean tooManyWarps = maxWarps <= myFaction.getWarps().size(); + if (tooManyWarps && !warpExists) { + fme.msg(TL.COMMAND_SETFWARP_LIMIT, maxWarps); + return; + } - if (!transact(fme)) { - return; - } + if (!transact(fme)) { + return; + } - String password = argAsString(1); + String password = argAsString(1); - LazyLocation loc = new LazyLocation(fme.getPlayer().getLocation()); - myFaction.setWarp(warp, loc); - if (password != null) { - myFaction.setWarpPassword(warp, password); - } - fme.msg(TL.COMMAND_SETFWARP_SET, warp, password != null ? password : ""); - } + LazyLocation loc = new LazyLocation(fme.getPlayer().getLocation()); + myFaction.setWarp(warp, loc); + if (password != null) { + myFaction.setWarpPassword(warp, password); + } + fme.msg(TL.COMMAND_SETFWARP_SET, warp, password != null ? password : ""); + } - private boolean transact(FPlayer player) { - return !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || payForCommand(SavageFactions.plugin.getConfig().getDouble("warp-cost.setwarp", 5), TL.COMMAND_SETFWARP_TOSET.toString(), TL.COMMAND_SETFWARP_FORSET.toString()); - } + private boolean transact(FPlayer player) { + return !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing() || payForCommand(SavageFactions.plugin.getConfig().getDouble("warp-cost.setwarp", 5), TL.COMMAND_SETFWARP_TOSET.toString(), TL.COMMAND_SETFWARP_FORSET.toString()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SETFWARP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETFWARP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java b/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java index 1f3a98f9..de49364e 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSetMaxVaults.java @@ -7,44 +7,44 @@ import org.bukkit.ChatColor; public class CmdSetMaxVaults extends FCommand { - public CmdSetMaxVaults() { - this.aliases.add("setmaxvaults"); - this.aliases.add("smv"); + public CmdSetMaxVaults() { + this.aliases.add("setmaxvaults"); + this.aliases.add("smv"); - this.requiredArgs.add("faction"); - this.requiredArgs.add("number"); + this.requiredArgs.add("faction"); + this.requiredArgs.add("number"); - this.permission = Permission.SETMAXVAULTS.node; - this.disableOnLock = false; + this.permission = Permission.SETMAXVAULTS.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - Faction targetFaction = argAsFaction(0); - int value = argAsInt(1, -1); - if (value < 0) { - sender.sendMessage(ChatColor.RED + "Number must be greater than 0."); - return; - } + @Override + public void perform() { + Faction targetFaction = argAsFaction(0); + int value = argAsInt(1, -1); + if (value < 0) { + sender.sendMessage(ChatColor.RED + "Number must be greater than 0."); + return; + } - if (targetFaction == null) { - sender.sendMessage(ChatColor.RED + "Couldn't find Faction: " + ChatColor.YELLOW + argAsString(0)); - return; - } + if (targetFaction == null) { + sender.sendMessage(ChatColor.RED + "Couldn't find Faction: " + ChatColor.YELLOW + argAsString(0)); + return; + } - targetFaction.setMaxVaults(value); - sender.sendMessage(TL.COMMAND_SETMAXVAULTS_SUCCESS.format(targetFaction.getTag(), value)); - } + targetFaction.setMaxVaults(value); + sender.sendMessage(TL.COMMAND_SETMAXVAULTS_SUCCESS.format(targetFaction.getTag(), value)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SETMAXVAULTS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETMAXVAULTS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java index b9440e05..eaf2c94d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdSethome.java @@ -12,68 +12,68 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdSethome extends FCommand { - public CmdSethome() { - this.aliases.add("sethome"); + public CmdSethome() { + this.aliases.add("sethome"); - //this.requiredArgs.add(""); - this.optionalArgs.put("faction tag", "mine"); + //this.requiredArgs.add(""); + this.optionalArgs.put("faction tag", "mine"); - this.permission = Permission.SETHOME.node; - this.disableOnLock = true; + this.permission = Permission.SETHOME.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (!Conf.homesEnabled) { - fme.msg(TL.COMMAND_SETHOME_DISABLED); - return; - } + @Override + public void perform() { + if (!Conf.homesEnabled) { + fme.msg(TL.COMMAND_SETHOME_DISABLED); + return; + } - Faction faction = this.argAsFaction(0, myFaction); - if (faction == null) { - return; - } + Faction faction = this.argAsFaction(0, myFaction); + if (faction == null) { + return; + } - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.SETHOME); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER && !Permission.SETHOME_ANY.has(sender, true)) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "set home"); - return; - } - } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.SETHOME); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER && !Permission.SETHOME_ANY.has(sender, true)) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "set home"); + return; + } + } - // Can the player set the faction home HERE? - if (!Permission.BYPASS.has(me) && - Conf.homesMustBeInClaimedTerritory && - Board.getInstance().getFactionAt(new FLocation(me)) != faction) { - fme.msg(TL.COMMAND_SETHOME_NOTCLAIMED); - return; - } + // Can the player set the faction home HERE? + if (!Permission.BYPASS.has(me) && + Conf.homesMustBeInClaimedTerritory && + Board.getInstance().getFactionAt(new FLocation(me)) != faction) { + fme.msg(TL.COMMAND_SETHOME_NOTCLAIMED); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostSethome, TL.COMMAND_SETHOME_TOSET, TL.COMMAND_SETHOME_FORSET)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostSethome, TL.COMMAND_SETHOME_TOSET, TL.COMMAND_SETHOME_FORSET)) { + return; + } - faction.setHome(me.getLocation()); + faction.setHome(me.getLocation()); - faction.msg(TL.COMMAND_SETHOME_SET, fme.describeTo(myFaction, true)); - faction.sendMessage(p.cmdBase.cmdHome.getUseageTemplate()); - if (faction != myFaction) { - fme.msg(TL.COMMAND_SETHOME_SETOTHER, faction.getTag(fme)); - } - } + faction.msg(TL.COMMAND_SETHOME_SET, fme.describeTo(myFaction, true)); + faction.sendMessage(p.cmdBase.cmdHome.getUseageTemplate()); + if (faction != myFaction) { + fme.msg(TL.COMMAND_SETHOME_SETOTHER, faction.getTag(fme)); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SETHOME_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SETHOME_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java index 66ae2ee8..ee437b55 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShow.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShow.java @@ -14,105 +14,105 @@ import java.util.List; public class CmdShow extends FCommand { - List defaults = new ArrayList<>(); + List defaults = new ArrayList<>(); - public CmdShow() { - this.aliases.add("show"); - this.aliases.add("who"); + public CmdShow() { + this.aliases.add("show"); + this.aliases.add("who"); - // add defaults to /f show in case config doesnt have it - defaults.add("{header}"); - defaults.add("Description: {description}"); - defaults.add("Joining: {joining} {peaceful}"); - defaults.add("Land / Power / Maxpower: {chunks} / {power} / {maxPower}"); - defaults.add("Founded: {create-date}"); - defaults.add("This faction is permanent, remaining even with no members."); - defaults.add("Land value: {land-value} {land-refund}"); - defaults.add("Balance: {faction-balance}"); - defaults.add("Allies({allies}/{max-allies}): {allies-list}"); - defaults.add("Online: ({online}/{members}): {online-list}"); - defaults.add("Offline: ({offline}/{members}): {offline-list}"); + // add defaults to /f show in case config doesnt have it + defaults.add("{header}"); + defaults.add("Description: {description}"); + defaults.add("Joining: {joining} {peaceful}"); + defaults.add("Land / Power / Maxpower: {chunks} / {power} / {maxPower}"); + defaults.add("Founded: {create-date}"); + defaults.add("This faction is permanent, remaining even with no members."); + defaults.add("Land value: {land-value} {land-refund}"); + defaults.add("Balance: {faction-balance}"); + defaults.add("Allies({allies}/{max-allies}): {allies-list}"); + defaults.add("Online: ({online}/{members}): {online-list}"); + defaults.add("Offline: ({offline}/{members}): {offline-list}"); - // this.requiredArgs.add(""); - this.optionalArgs.put("faction tag", "yours"); + // this.requiredArgs.add(""); + this.optionalArgs.put("faction tag", "yours"); - this.permission = Permission.SHOW.node; - this.disableOnLock = false; + this.permission = Permission.SHOW.node; + this.disableOnLock = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Faction faction = myFaction; - if (this.argIsSet(0)) - faction = this.argAsFaction(0); + @Override + public void perform() { + Faction faction = myFaction; + if (this.argIsSet(0)) + faction = this.argAsFaction(0); - if (faction == null) - return; + if (faction == null) + return; - if (fme != null && !fme.getPlayer().hasPermission("factions.show.bypassexempt") - && SavageFactions.plugin.getConfig().getStringList("show-exempt").contains(faction.getTag())) { - msg(TL.COMMAND_SHOW_EXEMPT); - return; - } + if (fme != null && !fme.getPlayer().hasPermission("factions.show.bypassexempt") + && SavageFactions.plugin.getConfig().getStringList("show-exempt").contains(faction.getTag())) { + msg(TL.COMMAND_SHOW_EXEMPT); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostShow, TL.COMMAND_SHOW_TOSHOW, TL.COMMAND_SHOW_FORSHOW)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostShow, TL.COMMAND_SHOW_TOSHOW, TL.COMMAND_SHOW_FORSHOW)) { + return; + } - List show = SavageFactions.plugin.getConfig().getStringList("show"); - if (show == null || show.isEmpty()) - show = defaults; + List show = SavageFactions.plugin.getConfig().getStringList("show"); + if (show == null || show.isEmpty()) + show = defaults; - if (!faction.isNormal()) { - String tag = faction.getTag(fme); - // send header and that's all - String header = show.get(0); - if (TagReplacer.HEADER.contains(header)) { - msg(p.txt.titleize(tag)); - } else { - msg(p.txt.parse(TagReplacer.FACTION.replace(header, tag))); - } - return; // we only show header for non-normal factions - } + if (!faction.isNormal()) { + String tag = faction.getTag(fme); + // send header and that's all + String header = show.get(0); + if (TagReplacer.HEADER.contains(header)) { + msg(p.txt.titleize(tag)); + } else { + msg(p.txt.parse(TagReplacer.FACTION.replace(header, tag))); + } + return; // we only show header for non-normal factions + } - for (String raw : show) { - String parsed = TagUtil.parsePlain(faction, fme, raw); // use relations - if (parsed == null) { - continue; // Due to minimal f show. - } + for (String raw : show) { + String parsed = TagUtil.parsePlain(faction, fme, raw); // use relations + if (parsed == null) { + continue; // Due to minimal f show. + } - if (fme != null) { - parsed = TagUtil.parsePlaceholders(fme.getPlayer(), parsed); - } + if (fme != null) { + parsed = TagUtil.parsePlaceholders(fme.getPlayer(), parsed); + } - if (TagUtil.hasFancy(parsed)) { - List fancy = TagUtil.parseFancy(faction, fme, parsed); - if (fancy != null) - sendFancyMessage(fancy); + if (TagUtil.hasFancy(parsed)) { + List fancy = TagUtil.parseFancy(faction, fme, parsed); + if (fancy != null) + sendFancyMessage(fancy); - continue; - } - if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { - if (parsed.contains("{ig}")) { - // replaces all variables with no home TL - parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); - } - if (parsed.contains("%")) { - parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. - } - msg(p.txt.parse(parsed)); - } - } - } + continue; + } + if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { + if (parsed.contains("{ig}")) { + // replaces all variables with no home TL + parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); + } + if (parsed.contains("%")) { + parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. + } + msg(p.txt.parse(parsed)); + } + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SHOW_COMMANDDESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SHOW_COMMANDDESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdShowClaims.java b/src/main/java/com/massivecraft/factions/cmd/CmdShowClaims.java index 10c0492b..f51f662b 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShowClaims.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShowClaims.java @@ -8,51 +8,51 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdShowClaims extends FCommand { - public CmdShowClaims() { + public CmdShowClaims() { - this.aliases.add("showclaims"); - this.aliases.add("showclaim"); + this.aliases.add("showclaims"); + this.aliases.add("showclaim"); - permission = Permission.SHOWCLAIMS.node; + permission = Permission.SHOWCLAIMS.node; - this.senderMustBePlayer = true; - this.senderMustBeMember = true; - this.senderMustBeModerator = false; - this.senderMustBePlayer = true; + this.senderMustBePlayer = true; + this.senderMustBeMember = true; + this.senderMustBeModerator = false; + this.senderMustBePlayer = true; - } + } - @Override - public void perform() { - sendMessage(TL.COMMAND_SHOWCLAIMS_HEADER.toString().replace("{faction}", fme.getFaction().describeTo(fme))); - ListMultimap chunkMap = ArrayListMultimap.create(); - String format = TL.COMMAND_SHOWCLAIMS_CHUNKSFORMAT.toString(); - for (FLocation fLocation : fme.getFaction().getAllClaims()) { - chunkMap.put(fLocation.getWorldName(), format.replace("{x}", fLocation.getX() + "").replace("{z}", fLocation.getZ() + "")); - } - for (String world : chunkMap.keySet()) { - String message = TL.COMMAND_SHOWCLAIMS_FORMAT.toString().replace("{world}", world); - sendMessage(message.replace("{chunks}", "")); // made {chunks} blank as I removed the placeholder and people wont update their config :shrug: - StringBuilder chunks = new StringBuilder(); - for (String chunkString : chunkMap.get(world)) { - chunks.append(chunkString + ", "); - if (chunks.toString().length() >= 2000) { - sendMessage(chunks.toString()); - chunks.setLength(0); - } - } + @Override + public void perform() { + sendMessage(TL.COMMAND_SHOWCLAIMS_HEADER.toString().replace("{faction}", fme.getFaction().describeTo(fme))); + ListMultimap chunkMap = ArrayListMultimap.create(); + String format = TL.COMMAND_SHOWCLAIMS_CHUNKSFORMAT.toString(); + for (FLocation fLocation : fme.getFaction().getAllClaims()) { + chunkMap.put(fLocation.getWorldName(), format.replace("{x}", fLocation.getX() + "").replace("{z}", fLocation.getZ() + "")); + } + for (String world : chunkMap.keySet()) { + String message = TL.COMMAND_SHOWCLAIMS_FORMAT.toString().replace("{world}", world); + sendMessage(message.replace("{chunks}", "")); // made {chunks} blank as I removed the placeholder and people wont update their config :shrug: + StringBuilder chunks = new StringBuilder(); + for (String chunkString : chunkMap.get(world)) { + chunks.append(chunkString + ", "); + if (chunks.toString().length() >= 2000) { + sendMessage(chunks.toString()); + chunks.setLength(0); + } + } - sendMessage(""); - } + sendMessage(""); + } - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SHOWCLAIMS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SHOWCLAIMS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java b/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java index 4666ff03..79f48b91 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdShowInvites.java @@ -10,32 +10,32 @@ import org.bukkit.ChatColor; public class CmdShowInvites extends FCommand { - public CmdShowInvites() { - super(); - aliases.add("showinvites"); - permission = Permission.SHOW_INVITES.node; + public CmdShowInvites() { + super(); + aliases.add("showinvites"); + permission = Permission.SHOW_INVITES.node; - senderMustBePlayer = true; - senderMustBeMember = true; + senderMustBePlayer = true; + senderMustBeMember = true; - } + } - @Override - public void perform() { - FancyMessage msg = new FancyMessage(TL.COMMAND_SHOWINVITES_PENDING.toString()).color(ChatColor.GOLD); - for (String id : myFaction.getInvites()) { - FPlayer fp = FPlayers.getInstance().getById(id); - String name = fp != null ? fp.getName() : id; - msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_SHOWINVITES_CLICKTOREVOKE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name); - } + @Override + public void perform() { + FancyMessage msg = new FancyMessage(TL.COMMAND_SHOWINVITES_PENDING.toString()).color(ChatColor.GOLD); + for (String id : myFaction.getInvites()) { + FPlayer fp = FPlayers.getInstance().getById(id); + String name = fp != null ? fp.getName() : id; + msg.then(name + " ").color(ChatColor.WHITE).tooltip(TL.COMMAND_SHOWINVITES_CLICKTOREVOKE.format(name)).command("/" + Conf.baseCommandAliases.get(0) + " deinvite " + name); + } - sendFancyMessage(msg); - } + sendFancyMessage(msg); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_SHOWINVITES_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_SHOWINVITES_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java b/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java index 4dfec779..1df3b189 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStatus.java @@ -10,35 +10,35 @@ import java.util.ArrayList; public class CmdStatus extends FCommand { - public CmdStatus() { - super(); - this.aliases.add("status"); - this.aliases.add("s"); + public CmdStatus() { + super(); + this.aliases.add("status"); + this.aliases.add("s"); - this.permission = Permission.STATUS.node; + this.permission = Permission.STATUS.node; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - ArrayList ret = new ArrayList<>(); - for (FPlayer fp : myFaction.getFPlayers()) { - String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; - String last = fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); - String power = ChatColor.YELLOW + String.valueOf(fp.getPowerRounded()) + " / " + fp.getPowerMaxRounded() + ChatColor.RESET; - ret.add(String.format(TL.COMMAND_STATUS_FORMAT.toString(), ChatColor.GOLD + fp.getRole().getPrefix() + fp.getName() + ChatColor.RESET, power, last).trim()); - } - fme.sendMessage(ret); - } + @Override + public void perform() { + ArrayList ret = new ArrayList<>(); + for (FPlayer fp : myFaction.getFPlayers()) { + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fp.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + String last = fp.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fp.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + String power = ChatColor.YELLOW + String.valueOf(fp.getPowerRounded()) + " / " + fp.getPowerMaxRounded() + ChatColor.RESET; + ret.add(String.format(TL.COMMAND_STATUS_FORMAT.toString(), ChatColor.GOLD + fp.getRole().getPrefix() + fp.getName() + ChatColor.RESET, power, last).trim()); + } + fme.sendMessage(ret); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STATUS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STATUS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java b/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java index fe391273..cd1d9438 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStealth.java @@ -5,32 +5,32 @@ import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.zcore.util.TL; public class CmdStealth extends FCommand { - public CmdStealth() { - this.aliases.add("ninja"); - this.aliases.add("stealth"); - this.permission = Permission.STEALTH.node; + public CmdStealth() { + this.aliases.add("ninja"); + this.aliases.add("stealth"); + this.permission = Permission.STEALTH.node; - this.disableOnLock = true; + this.disableOnLock = true; - this.senderMustBePlayer = true; - this.senderMustBeMember = false; - this.senderMustBeModerator = false; - this.senderMustBeColeader = false; - this.senderMustBeAdmin = false; + this.senderMustBePlayer = true; + this.senderMustBeMember = false; + this.senderMustBeModerator = false; + this.senderMustBeColeader = false; + this.senderMustBeAdmin = false; - } + } - public void perform() { - Faction faction = fme.getFaction(); - if (faction != null && !faction.getId().equalsIgnoreCase("0") && !faction.getId().equalsIgnoreCase("none") && !faction.getId().equalsIgnoreCase("safezone") && !faction.getId().equalsIgnoreCase("warzone")) { - fme.setStealth(!fme.isStealthEnabled()); - fme.msg(fme.isStealthEnabled() ? TL.COMMAND_STEALTH_ENABLE : TL.COMMAND_STEALTH_DISABLE); - } else { - fme.msg(TL.COMMAND_STEALTH_MUSTBEMEMBER); - } - } + public void perform() { + Faction faction = fme.getFaction(); + if (faction != null && !faction.getId().equalsIgnoreCase("0") && !faction.getId().equalsIgnoreCase("none") && !faction.getId().equalsIgnoreCase("safezone") && !faction.getId().equalsIgnoreCase("warzone")) { + fme.setStealth(!fme.isStealthEnabled()); + fme.msg(fme.isStealthEnabled() ? TL.COMMAND_STEALTH_ENABLE : TL.COMMAND_STEALTH_DISABLE); + } else { + fme.msg(TL.COMMAND_STEALTH_MUSTBEMEMBER); + } + } - public TL getUsageTranslation() { - return TL.COMMAND_STEALTH_DESCRIPTION; - } + public TL getUsageTranslation() { + return TL.COMMAND_STEALTH_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java b/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java index 57b60fb9..f1aa9172 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdStuck.java @@ -14,98 +14,98 @@ import org.bukkit.scheduler.BukkitRunnable; public class CmdStuck extends FCommand { - public CmdStuck() { - super(); + public CmdStuck() { + super(); - this.aliases.add("stuck"); - this.aliases.add("halp!"); // halp!c: + this.aliases.add("stuck"); + this.aliases.add("halp!"); // halp!c: - this.permission = Permission.STUCK.node; - this.disableOnLock = true; + this.permission = Permission.STUCK.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - final Player player = fme.getPlayer(); - final Location sentAt = player.getLocation(); - final FLocation chunk = fme.getLastStoodAt(); - final long delay = SavageFactions.plugin.getConfig().getLong("hcf.stuck.delay", 30); - final int radius = SavageFactions.plugin.getConfig().getInt("hcf.stuck.radius", 10); + @Override + public void perform() { + final Player player = fme.getPlayer(); + final Location sentAt = player.getLocation(); + final FLocation chunk = fme.getLastStoodAt(); + final long delay = SavageFactions.plugin.getConfig().getLong("hcf.stuck.delay", 30); + final int radius = SavageFactions.plugin.getConfig().getInt("hcf.stuck.radius", 10); - if (SavageFactions.plugin.getStuckMap().containsKey(player.getUniqueId())) { - long wait = SavageFactions.plugin.getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); - String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); - msg(TL.COMMAND_STUCK_EXISTS, time); - } else { + if (SavageFactions.plugin.getStuckMap().containsKey(player.getUniqueId())) { + long wait = SavageFactions.plugin.getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); + String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); + msg(TL.COMMAND_STUCK_EXISTS, time); + } else { - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostStuck, TL.COMMAND_STUCK_TOSTUCK.format(fme.getName()), TL.COMMAND_STUCK_FORSTUCK.format(fme.getName()))) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostStuck, TL.COMMAND_STUCK_TOSTUCK.format(fme.getName()), TL.COMMAND_STUCK_FORSTUCK.format(fme.getName()))) { + return; + } - final int id = Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new BukkitRunnable() { + final int id = Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new BukkitRunnable() { - @Override - public void run() { - if (!SavageFactions.plugin.getStuckMap().containsKey(player.getUniqueId())) { - return; - } + @Override + public void run() { + if (!SavageFactions.plugin.getStuckMap().containsKey(player.getUniqueId())) { + return; + } - // check for world difference or radius exceeding - final World world = chunk.getWorld(); - if (world.getUID() != player.getWorld().getUID() || sentAt.distance(player.getLocation()) > radius) { - msg(TL.COMMAND_STUCK_OUTSIDE.format(radius)); - SavageFactions.plugin.getTimers().remove(player.getUniqueId()); - SavageFactions.plugin.getStuckMap().remove(player.getUniqueId()); - return; - } + // check for world difference or radius exceeding + final World world = chunk.getWorld(); + if (world.getUID() != player.getWorld().getUID() || sentAt.distance(player.getLocation()) > radius) { + msg(TL.COMMAND_STUCK_OUTSIDE.format(radius)); + SavageFactions.plugin.getTimers().remove(player.getUniqueId()); + SavageFactions.plugin.getStuckMap().remove(player.getUniqueId()); + return; + } - final Board board = Board.getInstance(); - // spiral task to find nearest wilderness chunk - new SpiralTask(new FLocation(me), radius * 2) { + final Board board = Board.getInstance(); + // spiral task to find nearest wilderness chunk + new SpiralTask(new FLocation(me), radius * 2) { - @Override - public boolean work() { - FLocation chunk = currentFLocation(); - Faction faction = board.getFactionAt(chunk); - int buffer = SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0); - if (faction.isWilderness() && !chunk.isOutsideWorldBorder(buffer)) { - int cx = FLocation.chunkToBlock((int) chunk.getX()); - int cz = FLocation.chunkToBlock((int) chunk.getZ()); - int y = world.getHighestBlockYAt(cx, cz); - Location tp = new Location(world, cx, y, cz); - msg(TL.COMMAND_STUCK_TELEPORT, tp.getBlockX(), tp.getBlockY(), tp.getBlockZ()); - SavageFactions.plugin.getTimers().remove(player.getUniqueId()); - SavageFactions.plugin.getStuckMap().remove(player.getUniqueId()); - if (!Essentials.handleTeleport(player, tp)) { - player.teleport(tp); - SavageFactions.plugin.debug("/f stuck used regular teleport, not essentials!"); - } - this.stop(); - return false; - } - return true; - } - }; - } - }, delay * 20).getTaskId(); + @Override + public boolean work() { + FLocation chunk = currentFLocation(); + Faction faction = board.getFactionAt(chunk); + int buffer = SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0); + if (faction.isWilderness() && !chunk.isOutsideWorldBorder(buffer)) { + int cx = FLocation.chunkToBlock((int) chunk.getX()); + int cz = FLocation.chunkToBlock((int) chunk.getZ()); + int y = world.getHighestBlockYAt(cx, cz); + Location tp = new Location(world, cx, y, cz); + msg(TL.COMMAND_STUCK_TELEPORT, tp.getBlockX(), tp.getBlockY(), tp.getBlockZ()); + SavageFactions.plugin.getTimers().remove(player.getUniqueId()); + SavageFactions.plugin.getStuckMap().remove(player.getUniqueId()); + if (!Essentials.handleTeleport(player, tp)) { + player.teleport(tp); + SavageFactions.plugin.debug("/f stuck used regular teleport, not essentials!"); + } + this.stop(); + return false; + } + return true; + } + }; + } + }, delay * 20).getTaskId(); - SavageFactions.plugin.getTimers().put(player.getUniqueId(), System.currentTimeMillis() + (delay * 1000)); - long wait = SavageFactions.plugin.getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); - String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); - msg(TL.COMMAND_STUCK_START, time); - SavageFactions.plugin.getStuckMap().put(player.getUniqueId(), id); - } - } + SavageFactions.plugin.getTimers().put(player.getUniqueId(), System.currentTimeMillis() + (delay * 1000)); + long wait = SavageFactions.plugin.getTimers().get(player.getUniqueId()) - System.currentTimeMillis(); + String time = DurationFormatUtils.formatDuration(wait, TL.COMMAND_STUCK_TIMEFORMAT.toString(), true); + msg(TL.COMMAND_STUCK_START, time); + SavageFactions.plugin.getStuckMap().put(player.getUniqueId(), id); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_STUCK_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_STUCK_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java index bc65ef26..6eefe687 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTag.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTag.java @@ -12,79 +12,79 @@ import java.util.ArrayList; public class CmdTag extends FCommand { - public CmdTag() { - this.aliases.add("tag"); - this.aliases.add("rename"); + public CmdTag() { + this.aliases.add("tag"); + this.aliases.add("rename"); - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("", ""); + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("", ""); - this.permission = Permission.TAG.node; - this.disableOnLock = true; + this.permission = Permission.TAG.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - String tag = this.argAsString(0); + @Override + public void perform() { + String tag = this.argAsString(0); - // TODO does not first test cover selfcase? - if (Factions.getInstance().isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(myFaction.getComparisonTag())) { - msg(TL.COMMAND_TAG_TAKEN); - return; - } + // TODO does not first test cover selfcase? + if (Factions.getInstance().isTagTaken(tag) && !MiscUtil.getComparisonString(tag).equals(myFaction.getComparisonTag())) { + msg(TL.COMMAND_TAG_TAKEN); + return; + } - ArrayList errors = MiscUtil.validateTag(tag); - if (errors.size() > 0) { - sendMessage(errors); - return; - } + ArrayList errors = MiscUtil.validateTag(tag); + if (errors.size() > 0) { + sendMessage(errors); + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay - if (!canAffordCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE.toString())) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make sure they can pay + if (!canAffordCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE.toString())) { + return; + } - // trigger the faction rename event (cancellable) - FactionRenameEvent renameEvent = new FactionRenameEvent(fme, tag); - Bukkit.getServer().getPluginManager().callEvent(renameEvent); - if (renameEvent.isCancelled()) { - return; - } + // trigger the faction rename event (cancellable) + FactionRenameEvent renameEvent = new FactionRenameEvent(fme, tag); + Bukkit.getServer().getPluginManager().callEvent(renameEvent); + if (renameEvent.isCancelled()) { + return; + } - // then make 'em pay (if applicable) - if (!payForCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE, TL.COMMAND_TAG_FORCHANGE)) { - return; - } + // then make 'em pay (if applicable) + if (!payForCommand(Conf.econCostTag, TL.COMMAND_TAG_TOCHANGE, TL.COMMAND_TAG_FORCHANGE)) { + return; + } - String oldtag = myFaction.getTag(); - myFaction.setTag(tag); + String oldtag = myFaction.getTag(); + myFaction.setTag(tag); - // Inform - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (fplayer.getFactionId().equals(myFaction.getId())) { - fplayer.msg(TL.COMMAND_TAG_FACTION, fme.describeTo(myFaction, true), myFaction.getTag(myFaction)); - continue; - } + // Inform + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.getFactionId().equals(myFaction.getId())) { + fplayer.msg(TL.COMMAND_TAG_FACTION, fme.describeTo(myFaction, true), myFaction.getTag(myFaction)); + continue; + } - // Broadcast the tag change (if applicable) - if (Conf.broadcastTagChanges) { - Faction faction = fplayer.getFaction(); - fplayer.msg(TL.COMMAND_TAG_CHANGED, fme.getColorTo(faction) + oldtag, myFaction.getTag(faction)); - } - } + // Broadcast the tag change (if applicable) + if (Conf.broadcastTagChanges) { + Faction faction = fplayer.getFaction(); + fplayer.msg(TL.COMMAND_TAG_CHANGED, fme.getColorTo(faction) + oldtag, myFaction.getTag(faction)); + } + } - FTeamWrapper.updatePrefixes(myFaction); - } + FTeamWrapper.updatePrefixes(myFaction); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TAG_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TAG_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java index 2d716dee..11461956 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTitle.java @@ -8,51 +8,51 @@ import com.massivecraft.factions.zcore.util.TextUtil; public class CmdTitle extends FCommand { - public CmdTitle() { - this.aliases.add("title"); + public CmdTitle() { + this.aliases.add("title"); - this.requiredArgs.add("player name"); - this.optionalArgs.put("title", ""); + this.requiredArgs.add("player name"); + this.optionalArgs.put("title", ""); - this.permission = Permission.TITLE.node; - this.disableOnLock = true; + this.permission = Permission.TITLE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - FPlayer you = this.argAsBestFPlayerMatch(0); - if (you == null) { - return; - } + @Override + public void perform() { + FPlayer you = this.argAsBestFPlayerMatch(0); + if (you == null) { + return; + } - args.remove(0); - String title = TextUtil.implode(args, " "); + args.remove(0); + String title = TextUtil.implode(args, " "); - if (!canIAdministerYou(fme, you)) { - return; - } + if (!canIAdministerYou(fme, you)) { + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(Conf.econCostTitle, TL.COMMAND_TITLE_TOCHANGE, TL.COMMAND_TITLE_FORCHANGE)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(Conf.econCostTitle, TL.COMMAND_TITLE_TOCHANGE, TL.COMMAND_TITLE_FORCHANGE)) { + return; + } - you.setTitle(sender, title); + you.setTitle(sender, title); - // Inform - myFaction.msg(TL.COMMAND_TITLE_CHANGED, fme.describeTo(myFaction, true), you.describeTo(myFaction, true)); - } + // Inform + myFaction.msg(TL.COMMAND_TITLE_CHANGED, fme.describeTo(myFaction, true), you.describeTo(myFaction, true)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TITLE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TITLE_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTnt.java b/src/main/java/com/massivecraft/factions/cmd/CmdTnt.java index 6bb42301..77f0f55a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTnt.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTnt.java @@ -12,172 +12,172 @@ import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class CmdTnt extends FCommand { - public CmdTnt() { - super(); - this.aliases.add("tnt"); + public CmdTnt() { + super(); + this.aliases.add("tnt"); - this.optionalArgs.put("add/take", ""); - this.optionalArgs.put("amount", "number"); + this.optionalArgs.put("add/take", ""); + this.optionalArgs.put("amount", "number"); - this.permission = Permission.TNT.node; - this.disableOnLock = true; + this.permission = Permission.TNT.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("ftnt.Enabled")) { - fme.msg(TL.COMMAND_TNT_DISABLED_MSG); - return; - } + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("ftnt.Enabled")) { + fme.msg(TL.COMMAND_TNT_DISABLED_MSG); + return; + } - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.TNTBANK); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "use tnt bank"); - return; - } - } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.TNTBANK); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "use tnt bank"); + return; + } + } - if (args.size() == 2) { - if (args.get(0).equalsIgnoreCase("add") || args.get(0).equalsIgnoreCase("a")) { - try { - Integer.parseInt(args.get(1)); - } catch (NumberFormatException e) { - fme.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } - int amount = Integer.parseInt(args.get(1)); - if (amount < 0) { - fme.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - Inventory inv = me.getInventory(); - int invTnt = 0; - for (int i = 0; i <= inv.getSize(); i++) { - if (inv.getItem(i) == null) { - continue; - } - if (inv.getItem(i).getType() == Material.TNT) { - invTnt += inv.getItem(i).getAmount(); - } - } - if (amount > invTnt) { - fme.msg(TL.COMMAND_TNT_DEPOSIT_NOTENOUGH); - return; - } - ItemStack tnt = new ItemStack(Material.TNT, amount); - if (fme.getFaction().getTnt() + amount > SavageFactions.plugin.getConfig().getInt("ftnt.Bank-Limit")) { - msg(TL.COMMAND_TNT_EXCEEDLIMIT); - return; - } - removeFromInventory(me.getInventory(), tnt); - me.updateInventory(); + if (args.size() == 2) { + if (args.get(0).equalsIgnoreCase("add") || args.get(0).equalsIgnoreCase("a")) { + try { + Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + fme.msg(TL.COMMAND_TNT_INVALID_NUM); + return; + } + int amount = Integer.parseInt(args.get(1)); + if (amount < 0) { + fme.msg(TL.COMMAND_TNT_POSITIVE); + return; + } + Inventory inv = me.getInventory(); + int invTnt = 0; + for (int i = 0; i <= inv.getSize(); i++) { + if (inv.getItem(i) == null) { + continue; + } + if (inv.getItem(i).getType() == Material.TNT) { + invTnt += inv.getItem(i).getAmount(); + } + } + if (amount > invTnt) { + fme.msg(TL.COMMAND_TNT_DEPOSIT_NOTENOUGH); + return; + } + ItemStack tnt = new ItemStack(Material.TNT, amount); + if (fme.getFaction().getTnt() + amount > SavageFactions.plugin.getConfig().getInt("ftnt.Bank-Limit")) { + msg(TL.COMMAND_TNT_EXCEEDLIMIT); + return; + } + removeFromInventory(me.getInventory(), tnt); + me.updateInventory(); - fme.getFaction().addTnt(amount); - fme.msg(TL.COMMAND_TNT_DEPOSIT_SUCCESS); - fme.sendMessage(SavageFactions.plugin.color(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", fme.getFaction().getTnt() + ""))); - return; + fme.getFaction().addTnt(amount); + fme.msg(TL.COMMAND_TNT_DEPOSIT_SUCCESS); + fme.sendMessage(SavageFactions.plugin.color(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", fme.getFaction().getTnt() + ""))); + return; - } - if (args.get(0).equalsIgnoreCase("take") || args.get(0).equalsIgnoreCase("t")) { - try { - Integer.parseInt(args.get(1)); - } catch (NumberFormatException e) { - fme.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } - int amount = Integer.parseInt(args.get(1)); - if (amount < 0) { - fme.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - if (fme.getFaction().getTnt() < amount) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); - return; - } - int fullStacks = amount / 64; - int remainderAmt = amount % 64; - if ((remainderAmt == 0 && !hasAvaliableSlot(me, fullStacks))) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); - return; - } - if (!hasAvaliableSlot(me, fullStacks + 1)) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); - return; - } - ItemStack tnt64 = new ItemStack(Material.TNT, 64); - for (int i = 0; i <= fullStacks - 1; i++) { - me.getInventory().addItem(tnt64); - } - if (remainderAmt != 0) { - ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); - me.getInventory().addItem(tnt); - } - fme.getFaction().takeTnt(amount); - me.updateInventory(); - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_SUCCESS); - } - } else if (args.size() == 1) { - fme.msg(TL.GENERIC_ARGS_TOOFEW); - fme.msg(args.get(0).equalsIgnoreCase("take") || args.get(0).equalsIgnoreCase("t") ? TL.COMMAND_TNT_TAKE_DESCRIPTION : TL.COMMAND_TNT_ADD_DESCRIPTION); - } - fme.sendMessage(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", fme.getFaction().getTnt() + "")); - } + } + if (args.get(0).equalsIgnoreCase("take") || args.get(0).equalsIgnoreCase("t")) { + try { + Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + fme.msg(TL.COMMAND_TNT_INVALID_NUM); + return; + } + int amount = Integer.parseInt(args.get(1)); + if (amount < 0) { + fme.msg(TL.COMMAND_TNT_POSITIVE); + return; + } + if (fme.getFaction().getTnt() < amount) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); + return; + } + int fullStacks = amount / 64; + int remainderAmt = amount % 64; + if ((remainderAmt == 0 && !hasAvaliableSlot(me, fullStacks))) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); + return; + } + if (!hasAvaliableSlot(me, fullStacks + 1)) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE); + return; + } + ItemStack tnt64 = new ItemStack(Material.TNT, 64); + for (int i = 0; i <= fullStacks - 1; i++) { + me.getInventory().addItem(tnt64); + } + if (remainderAmt != 0) { + ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); + me.getInventory().addItem(tnt); + } + fme.getFaction().takeTnt(amount); + me.updateInventory(); + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_SUCCESS); + } + } else if (args.size() == 1) { + fme.msg(TL.GENERIC_ARGS_TOOFEW); + fme.msg(args.get(0).equalsIgnoreCase("take") || args.get(0).equalsIgnoreCase("t") ? TL.COMMAND_TNT_TAKE_DESCRIPTION : TL.COMMAND_TNT_ADD_DESCRIPTION); + } + fme.sendMessage(TL.COMMAND_TNT_AMOUNT.toString().replace("{amount}", fme.getFaction().getTnt() + "")); + } - public boolean inventoryContains(Inventory inventory, ItemStack item) { - int count = 0; - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - count += items[i].getAmount(); - } - if (count >= item.getAmount()) { - return true; - } - } - return false; - } + public boolean inventoryContains(Inventory inventory, ItemStack item) { + int count = 0; + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + count += items[i].getAmount(); + } + if (count >= item.getAmount()) { + return true; + } + } + return false; + } - public boolean hasAvaliableSlot(Player player, int howmany) { - Integer check = 0; - for (ItemStack item : player.getInventory().getContents()) { - if (item == null) { - check++; - } - } - return check >= howmany; - } + public boolean hasAvaliableSlot(Player player, int howmany) { + Integer check = 0; + for (ItemStack item : player.getInventory().getContents()) { + if (item == null) { + check++; + } + } + return check >= howmany; + } - public void removeFromInventory(Inventory inventory, ItemStack item) { - int amt = item.getAmount(); - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - if (items[i].getAmount() > amt) { - items[i].setAmount(items[i].getAmount() - amt); - break; - } else if (items[i].getAmount() == amt) { - items[i] = null; - break; - } else { - amt -= items[i].getAmount(); - items[i] = null; - } - } - } - inventory.setContents(items); - } + public void removeFromInventory(Inventory inventory, ItemStack item) { + int amt = item.getAmount(); + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + if (items[i].getAmount() > amt) { + items[i].setAmount(items[i].getAmount() - amt); + break; + } else if (items[i].getAmount() == amt) { + items[i] = null; + break; + } else { + amt -= items[i].getAmount(); + items[i] = null; + } + } + } + inventory.setContents(items); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TNT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTntFill.java b/src/main/java/com/massivecraft/factions/cmd/CmdTntFill.java index b6237e59..954b89e4 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTntFill.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTntFill.java @@ -16,240 +16,240 @@ import org.bukkit.inventory.PlayerInventory; public class CmdTntFill extends FCommand { - public CmdTntFill() { - super(); - this.aliases.add("tntfill"); + public CmdTntFill() { + super(); + this.aliases.add("tntfill"); - this.requiredArgs.add("radius"); - this.requiredArgs.add("amount"); + this.requiredArgs.add("radius"); + this.requiredArgs.add("amount"); - this.permission = Permission.TNTFILL.node; - this.disableOnLock = true; + this.permission = Permission.TNTFILL.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("Tntfill.enabled")) { - this.fme.msg(TL.GENERIC_DISABLED); - return; - } - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.TNTFILL); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "use tnt fill"); - return; - } - } + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("Tntfill.enabled")) { + this.fme.msg(TL.GENERIC_DISABLED); + return; + } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.TNTFILL); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "use tnt fill"); + return; + } + } - msg(TL.COMMAND_TNTFILL_HEADER); - int radius = argAsInt(0, 16); - int amount = argAsInt(1, 16); - if (radius > SavageFactions.plugin.getConfig().getInt("Tntfill.max-radius")) { - fme.msg(TL.COMMAND_TNTFILL_RADIUSMAX.toString().replace("{max}", SavageFactions.plugin.getConfig().getInt("Tntfill.max-radius") + "")); - return; - } - if (amount > SavageFactions.plugin.getConfig().getInt("Tntfill.max-amount")) { - fme.msg(TL.COMMAND_TNTFILL_AMOUNTMAX.toString().replace("{max}", SavageFactions.plugin.getConfig().getInt("Tntfill.max-amount") + "")); - return; - } + msg(TL.COMMAND_TNTFILL_HEADER); + int radius = argAsInt(0, 16); + int amount = argAsInt(1, 16); + if (radius > SavageFactions.plugin.getConfig().getInt("Tntfill.max-radius")) { + fme.msg(TL.COMMAND_TNTFILL_RADIUSMAX.toString().replace("{max}", SavageFactions.plugin.getConfig().getInt("Tntfill.max-radius") + "")); + return; + } + if (amount > SavageFactions.plugin.getConfig().getInt("Tntfill.max-amount")) { + fme.msg(TL.COMMAND_TNTFILL_AMOUNTMAX.toString().replace("{max}", SavageFactions.plugin.getConfig().getInt("Tntfill.max-amount") + "")); + return; + } - try { - Integer.parseInt(args.get(1)); - } catch (NumberFormatException e) { - fme.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } - if (amount < 0) { - fme.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - boolean bankMode = fme.getRole().isAtLeast(Role.MODERATOR); - Location start = me.getLocation(); - int counter = 0; - for (double x = start.getX() - radius; x <= start.getX() + radius; x++) { - for (double y = start.getY() - radius; y <= start.getY() + radius; y++) { - for (double z = start.getZ() - radius; z <= start.getZ() + radius; z++) { - Location blockLoc = new Location(start.getWorld(), x, y, z); - if (blockLoc.getBlock().getState() instanceof Dispenser) { - Dispenser disp = (Dispenser) blockLoc.getBlock().getState(); - Inventory dispenser = disp.getInventory(); - if (canHold(dispenser, amount)) { - int fullStacks = amount / 64; - int remainderAmt = amount % 64; - if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT, amount))) { - if (!fme.getRole().isAtLeast(Role.MODERATOR)) { - fme.msg(TL.COMMAND_TNTFILL_NOTENOUGH.toString()); - sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + "")); - me.updateInventory(); - return; - } else if (bankMode) { - //msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}",fme.getRole().nicename)); - bankMode = true; - removeFromBank(amount); - if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT, amount))) { - fme.msg(TL.COMMAND_TNTFILL_NOTENOUGH.toString()); - sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + "")); - me.updateInventory(); - return; - } - } - } - ItemStack tnt64 = new ItemStack(Material.TNT, 64); - for (int i = 0; i <= fullStacks - 1; i++) { - dispenser.addItem(tnt64); - takeTnt(64); - } - if (remainderAmt != 0) { - ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); - dispenser.addItem(tnt); - takeTnt(remainderAmt); - } - //sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{x}",(int) x + "").replace("{y}",(int) y + "").replace("{z}",(int) z + "")); - counter++; - } + try { + Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + fme.msg(TL.COMMAND_TNT_INVALID_NUM); + return; + } + if (amount < 0) { + fme.msg(TL.COMMAND_TNT_POSITIVE); + return; + } + boolean bankMode = fme.getRole().isAtLeast(Role.MODERATOR); + Location start = me.getLocation(); + int counter = 0; + for (double x = start.getX() - radius; x <= start.getX() + radius; x++) { + for (double y = start.getY() - radius; y <= start.getY() + radius; y++) { + for (double z = start.getZ() - radius; z <= start.getZ() + radius; z++) { + Location blockLoc = new Location(start.getWorld(), x, y, z); + if (blockLoc.getBlock().getState() instanceof Dispenser) { + Dispenser disp = (Dispenser) blockLoc.getBlock().getState(); + Inventory dispenser = disp.getInventory(); + if (canHold(dispenser, amount)) { + int fullStacks = amount / 64; + int remainderAmt = amount % 64; + if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT, amount))) { + if (!fme.getRole().isAtLeast(Role.MODERATOR)) { + fme.msg(TL.COMMAND_TNTFILL_NOTENOUGH.toString()); + sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + "")); + me.updateInventory(); + return; + } else if (bankMode) { + //msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}",fme.getRole().nicename)); + bankMode = true; + removeFromBank(amount); + if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT, amount))) { + fme.msg(TL.COMMAND_TNTFILL_NOTENOUGH.toString()); + sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + "")); + me.updateInventory(); + return; + } + } + } + ItemStack tnt64 = new ItemStack(Material.TNT, 64); + for (int i = 0; i <= fullStacks - 1; i++) { + dispenser.addItem(tnt64); + takeTnt(64); + } + if (remainderAmt != 0) { + ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); + dispenser.addItem(tnt); + takeTnt(remainderAmt); + } + //sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{x}",(int) x + "").replace("{y}",(int) y + "").replace("{z}",(int) z + "")); + counter++; + } - } - } - } - } - if (bankMode) { - msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}", fme.getRole().nicename)); - } - sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + "")); - me.updateInventory(); + } + } + } + } + if (bankMode) { + msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}", fme.getRole().nicename)); + } + sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + "")); + me.updateInventory(); - } + } - private void removeFromBank(int amount) { - try { - Integer.parseInt(args.get(1)); - } catch (NumberFormatException e) { - fme.msg(TL.COMMAND_TNT_INVALID_NUM); - return; - } - if (amount < 0) { - fme.msg(TL.COMMAND_TNT_POSITIVE); - return; - } - if (fme.getFaction().getTnt() < amount) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); - return; - } - int fullStacks = amount / 64; - int remainderAmt = amount % 64; - if ((remainderAmt == 0 && getEmptySlots(me) <= fullStacks)) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); - return; - } - if (getEmptySlots(me) + 1 <= fullStacks) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); - return; - } - ItemStack tnt64 = new ItemStack(Material.TNT, 64); - for (int i = 0; i <= fullStacks - 1; i++) { - me.getInventory().addItem(tnt64); - } - if (remainderAmt != 0) { - ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); - me.getInventory().addItem(tnt); - } - fme.getFaction().takeTnt(amount); - me.updateInventory(); - } + private void removeFromBank(int amount) { + try { + Integer.parseInt(args.get(1)); + } catch (NumberFormatException e) { + fme.msg(TL.COMMAND_TNT_INVALID_NUM); + return; + } + if (amount < 0) { + fme.msg(TL.COMMAND_TNT_POSITIVE); + return; + } + if (fme.getFaction().getTnt() < amount) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); + return; + } + int fullStacks = amount / 64; + int remainderAmt = amount % 64; + if ((remainderAmt == 0 && getEmptySlots(me) <= fullStacks)) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); + return; + } + if (getEmptySlots(me) + 1 <= fullStacks) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); + return; + } + ItemStack tnt64 = new ItemStack(Material.TNT, 64); + for (int i = 0; i <= fullStacks - 1; i++) { + me.getInventory().addItem(tnt64); + } + if (remainderAmt != 0) { + ItemStack tnt = new ItemStack(Material.TNT, remainderAmt); + me.getInventory().addItem(tnt); + } + fme.getFaction().takeTnt(amount); + me.updateInventory(); + } - public void takeTnt(int amount) { - Inventory inv = me.getInventory(); - int invTnt = 0; - for (int i = 0; i <= inv.getSize(); i++) { - if (inv.getItem(i) == null) { - continue; - } - if (inv.getItem(i).getType() == Material.TNT) { - invTnt += inv.getItem(i).getAmount(); - } - } - if (amount > invTnt) { - fme.msg(TL.COMMAND_TNTFILL_NOTENOUGH); - return; - } - ItemStack tnt = new ItemStack(Material.TNT, amount); - if (fme.getFaction().getTnt() + amount > SavageFactions.plugin.getConfig().getInt("ftnt.Bank-Limit")) { - msg(TL.COMMAND_TNT_EXCEEDLIMIT); - return; - } - removeFromInventory(me.getInventory(), tnt); - } + public void takeTnt(int amount) { + Inventory inv = me.getInventory(); + int invTnt = 0; + for (int i = 0; i <= inv.getSize(); i++) { + if (inv.getItem(i) == null) { + continue; + } + if (inv.getItem(i).getType() == Material.TNT) { + invTnt += inv.getItem(i).getAmount(); + } + } + if (amount > invTnt) { + fme.msg(TL.COMMAND_TNTFILL_NOTENOUGH); + return; + } + ItemStack tnt = new ItemStack(Material.TNT, amount); + if (fme.getFaction().getTnt() + amount > SavageFactions.plugin.getConfig().getInt("ftnt.Bank-Limit")) { + msg(TL.COMMAND_TNT_EXCEEDLIMIT); + return; + } + removeFromInventory(me.getInventory(), tnt); + } - public boolean canHold(Inventory inventory, int amount) { - int fullStacks = amount / 64; - int remainderAmt = amount % 64; - if ((remainderAmt == 0 && getEmptySlots(me) <= fullStacks)) { - return false; - } - if (getEmptySlots(me) + 1 <= fullStacks) { - fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); - return false; - } - return true; - } + public boolean canHold(Inventory inventory, int amount) { + int fullStacks = amount / 64; + int remainderAmt = amount % 64; + if ((remainderAmt == 0 && getEmptySlots(me) <= fullStacks)) { + return false; + } + if (getEmptySlots(me) + 1 <= fullStacks) { + fme.msg(TL.COMMAND_TNT_WIDTHDRAW_NOTENOUGH.toString()); + return false; + } + return true; + } - public boolean inventoryContains(Inventory inventory, ItemStack item) { - int count = 0; - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - count += items[i].getAmount(); - } - if (count >= item.getAmount()) { - return true; - } - } - return false; - } + public boolean inventoryContains(Inventory inventory, ItemStack item) { + int count = 0; + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + count += items[i].getAmount(); + } + if (count >= item.getAmount()) { + return true; + } + } + return false; + } - public void removeFromInventory(Inventory inventory, ItemStack item) { - int amt = item.getAmount(); - ItemStack[] items = inventory.getContents(); - for (int i = 0; i < items.length; i++) { - if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { - if (items[i].getAmount() > amt) { - items[i].setAmount(items[i].getAmount() - amt); - break; - } else if (items[i].getAmount() == amt) { - items[i] = null; - break; - } else { - amt -= items[i].getAmount(); - items[i] = null; - } - } - } - inventory.setContents(items); - } + public void removeFromInventory(Inventory inventory, ItemStack item) { + int amt = item.getAmount(); + ItemStack[] items = inventory.getContents(); + for (int i = 0; i < items.length; i++) { + if (items[i] != null && items[i].getType() == item.getType() && items[i].getDurability() == item.getDurability()) { + if (items[i].getAmount() > amt) { + items[i].setAmount(items[i].getAmount() - amt); + break; + } else if (items[i].getAmount() == amt) { + items[i] = null; + break; + } else { + amt -= items[i].getAmount(); + items[i] = null; + } + } + } + inventory.setContents(items); + } - public int getEmptySlots(Player p) { - PlayerInventory inventory = p.getInventory(); - ItemStack[] cont = inventory.getContents(); - int i = 0; - for (ItemStack item : cont) - if (item != null && item.getType() != Material.AIR) { - i++; - } - return 36 - i; - } + public int getEmptySlots(Player p) { + PlayerInventory inventory = p.getInventory(); + ItemStack[] cont = inventory.getContents(); + int i = 0; + for (ItemStack item : cont) + if (item != null && item.getType() != Material.AIR) { + i++; + } + return 36 - i; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TNTFILL_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TNTFILL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java b/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java index 95664b6d..3f4d45ba 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdToggleAllianceChat.java @@ -6,39 +6,39 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdToggleAllianceChat extends FCommand { - public CmdToggleAllianceChat() { - super(); - this.aliases.add("tac"); - this.aliases.add("togglealliancechat"); - this.aliases.add("ac"); + public CmdToggleAllianceChat() { + super(); + this.aliases.add("tac"); + this.aliases.add("togglealliancechat"); + this.aliases.add("ac"); - this.disableOnLock = false; + this.disableOnLock = false; - this.permission = Permission.TOGGLE_ALLIANCE_CHAT.node; - this.disableOnLock = false; + this.permission = Permission.TOGGLE_ALLIANCE_CHAT.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION; + } - @Override - public void perform() { - if (!Conf.factionOnlyChat) { - msg(TL.COMMAND_CHAT_DISABLED.toString()); - return; - } + @Override + public void perform() { + if (!Conf.factionOnlyChat) { + msg(TL.COMMAND_CHAT_DISABLED.toString()); + return; + } - boolean ignoring = fme.isIgnoreAllianceChat(); + boolean ignoring = fme.isIgnoreAllianceChat(); - msg(ignoring ? TL.COMMAND_TOGGLEALLIANCECHAT_UNIGNORE : TL.COMMAND_TOGGLEALLIANCECHAT_IGNORE); - fme.setIgnoreAllianceChat(!ignoring); - } + msg(ignoring ? TL.COMMAND_TOGGLEALLIANCECHAT_UNIGNORE : TL.COMMAND_TOGGLEALLIANCECHAT_IGNORE); + fme.setIgnoreAllianceChat(!ignoring); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTop.java b/src/main/java/com/massivecraft/factions/cmd/CmdTop.java index 48c9a9f5..5fd1180a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTop.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTop.java @@ -12,167 +12,167 @@ import java.util.ArrayList; public class CmdTop extends FCommand { - public CmdTop() { - super(); - this.aliases.add("top"); - this.aliases.add("t"); + public CmdTop() { + super(); + this.aliases.add("top"); + this.aliases.add("t"); - //this.requiredArgs.add(""); - this.requiredArgs.add("criteria"); - this.optionalArgs.put("page", "1"); + //this.requiredArgs.add(""); + this.requiredArgs.add("criteria"); + this.optionalArgs.put("page", "1"); - this.permission = Permission.TOP.node; - this.disableOnLock = false; + this.permission = Permission.TOP.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - // Can sort by: money, members, online, allies, enemies, power, land. - // Get all Factions and remove non player ones. - ArrayList factionList = Factions.getInstance().getAllFactions(); - factionList.remove(Factions.getInstance().getWilderness()); - factionList.remove(Factions.getInstance().getSafeZone()); - factionList.remove(Factions.getInstance().getWarZone()); + @Override + public void perform() { + // Can sort by: money, members, online, allies, enemies, power, land. + // Get all Factions and remove non player ones. + ArrayList factionList = Factions.getInstance().getAllFactions(); + factionList.remove(Factions.getInstance().getWilderness()); + factionList.remove(Factions.getInstance().getSafeZone()); + factionList.remove(Factions.getInstance().getWarZone()); - String criteria = argAsString(0); + String criteria = argAsString(0); - // TODO: Better way to sort? - if (criteria.equalsIgnoreCase("members")) { - 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; - }); - } else if (criteria.equalsIgnoreCase("start")) { - factionList.sort((f1, f2) -> { - long f1start = f1.getFoundedDate(); - long f2start = f2.getFoundedDate(); - // flip signs because a smaller date is farther in the past - if (f1start > f2start) { - return 1; - } else if (f1start < f2start) { - return -1; - } - return 0; - }); - } else if (criteria.equalsIgnoreCase("power")) { - factionList.sort((f1, f2) -> { - int f1Size = f1.getPowerRounded(); - int f2Size = f2.getPowerRounded(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); - } else if (criteria.equalsIgnoreCase("land")) { - factionList.sort((f1, f2) -> { - int f1Size = f1.getLandRounded(); - int f2Size = f2.getLandRounded(); - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); - } else if (criteria.equalsIgnoreCase("online")) { - 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; - }); - } else if (criteria.equalsIgnoreCase("money") || criteria.equalsIgnoreCase("balance") || criteria.equalsIgnoreCase("bal")) { - factionList.sort((f1, f2) -> { - double f1Size = Econ.getBalance(f1.getAccountId()); - // Lets get the balance of /all/ the players in the Faction. - for (FPlayer fp : f1.getFPlayers()) { - f1Size = f1Size + Econ.getBalance(fp.getAccountId()); - } - double f2Size = Econ.getBalance(f2.getAccountId()); - for (FPlayer fp : f2.getFPlayers()) { - f2Size = f2Size + Econ.getBalance(fp.getAccountId()); - } - if (f1Size < f2Size) { - return 1; - } else if (f1Size > f2Size) { - return -1; - } - return 0; - }); - } else { - msg(TL.COMMAND_TOP_INVALID, criteria); - } + // TODO: Better way to sort? + if (criteria.equalsIgnoreCase("members")) { + 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; + }); + } else if (criteria.equalsIgnoreCase("start")) { + factionList.sort((f1, f2) -> { + long f1start = f1.getFoundedDate(); + long f2start = f2.getFoundedDate(); + // flip signs because a smaller date is farther in the past + if (f1start > f2start) { + return 1; + } else if (f1start < f2start) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("power")) { + factionList.sort((f1, f2) -> { + int f1Size = f1.getPowerRounded(); + int f2Size = f2.getPowerRounded(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("land")) { + factionList.sort((f1, f2) -> { + int f1Size = f1.getLandRounded(); + int f2Size = f2.getLandRounded(); + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else if (criteria.equalsIgnoreCase("online")) { + 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; + }); + } else if (criteria.equalsIgnoreCase("money") || criteria.equalsIgnoreCase("balance") || criteria.equalsIgnoreCase("bal")) { + factionList.sort((f1, f2) -> { + double f1Size = Econ.getBalance(f1.getAccountId()); + // Lets get the balance of /all/ the players in the Faction. + for (FPlayer fp : f1.getFPlayers()) { + f1Size = f1Size + Econ.getBalance(fp.getAccountId()); + } + double f2Size = Econ.getBalance(f2.getAccountId()); + for (FPlayer fp : f2.getFPlayers()) { + f2Size = f2Size + Econ.getBalance(fp.getAccountId()); + } + if (f1Size < f2Size) { + return 1; + } else if (f1Size > f2Size) { + return -1; + } + return 0; + }); + } else { + msg(TL.COMMAND_TOP_INVALID, criteria); + } - ArrayList lines = new ArrayList<>(); + ArrayList lines = new ArrayList<>(); - final int pageheight = 9; - int pagenumber = this.argAsInt(1, 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(); - } + final int pageheight = 9; + int pagenumber = this.argAsInt(1, 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(); + } - lines.add(TL.COMMAND_TOP_TOP.format(criteria.toUpperCase(), pagenumber, pagecount)); + lines.add(TL.COMMAND_TOP_TOP.format(criteria.toUpperCase(), pagenumber, pagecount)); - int rank = 1; - for (Faction faction : factionList.subList(start, end)) { - // Get the relation color if player is executing this. - String fac = sender instanceof Player ? faction.getRelationTo(fme).getColor() + faction.getTag() : faction.getTag(); - lines.add(TL.COMMAND_TOP_LINE.format(rank, fac, getValue(faction, criteria))); - rank++; - } + int rank = 1; + for (Faction faction : factionList.subList(start, end)) { + // Get the relation color if player is executing this. + String fac = sender instanceof Player ? faction.getRelationTo(fme).getColor() + faction.getTag() : faction.getTag(); + lines.add(TL.COMMAND_TOP_LINE.format(rank, fac, getValue(faction, criteria))); + rank++; + } - sendMessage(lines); - } + sendMessage(lines); + } - private String getValue(Faction faction, String criteria) { - if (criteria.equalsIgnoreCase("online")) { - return String.valueOf(faction.getFPlayersWhereOnline(true).size()); - } else if (criteria.equalsIgnoreCase("start")) { - return TL.sdf.format(faction.getFoundedDate()); - } else if (criteria.equalsIgnoreCase("members")) { - return String.valueOf(faction.getFPlayers().size()); - } else if (criteria.equalsIgnoreCase("land")) { - return String.valueOf(faction.getLandRounded()); - } else if (criteria.equalsIgnoreCase("power")) { - return String.valueOf(faction.getPowerRounded()); - } else { // Last one is balance, and it has 3 different things it could be. - double balance = Econ.getBalance(faction.getAccountId()); - for (FPlayer fp : faction.getFPlayers()) { - balance = Math.round(balance + Econ.getBalance(fp.getAccountId())); - } - return String.valueOf(balance); - } - } + private String getValue(Faction faction, String criteria) { + if (criteria.equalsIgnoreCase("online")) { + return String.valueOf(faction.getFPlayersWhereOnline(true).size()); + } else if (criteria.equalsIgnoreCase("start")) { + return TL.sdf.format(faction.getFoundedDate()); + } else if (criteria.equalsIgnoreCase("members")) { + return String.valueOf(faction.getFPlayers().size()); + } else if (criteria.equalsIgnoreCase("land")) { + return String.valueOf(faction.getLandRounded()); + } else if (criteria.equalsIgnoreCase("power")) { + return String.valueOf(faction.getPowerRounded()); + } else { // Last one is balance, and it has 3 different things it could be. + double balance = Econ.getBalance(faction.getAccountId()); + for (FPlayer fp : faction.getFPlayers()) { + balance = Math.round(balance + Econ.getBalance(fp.getAccountId())); + } + return String.valueOf(balance); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TOP_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TOP_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdTpBanner.java b/src/main/java/com/massivecraft/factions/cmd/CmdTpBanner.java index 4023e49f..55f81229 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdTpBanner.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdTpBanner.java @@ -8,46 +8,46 @@ import com.massivecraft.factions.util.WarmUpUtil; import com.massivecraft.factions.zcore.util.TL; public class CmdTpBanner extends FCommand { - public CmdTpBanner() { - super(); + public CmdTpBanner() { + super(); - this.aliases.add("tpbanner"); + this.aliases.add("tpbanner"); - this.permission = Permission.TPBANNER.node; - this.disableOnLock = true; + this.permission = Permission.TPBANNER.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fbanners.Enabled")) { - return; - } + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fbanners.Enabled")) { + return; + } - final FactionsPlayerListener fpl = new FactionsPlayerListener(); + final FactionsPlayerListener fpl = new FactionsPlayerListener(); - if (FactionsBlockListener.bannerLocations.containsKey(fme.getTag())) { - fme.msg(TL.COMMAND_TPBANNER_SUCCESS); - this.doWarmUp(WarmUpUtil.Warmup.BANNER, TL.WARMUPS_NOTIFY_TELEPORT, "Banner", new Runnable() { - @Override - public void run() { - me.teleport(FactionsBlockListener.bannerLocations.get(fme.getTag())); - } - }, this.p.getConfig().getLong("warmups.f-banner", 0)); - } else { - fme.msg(TL.COMMAND_TPBANNER_NOTSET); - } + if (FactionsBlockListener.bannerLocations.containsKey(fme.getTag())) { + fme.msg(TL.COMMAND_TPBANNER_SUCCESS); + this.doWarmUp(WarmUpUtil.Warmup.BANNER, TL.WARMUPS_NOTIFY_TELEPORT, "Banner", new Runnable() { + @Override + public void run() { + me.teleport(FactionsBlockListener.bannerLocations.get(fme.getTag())); + } + }, this.p.getConfig().getLong("warmups.f-banner", 0)); + } else { + fme.msg(TL.COMMAND_TPBANNER_NOTSET); + } - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_TPBANNER_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_TPBANNER_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java index 86ba4be7..26ac45db 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnban.java @@ -9,51 +9,51 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdUnban extends FCommand { - public CmdUnban() { - super(); - this.aliases.add("unban"); + public CmdUnban() { + super(); + this.aliases.add("unban"); - this.requiredArgs.add("target"); + this.requiredArgs.add("target"); - this.permission = Permission.BAN.node; - this.disableOnLock = true; + this.permission = Permission.BAN.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBeAdmin = false; + } - @Override - public void perform() { - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.BAN); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER && !Permission.BAN.has(sender, true)) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage bans"); - return; - } - } + @Override + public void perform() { + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.BAN); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER && !Permission.BAN.has(sender, true)) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage bans"); + return; + } + } - // Good on permission checks. Now lets just ban the player. - FPlayer target = argAsFPlayer(0); - if (target == null) { - return; // the above method sends a message if fails to find someone. - } + // Good on permission checks. Now lets just ban the player. + FPlayer target = argAsFPlayer(0); + if (target == null) { + return; // the above method sends a message if fails to find someone. + } - if (!myFaction.isBanned(target)) { - fme.msg(TL.COMMAND_UNBAN_NOTBANNED, target.getName()); - return; - } + if (!myFaction.isBanned(target)) { + fme.msg(TL.COMMAND_UNBAN_NOTBANNED, target.getName()); + return; + } - myFaction.unban(target); + myFaction.unban(target); - myFaction.msg(TL.COMMAND_UNBAN_UNBANNED, fme.getName(), target.getName()); - target.msg(TL.COMMAND_UNBAN_TARGET, myFaction.getTag(target)); - } + myFaction.msg(TL.COMMAND_UNBAN_UNBANNED, fme.getName(), target.getName()); + target.msg(TL.COMMAND_UNBAN_TARGET, myFaction.getTag(target)); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_UNBAN_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNBAN_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java index 9fa2293e..3b9d0f4a 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaim.java @@ -13,172 +13,172 @@ import org.bukkit.Bukkit; public class CmdUnclaim extends FCommand { - public CmdUnclaim() { - this.aliases.add("unclaim"); - this.aliases.add("declaim"); + public CmdUnclaim() { + this.aliases.add("unclaim"); + this.aliases.add("declaim"); - this.optionalArgs.put("radius", "1"); + this.optionalArgs.put("radius", "1"); - this.permission = Permission.UNCLAIM.node; - this.disableOnLock = true; + this.permission = Permission.UNCLAIM.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - // Read and validate input - int radius = this.argAsInt(0, 1); // Default to 1 + @Override + public void perform() { + // Read and validate input + int radius = this.argAsInt(0, 1); // Default to 1 - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.TERRITORY); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage faction territory"); - return; - } - } + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.TERRITORY); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "manage faction territory"); + return; + } + } - if (radius < 1) { - msg(TL.COMMAND_CLAIM_INVALIDRADIUS); - return; - } + if (radius < 1) { + msg(TL.COMMAND_CLAIM_INVALIDRADIUS); + return; + } - if (radius < 2) { - // single chunk - unClaim(new FLocation(me)); - } else { - // radius claim - if (!Permission.CLAIM_RADIUS.has(sender, false)) { - msg(TL.COMMAND_CLAIM_DENIED); - return; - } + if (radius < 2) { + // single chunk + unClaim(new FLocation(me)); + } else { + // radius claim + if (!Permission.CLAIM_RADIUS.has(sender, false)) { + msg(TL.COMMAND_CLAIM_DENIED); + return; + } - new SpiralTask(new FLocation(me), radius) { - private final int limit = Conf.radiusClaimFailureLimit - 1; - private int failCount = 0; + new SpiralTask(new FLocation(me), radius) { + private final int limit = Conf.radiusClaimFailureLimit - 1; + private int failCount = 0; - @Override - public boolean work() { - boolean success = unClaim(this.currentFLocation()); - if (success) { - failCount = 0; - } else if (failCount++ >= limit) { - this.stop(); - return false; - } + @Override + public boolean work() { + boolean success = unClaim(this.currentFLocation()); + if (success) { + failCount = 0; + } else if (failCount++ >= limit) { + this.stop(); + return false; + } - return true; - } - }; - } - } + return true; + } + }; + } + } - private boolean unClaim(FLocation target) { - Faction targetFaction = Board.getInstance().getFactionAt(target); - if (targetFaction.isSafeZone()) { - if (Permission.MANAGE_SAFE_ZONE.has(sender)) { - Board.getInstance().removeAt(target); - msg(TL.COMMAND_UNCLAIM_SAFEZONE_SUCCESS); + private boolean unClaim(FLocation target) { + Faction targetFaction = Board.getInstance().getFactionAt(target); + if (targetFaction.isSafeZone()) { + if (Permission.MANAGE_SAFE_ZONE.has(sender)) { + Board.getInstance().removeAt(target); + msg(TL.COMMAND_UNCLAIM_SAFEZONE_SUCCESS); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); - } - return true; - } else { - msg(TL.COMMAND_UNCLAIM_SAFEZONE_NOPERM); - return false; - } - } else if (targetFaction.isWarZone()) { - if (Permission.MANAGE_WAR_ZONE.has(sender)) { - Board.getInstance().removeAt(target); - msg(TL.COMMAND_UNCLAIM_WARZONE_SUCCESS); + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); + } + return true; + } else { + msg(TL.COMMAND_UNCLAIM_SAFEZONE_NOPERM); + return false; + } + } else if (targetFaction.isWarZone()) { + if (Permission.MANAGE_WAR_ZONE.has(sender)) { + Board.getInstance().removeAt(target); + msg(TL.COMMAND_UNCLAIM_WARZONE_SUCCESS); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); - } - return true; - } else { - msg(TL.COMMAND_UNCLAIM_WARZONE_NOPERM); - return false; - } - } + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); + } + return true; + } else { + msg(TL.COMMAND_UNCLAIM_WARZONE_NOPERM); + return false; + } + } - if (fme.isAdminBypassing()) { - LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, fme); - Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); - if (unclaimEvent.isCancelled()) { - return false; - } + if (fme.isAdminBypassing()) { + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, fme); + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); + if (unclaimEvent.isCancelled()) { + return false; + } - Board.getInstance().removeAt(target); + Board.getInstance().removeAt(target); - targetFaction.msg(TL.COMMAND_UNCLAIM_UNCLAIMED, fme.describeTo(targetFaction, true)); - msg(TL.COMMAND_UNCLAIM_UNCLAIMS); + targetFaction.msg(TL.COMMAND_UNCLAIM_UNCLAIMED, fme.describeTo(targetFaction, true)); + msg(TL.COMMAND_UNCLAIM_UNCLAIMS); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); - } + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); + } - return true; - } + return true; + } - if (targetFaction.getAccess(fme, PermissableAction.TERRITORY) == Access.DENY) { - return false; - } + if (targetFaction.getAccess(fme, PermissableAction.TERRITORY) == Access.DENY) { + return false; + } - if (!assertHasFaction()) { - return false; - } + if (!assertHasFaction()) { + return false; + } - if (targetFaction.getAccess(fme, PermissableAction.TERRITORY) != Access.ALLOW && !assertMinRole(Role.MODERATOR)) { - return false; - } + if (targetFaction.getAccess(fme, PermissableAction.TERRITORY) != Access.ALLOW && !assertMinRole(Role.MODERATOR)) { + return false; + } - if (myFaction != targetFaction) { - msg(TL.COMMAND_UNCLAIM_WRONGFACTION); - return false; - } + if (myFaction != targetFaction) { + msg(TL.COMMAND_UNCLAIM_WRONGFACTION); + return false; + } - LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, fme); - Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); - if (unclaimEvent.isCancelled()) { - return false; - } + LandUnclaimEvent unclaimEvent = new LandUnclaimEvent(target, targetFaction, fme); + Bukkit.getServer().getPluginManager().callEvent(unclaimEvent); + if (unclaimEvent.isCancelled()) { + return false; + } - if (Econ.shouldBeUsed()) { - double refund = Econ.calculateClaimRefund(myFaction.getLandRounded()); + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateClaimRefund(myFaction.getLandRounded()); - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { - if (!Econ.modifyMoney(myFaction, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { - return false; - } - } else { - if (!Econ.modifyMoney(fme, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { - return false; - } - } - } + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { + if (!Econ.modifyMoney(myFaction, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + return false; + } + } else { + if (!Econ.modifyMoney(fme, refund, TL.COMMAND_UNCLAIM_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIM_FORUNCLAIM.toString())) { + return false; + } + } + } - Board.getInstance().removeAt(target); - myFaction.msg(TL.COMMAND_UNCLAIM_FACTIONUNCLAIMED, fme.describeTo(myFaction, true)); + Board.getInstance().removeAt(target); + myFaction.msg(TL.COMMAND_UNCLAIM_FACTIONUNCLAIMED, fme.describeTo(myFaction, true)); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); - } + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_UNCLAIM_LOG.format(fme.getName(), target.getCoordString(), targetFaction.getTag())); + } - return true; - } + return true; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_UNCLAIM_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNCLAIM_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java index 5d8efb28..8eef33a2 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUnclaimall.java @@ -11,55 +11,55 @@ import org.bukkit.Bukkit; public class CmdUnclaimall extends FCommand { - public CmdUnclaimall() { - this.aliases.add("unclaimall"); - this.aliases.add("declaimall"); + public CmdUnclaimall() { + this.aliases.add("unclaimall"); + this.aliases.add("declaimall"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - this.permission = Permission.UNCLAIM_ALL.node; - this.disableOnLock = true; + this.permission = Permission.UNCLAIM_ALL.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (Econ.shouldBeUsed()) { - double refund = Econ.calculateTotalLandRefund(myFaction.getLandRounded()); - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { - if (!Econ.modifyMoney(myFaction, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { - return; - } - } else { - if (!Econ.modifyMoney(fme, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { - return; - } - } - } + @Override + public void perform() { + if (Econ.shouldBeUsed()) { + double refund = Econ.calculateTotalLandRefund(myFaction.getLandRounded()); + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts) { + if (!Econ.modifyMoney(myFaction, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; + } + } else { + if (!Econ.modifyMoney(fme, refund, TL.COMMAND_UNCLAIMALL_TOUNCLAIM.toString(), TL.COMMAND_UNCLAIMALL_FORUNCLAIM.toString())) { + return; + } + } + } - LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(myFaction, fme); - Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent); - if (unclaimAllEvent.isCancelled()) { - return; - } + LandUnclaimAllEvent unclaimAllEvent = new LandUnclaimAllEvent(myFaction, fme); + Bukkit.getServer().getPluginManager().callEvent(unclaimAllEvent); + if (unclaimAllEvent.isCancelled()) { + return; + } - Board.getInstance().unclaimAll(myFaction.getId()); - myFaction.msg(TL.COMMAND_UNCLAIMALL_UNCLAIMED, fme.describeTo(myFaction, true)); + Board.getInstance().unclaimAll(myFaction.getId()); + myFaction.msg(TL.COMMAND_UNCLAIMALL_UNCLAIMED, fme.describeTo(myFaction, true)); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_UNCLAIMALL_LOG.format(fme.getName(), myFaction.getTag())); - } - } + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_UNCLAIMALL_LOG.format(fme.getName(), myFaction.getTag())); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_UNCLAIMALL_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UNCLAIMALL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java b/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java index ee8ac071..726e7c59 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdUpgrades.java @@ -6,37 +6,37 @@ import com.massivecraft.factions.zcore.fupgrades.FUpgradesGUI; import com.massivecraft.factions.zcore.util.TL; public class CmdUpgrades extends FCommand { - public CmdUpgrades() { - super(); - this.aliases.add("upgrades"); - this.aliases.add("upgrade"); + public CmdUpgrades() { + super(); + this.aliases.add("upgrades"); + this.aliases.add("upgrade"); - //this.requiredArgs.add(""); - this.optionalArgs.put("mobs/crops/exp", ""); + //this.requiredArgs.add(""); + this.optionalArgs.put("mobs/crops/exp", ""); - this.permission = Permission.UPGRADES.node; - this.disableOnLock = true; + this.permission = Permission.UPGRADES.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fupgrades.Enabled")) { - fme.sendMessage("This command is disabled!"); - return; - } - FUpgradesGUI fgui = new FUpgradesGUI(); - fgui.openMainMenu(fme); - } + @Override + public void perform() { + if (!SavageFactions.plugin.getConfig().getBoolean("fupgrades.Enabled")) { + fme.sendMessage("This command is disabled!"); + return; + } + FUpgradesGUI fgui = new FUpgradesGUI(); + fgui.openMainMenu(fme); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_UPGRADES_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_UPGRADES_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdVault.java b/src/main/java/com/massivecraft/factions/cmd/CmdVault.java index 55fd8150..c4909596 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdVault.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdVault.java @@ -14,66 +14,66 @@ import org.bukkit.inventory.Inventory; public class CmdVault extends FCommand { - public CmdVault() { - this.aliases.add("vault"); + public CmdVault() { + this.aliases.add("vault"); - //this.requiredArgs.add(""); + //this.requiredArgs.add(""); - this.permission = Permission.VAULT.node; - this.disableOnLock = false; + this.permission = Permission.VAULT.node; + this.disableOnLock = false; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { + @Override + public void perform() { - if (!SavageFactions.plugin.getConfig().getBoolean("fvault.Enabled")) { - fme.sendMessage("This command is disabled!"); - return; - } - Access access = fme.getFaction().getAccess(fme, PermissableAction.VAULT); - if (access.equals(Access.DENY)) { - fme.msg(TL.GENERIC_NOPERMISSION, "vault"); - return; - } + if (!SavageFactions.plugin.getConfig().getBoolean("fvault.Enabled")) { + fme.sendMessage("This command is disabled!"); + return; + } + Access access = fme.getFaction().getAccess(fme, PermissableAction.VAULT); + if (access.equals(Access.DENY)) { + fme.msg(TL.GENERIC_NOPERMISSION, "vault"); + return; + } - if (fme.isInVault()) { - me.closeInventory(); - return; - } - fme.setInVault(true); - Location vaultLocation = fme.getFaction().getVault(); - if (vaultLocation == null) { - fme.msg(TL.COMMAND_VAULT_INVALID); - return; - } - FLocation vaultFLocation = new FLocation(vaultLocation); - if (Board.getInstance().getFactionAt(vaultFLocation) != fme.getFaction()) { - fme.getFaction().setVault(null); - fme.msg(TL.COMMAND_VAULT_INVALID); - return; - } - if (vaultLocation.getBlock().getType() != Material.CHEST) { - fme.getFaction().setVault(null); - fme.msg(TL.COMMAND_VAULT_INVALID); - return; - } - Chest chest = (Chest) vaultLocation.getBlock().getState(); - Inventory chestInv = chest.getBlockInventory(); - fme.msg(TL.COMMAND_VAULT_OPENING); - me.openInventory(chestInv); + if (fme.isInVault()) { + me.closeInventory(); + return; + } + fme.setInVault(true); + Location vaultLocation = fme.getFaction().getVault(); + if (vaultLocation == null) { + fme.msg(TL.COMMAND_VAULT_INVALID); + return; + } + FLocation vaultFLocation = new FLocation(vaultLocation); + if (Board.getInstance().getFactionAt(vaultFLocation) != fme.getFaction()) { + fme.getFaction().setVault(null); + fme.msg(TL.COMMAND_VAULT_INVALID); + return; + } + if (vaultLocation.getBlock().getType() != Material.CHEST) { + fme.getFaction().setVault(null); + fme.msg(TL.COMMAND_VAULT_INVALID); + return; + } + Chest chest = (Chest) vaultLocation.getBlock().getState(); + Inventory chestInv = chest.getBlockInventory(); + fme.msg(TL.COMMAND_VAULT_OPENING); + me.openInventory(chestInv); - } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_VAULT_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VAULT_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java index e0772fdc..f10f4e36 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdVersion.java @@ -7,30 +7,30 @@ import com.massivecraft.factions.zcore.util.TL; public class CmdVersion extends FCommand { - public CmdVersion() { - this.aliases.add("version"); - this.aliases.add("ver"); + public CmdVersion() { + this.aliases.add("version"); + this.aliases.add("ver"); - //this.requiredArgs.add(""); - //this.optionalArgs.put("", ""); + //this.requiredArgs.add(""); + //this.optionalArgs.put("", ""); - this.permission = Permission.VERSION.node; - this.disableOnLock = false; + this.permission = Permission.VERSION.node; + this.disableOnLock = false; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - msg(TL.COMMAND_VERSION_NAME); // Did this so people can differentiate between SavageFactions and FactionsUUID (( Requested Feature )) - msg(TL.COMMAND_VERSION_VERSION, SavageFactions.plugin.getDescription().getFullName()); - } + @Override + public void perform() { + msg(TL.COMMAND_VERSION_NAME); // Did this so people can differentiate between SavageFactions and FactionsUUID (( Requested Feature )) + msg(TL.COMMAND_VERSION_VERSION, SavageFactions.plugin.getDescription().getFullName()); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_VERSION_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_VERSION_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java b/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java index f69b3390..6a206a1d 100644 --- a/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java +++ b/src/main/java/com/massivecraft/factions/cmd/CmdWarunclaimall.java @@ -11,51 +11,51 @@ import org.bukkit.World; public class CmdWarunclaimall extends FCommand { - public CmdWarunclaimall() { - this.aliases.add("warunclaimall"); - this.aliases.add("wardeclaimall"); + public CmdWarunclaimall() { + this.aliases.add("warunclaimall"); + this.aliases.add("wardeclaimall"); - //this.requiredArgs.add(""); - this.optionalArgs.put("world", "all"); + //this.requiredArgs.add(""); + this.optionalArgs.put("world", "all"); - this.permission = Permission.MANAGE_WAR_ZONE.node; - this.disableOnLock = true; + this.permission = Permission.MANAGE_WAR_ZONE.node; + this.disableOnLock = true; - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; - } + } - @Override - public void perform() { - String worldName = argAsString(0); - World world = null; + @Override + public void perform() { + String worldName = argAsString(0); + World world = null; - if (worldName != null) { - world = Bukkit.getWorld(worldName); - } + if (worldName != null) { + world = Bukkit.getWorld(worldName); + } - String id = Factions.getInstance().getWarZone().getId(); + String id = Factions.getInstance().getWarZone().getId(); - if (world == null) { - Board.getInstance().unclaimAll(id); - } else { - Board.getInstance().unclaimAllInWorld(id, world); - } + if (world == null) { + Board.getInstance().unclaimAll(id); + } else { + Board.getInstance().unclaimAllInWorld(id, world); + } - fme.msg(TL.COMMAND_WARUNCLAIMALL_SUCCESS); + fme.msg(TL.COMMAND_WARUNCLAIMALL_SUCCESS); - if (Conf.logLandUnclaims) { - SavageFactions.plugin.log(TL.COMMAND_WARUNCLAIMALL_LOG.format(fme.getName())); - } - } + if (Conf.logLandUnclaims) { + SavageFactions.plugin.log(TL.COMMAND_WARUNCLAIMALL_LOG.format(fme.getName())); + } + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_WARUNCLAIMALL_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_WARUNCLAIMALL_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java index 96cb84f5..e94b5b6f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCmdRoot.java @@ -10,249 +10,249 @@ import java.util.logging.Level; public class FCmdRoot extends FCommand { - public CmdAdmin cmdAdmin = new CmdAdmin(); - public CmdAutoClaim cmdAutoClaim = new CmdAutoClaim(); - public CmdBoom cmdBoom = new CmdBoom(); - public CmdBypass cmdBypass = new CmdBypass(); - public CmdChat cmdChat = new CmdChat(); - public CmdChatSpy cmdChatSpy = new CmdChatSpy(); - public CmdClaim cmdClaim = new CmdClaim(); - public CmdConfig cmdConfig = new CmdConfig(); - public CmdCreate cmdCreate = new CmdCreate(); - public CmdDeinvite cmdDeinvite = new CmdDeinvite(); - public CmdDescription cmdDescription = new CmdDescription(); - public CmdDisband cmdDisband = new CmdDisband(); - public CmdFocus cmdFocus = new CmdFocus(); - public CmdHelp cmdHelp = new CmdHelp(); - public CmdHome cmdHome = new CmdHome(); - public CmdInvite cmdInvite = new CmdInvite(); - public CmdJoin cmdJoin = new CmdJoin(); - public CmdKick cmdKick = new CmdKick(); - public CmdLeave cmdLeave = new CmdLeave(); - public CmdList cmdList = new CmdList(); - public CmdLock cmdLock = new CmdLock(); - public CmdMap cmdMap = new CmdMap(); - public CmdMod cmdMod = new CmdMod(); - public CmdMoney cmdMoney = new CmdMoney(); - public CmdOpen cmdOpen = new CmdOpen(); - public CmdOwner cmdOwner = new CmdOwner(); - public CmdOwnerList cmdOwnerList = new CmdOwnerList(); - public CmdPeaceful cmdPeaceful = new CmdPeaceful(); - public CmdPermanent cmdPermanent = new CmdPermanent(); - public CmdPermanentPower cmdPermanentPower = new CmdPermanentPower(); - public CmdPowerBoost cmdPowerBoost = new CmdPowerBoost(); - public CmdPower cmdPower = new CmdPower(); - public CmdRelationAlly cmdRelationAlly = new CmdRelationAlly(); - public CmdRelationEnemy cmdRelationEnemy = new CmdRelationEnemy(); - public CmdRelationNeutral cmdRelationNeutral = new CmdRelationNeutral(); - public CmdRelationTruce cmdRelationTruce = new CmdRelationTruce(); - public CmdReload cmdReload = new CmdReload(); - public CmdSafeunclaimall cmdSafeunclaimall = new CmdSafeunclaimall(); - public CmdSaveAll cmdSaveAll = new CmdSaveAll(); - public CmdSethome cmdSethome = new CmdSethome(); - public CmdShow cmdShow = new CmdShow(); - public CmdStatus cmdStatus = new CmdStatus(); - public CmdStealth cmdStealth = new CmdStealth(); - public CmdStuck cmdStuck = new CmdStuck(); - public CmdTag cmdTag = new CmdTag(); - public CmdTitle cmdTitle = new CmdTitle(); - public CmdToggleAllianceChat cmdToggleAllianceChat = new CmdToggleAllianceChat(); - public CmdUnclaim cmdUnclaim = new CmdUnclaim(); - public CmdUnclaimall cmdUnclaimall = new CmdUnclaimall(); - public CmdVersion cmdVersion = new CmdVersion(); - public CmdWarunclaimall cmdWarunclaimall = new CmdWarunclaimall(); - public CmdSB cmdSB = new CmdSB(); - public CmdShowInvites cmdShowInvites = new CmdShowInvites(); - public CmdAnnounce cmdAnnounce = new CmdAnnounce(); - public CmdPaypalSet cmdPaypalSet = new CmdPaypalSet(); - public CmdPaypalSee cmdPaypalSee = new CmdPaypalSee(); - public CmdSeeChunk cmdSeeChunk = new CmdSeeChunk(); - public CmdConvert cmdConvert = new CmdConvert(); - public CmdFWarp cmdFWarp = new CmdFWarp(); - public CmdSetFWarp cmdSetFWarp = new CmdSetFWarp(); - public CmdDelFWarp cmdDelFWarp = new CmdDelFWarp(); - public CmdModifyPower cmdModifyPower = new CmdModifyPower(); - public CmdLogins cmdLogins = new CmdLogins(); - public CmdClaimLine cmdClaimLine = new CmdClaimLine(); - public CmdTop cmdTop = new CmdTop(); - public CmdAHome cmdAHome = new CmdAHome(); - public CmdPerm cmdPerm = new CmdPerm(); - public CmdPromote cmdPromote = new CmdPromote(); - public CmdDemote cmdDemote = new CmdDemote(); - public CmdSetDefaultRole cmdSetDefaultRole = new CmdSetDefaultRole(); - public CmdMapHeight cmdMapHeight = new CmdMapHeight(); - public CmdClaimAt cmdClaimAt = new CmdClaimAt(); - public CmdBan cmdban = new CmdBan(); - public CmdUnban cmdUnban = new CmdUnban(); - public CmdBanlist cmdbanlist = new CmdBanlist(); - public CmdRules cmdRules = new CmdRules(); - public CmdCheckpoint cmdCheckpoint = new CmdCheckpoint(); - public CmdTnt cmdTnt = new CmdTnt(); - public CmdNear cmdNear = new CmdNear(); - public CmdUpgrades cmdUpgrades = new CmdUpgrades(); - public CmdVault cmdVault = new CmdVault(); - public CmdGetVault cmdGetVault = new CmdGetVault(); - public CmdFly cmdFly = new CmdFly(); - public CmdColeader cmdColeader = new CmdColeader(); - public CmdBanner cmdBanner = new CmdBanner(); - public CmdTpBanner cmdTpBanner = new CmdTpBanner(); - public CmdKillHolograms cmdKillHolograms = new CmdKillHolograms(); - public CmdInspect cmdInspect = new CmdInspect(); - public CmdCoords cmdCoords = new CmdCoords(); - public CmdShowClaims cmdShowClaims = new CmdShowClaims(); - public CmdLowPower cmdLowPower = new CmdLowPower(); - public CmdTntFill cmdTntFill = new CmdTntFill(); - public CmdChest cmdChest = new CmdChest(); - public CmdSetBanner cmdSetBanner = new CmdSetBanner(); + public CmdAdmin cmdAdmin = new CmdAdmin(); + public CmdAutoClaim cmdAutoClaim = new CmdAutoClaim(); + public CmdBoom cmdBoom = new CmdBoom(); + public CmdBypass cmdBypass = new CmdBypass(); + public CmdChat cmdChat = new CmdChat(); + public CmdChatSpy cmdChatSpy = new CmdChatSpy(); + public CmdClaim cmdClaim = new CmdClaim(); + public CmdConfig cmdConfig = new CmdConfig(); + public CmdCreate cmdCreate = new CmdCreate(); + public CmdDeinvite cmdDeinvite = new CmdDeinvite(); + public CmdDescription cmdDescription = new CmdDescription(); + public CmdDisband cmdDisband = new CmdDisband(); + public CmdFocus cmdFocus = new CmdFocus(); + public CmdHelp cmdHelp = new CmdHelp(); + public CmdHome cmdHome = new CmdHome(); + public CmdInvite cmdInvite = new CmdInvite(); + public CmdJoin cmdJoin = new CmdJoin(); + public CmdKick cmdKick = new CmdKick(); + public CmdLeave cmdLeave = new CmdLeave(); + public CmdList cmdList = new CmdList(); + public CmdLock cmdLock = new CmdLock(); + public CmdMap cmdMap = new CmdMap(); + public CmdMod cmdMod = new CmdMod(); + public CmdMoney cmdMoney = new CmdMoney(); + public CmdOpen cmdOpen = new CmdOpen(); + public CmdOwner cmdOwner = new CmdOwner(); + public CmdOwnerList cmdOwnerList = new CmdOwnerList(); + public CmdPeaceful cmdPeaceful = new CmdPeaceful(); + public CmdPermanent cmdPermanent = new CmdPermanent(); + public CmdPermanentPower cmdPermanentPower = new CmdPermanentPower(); + public CmdPowerBoost cmdPowerBoost = new CmdPowerBoost(); + public CmdPower cmdPower = new CmdPower(); + public CmdRelationAlly cmdRelationAlly = new CmdRelationAlly(); + public CmdRelationEnemy cmdRelationEnemy = new CmdRelationEnemy(); + public CmdRelationNeutral cmdRelationNeutral = new CmdRelationNeutral(); + public CmdRelationTruce cmdRelationTruce = new CmdRelationTruce(); + public CmdReload cmdReload = new CmdReload(); + public CmdSafeunclaimall cmdSafeunclaimall = new CmdSafeunclaimall(); + public CmdSaveAll cmdSaveAll = new CmdSaveAll(); + public CmdSethome cmdSethome = new CmdSethome(); + public CmdShow cmdShow = new CmdShow(); + public CmdStatus cmdStatus = new CmdStatus(); + public CmdStealth cmdStealth = new CmdStealth(); + public CmdStuck cmdStuck = new CmdStuck(); + public CmdTag cmdTag = new CmdTag(); + public CmdTitle cmdTitle = new CmdTitle(); + public CmdToggleAllianceChat cmdToggleAllianceChat = new CmdToggleAllianceChat(); + public CmdUnclaim cmdUnclaim = new CmdUnclaim(); + public CmdUnclaimall cmdUnclaimall = new CmdUnclaimall(); + public CmdVersion cmdVersion = new CmdVersion(); + public CmdWarunclaimall cmdWarunclaimall = new CmdWarunclaimall(); + public CmdSB cmdSB = new CmdSB(); + public CmdShowInvites cmdShowInvites = new CmdShowInvites(); + public CmdAnnounce cmdAnnounce = new CmdAnnounce(); + public CmdPaypalSet cmdPaypalSet = new CmdPaypalSet(); + public CmdPaypalSee cmdPaypalSee = new CmdPaypalSee(); + public CmdSeeChunk cmdSeeChunk = new CmdSeeChunk(); + public CmdConvert cmdConvert = new CmdConvert(); + public CmdFWarp cmdFWarp = new CmdFWarp(); + public CmdSetFWarp cmdSetFWarp = new CmdSetFWarp(); + public CmdDelFWarp cmdDelFWarp = new CmdDelFWarp(); + public CmdModifyPower cmdModifyPower = new CmdModifyPower(); + public CmdLogins cmdLogins = new CmdLogins(); + public CmdClaimLine cmdClaimLine = new CmdClaimLine(); + public CmdTop cmdTop = new CmdTop(); + public CmdAHome cmdAHome = new CmdAHome(); + public CmdPerm cmdPerm = new CmdPerm(); + public CmdPromote cmdPromote = new CmdPromote(); + public CmdDemote cmdDemote = new CmdDemote(); + public CmdSetDefaultRole cmdSetDefaultRole = new CmdSetDefaultRole(); + public CmdMapHeight cmdMapHeight = new CmdMapHeight(); + public CmdClaimAt cmdClaimAt = new CmdClaimAt(); + public CmdBan cmdban = new CmdBan(); + public CmdUnban cmdUnban = new CmdUnban(); + public CmdBanlist cmdbanlist = new CmdBanlist(); + public CmdRules cmdRules = new CmdRules(); + public CmdCheckpoint cmdCheckpoint = new CmdCheckpoint(); + public CmdTnt cmdTnt = new CmdTnt(); + public CmdNear cmdNear = new CmdNear(); + public CmdUpgrades cmdUpgrades = new CmdUpgrades(); + public CmdVault cmdVault = new CmdVault(); + public CmdGetVault cmdGetVault = new CmdGetVault(); + public CmdFly cmdFly = new CmdFly(); + public CmdColeader cmdColeader = new CmdColeader(); + public CmdBanner cmdBanner = new CmdBanner(); + public CmdTpBanner cmdTpBanner = new CmdTpBanner(); + public CmdKillHolograms cmdKillHolograms = new CmdKillHolograms(); + public CmdInspect cmdInspect = new CmdInspect(); + public CmdCoords cmdCoords = new CmdCoords(); + public CmdShowClaims cmdShowClaims = new CmdShowClaims(); + public CmdLowPower cmdLowPower = new CmdLowPower(); + public CmdTntFill cmdTntFill = new CmdTntFill(); + public CmdChest cmdChest = new CmdChest(); + public CmdSetBanner cmdSetBanner = new CmdSetBanner(); - public FCmdRoot() { - super(); - this.aliases.addAll(Conf.baseCommandAliases); - this.aliases.removeAll(Collections.singletonList(null)); // remove any nulls from extra commas - this.allowNoSlashAccess = Conf.allowNoSlashCommand; + public FCmdRoot() { + super(); + this.aliases.addAll(Conf.baseCommandAliases); + this.aliases.removeAll(Collections.singletonList(null)); // remove any nulls from extra commas + this.allowNoSlashAccess = Conf.allowNoSlashCommand; - //this.requiredArgs.add(""); - //this.optionalArgs.put("","") + //this.requiredArgs.add(""); + //this.optionalArgs.put("","") - senderMustBePlayer = false; - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeAdmin = false; + senderMustBePlayer = false; + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeAdmin = false; - this.disableOnLock = false; + this.disableOnLock = false; - this.setHelpShort("The faction base command"); - this.helpLong.add(p.txt.parseTags("This command contains all faction stuff.")); + this.setHelpShort("The faction base command"); + this.helpLong.add(p.txt.parseTags("This command contains all faction stuff.")); - //this.subCommands.add(plugin.cmdHelp); + //this.subCommands.add(plugin.cmdHelp); - this.addSubCommand(this.cmdAdmin); - this.addSubCommand(this.cmdAutoClaim); - this.addSubCommand(this.cmdBoom); - this.addSubCommand(this.cmdBypass); - this.addSubCommand(this.cmdChat); - this.addSubCommand(this.cmdToggleAllianceChat); - this.addSubCommand(this.cmdChatSpy); - this.addSubCommand(this.cmdClaim); - this.addSubCommand(this.cmdConfig); - this.addSubCommand(this.cmdCreate); - this.addSubCommand(this.cmdDeinvite); - this.addSubCommand(this.cmdDescription); - this.addSubCommand(this.cmdDisband); + this.addSubCommand(this.cmdAdmin); + this.addSubCommand(this.cmdAutoClaim); + this.addSubCommand(this.cmdBoom); + this.addSubCommand(this.cmdBypass); + this.addSubCommand(this.cmdChat); + this.addSubCommand(this.cmdToggleAllianceChat); + this.addSubCommand(this.cmdChatSpy); + this.addSubCommand(this.cmdClaim); + this.addSubCommand(this.cmdConfig); + this.addSubCommand(this.cmdCreate); + this.addSubCommand(this.cmdDeinvite); + this.addSubCommand(this.cmdDescription); + this.addSubCommand(this.cmdDisband); - this.addSubCommand(this.cmdHelp); - this.addSubCommand(this.cmdHome); - this.addSubCommand(this.cmdInvite); - this.addSubCommand(this.cmdJoin); - this.addSubCommand(this.cmdKick); - this.addSubCommand(this.cmdLeave); - this.addSubCommand(this.cmdList); - this.addSubCommand(this.cmdLock); - this.addSubCommand(this.cmdMap); - this.addSubCommand(this.cmdMod); - this.addSubCommand(this.cmdMoney); - this.addSubCommand(this.cmdOpen); - this.addSubCommand(this.cmdOwner); - this.addSubCommand(this.cmdOwnerList); - this.addSubCommand(this.cmdPeaceful); - this.addSubCommand(this.cmdPermanent); - this.addSubCommand(this.cmdPermanentPower); - this.addSubCommand(this.cmdPower); - this.addSubCommand(this.cmdPowerBoost); - this.addSubCommand(this.cmdRelationAlly); - this.addSubCommand(this.cmdRelationEnemy); - this.addSubCommand(this.cmdRelationNeutral); - this.addSubCommand(this.cmdRelationTruce); - this.addSubCommand(this.cmdReload); - this.addSubCommand(this.cmdSafeunclaimall); - this.addSubCommand(this.cmdSaveAll); - this.addSubCommand(this.cmdSethome); - this.addSubCommand(this.cmdShow); - this.addSubCommand(this.cmdStatus); - this.addSubCommand(this.cmdStealth); - this.addSubCommand(this.cmdStuck); - this.addSubCommand(this.cmdTag); - this.addSubCommand(this.cmdTitle); - this.addSubCommand(this.cmdUnclaim); - this.addSubCommand(this.cmdUnclaimall); - this.addSubCommand(this.cmdVersion); - this.addSubCommand(this.cmdWarunclaimall); - this.addSubCommand(this.cmdSB); - this.addSubCommand(this.cmdShowInvites); - this.addSubCommand(this.cmdAnnounce); - this.addSubCommand(this.cmdSeeChunk); - this.addSubCommand(this.cmdConvert); - this.addSubCommand(this.cmdFWarp); - this.addSubCommand(this.cmdSetFWarp); - this.addSubCommand(this.cmdDelFWarp); - this.addSubCommand(this.cmdModifyPower); - this.addSubCommand(this.cmdLogins); - this.addSubCommand(this.cmdClaimLine); - this.addSubCommand(this.cmdAHome); - this.addSubCommand(this.cmdPerm); - this.addSubCommand(this.cmdPromote); - this.addSubCommand(this.cmdDemote); - this.addSubCommand(this.cmdSetDefaultRole); - this.addSubCommand(this.cmdMapHeight); - this.addSubCommand(this.cmdClaimAt); - this.addSubCommand(this.cmdban); - this.addSubCommand(this.cmdUnban); - this.addSubCommand(this.cmdbanlist); - this.addSubCommand(this.cmdRules); - this.addSubCommand(this.cmdCheckpoint); - this.addSubCommand(this.cmdTnt); - this.addSubCommand(this.cmdNear); - this.addSubCommand(this.cmdUpgrades); - this.addSubCommand(this.cmdVault); - this.addSubCommand(this.cmdGetVault); - this.addSubCommand(this.cmdColeader); - this.addSubCommand(this.cmdBanner); - this.addSubCommand(this.cmdTpBanner); - this.addSubCommand(this.cmdKillHolograms); - this.addSubCommand(this.cmdCoords); - this.addSubCommand(this.cmdShowClaims); - this.addSubCommand(this.cmdLowPower); - this.addSubCommand(this.cmdTntFill); - this.addSubCommand(this.cmdChest); - this.addSubCommand(this.cmdSetBanner); + this.addSubCommand(this.cmdHelp); + this.addSubCommand(this.cmdHome); + this.addSubCommand(this.cmdInvite); + this.addSubCommand(this.cmdJoin); + this.addSubCommand(this.cmdKick); + this.addSubCommand(this.cmdLeave); + this.addSubCommand(this.cmdList); + this.addSubCommand(this.cmdLock); + this.addSubCommand(this.cmdMap); + this.addSubCommand(this.cmdMod); + this.addSubCommand(this.cmdMoney); + this.addSubCommand(this.cmdOpen); + this.addSubCommand(this.cmdOwner); + this.addSubCommand(this.cmdOwnerList); + this.addSubCommand(this.cmdPeaceful); + this.addSubCommand(this.cmdPermanent); + this.addSubCommand(this.cmdPermanentPower); + this.addSubCommand(this.cmdPower); + this.addSubCommand(this.cmdPowerBoost); + this.addSubCommand(this.cmdRelationAlly); + this.addSubCommand(this.cmdRelationEnemy); + this.addSubCommand(this.cmdRelationNeutral); + this.addSubCommand(this.cmdRelationTruce); + this.addSubCommand(this.cmdReload); + this.addSubCommand(this.cmdSafeunclaimall); + this.addSubCommand(this.cmdSaveAll); + this.addSubCommand(this.cmdSethome); + this.addSubCommand(this.cmdShow); + this.addSubCommand(this.cmdStatus); + this.addSubCommand(this.cmdStealth); + this.addSubCommand(this.cmdStuck); + this.addSubCommand(this.cmdTag); + this.addSubCommand(this.cmdTitle); + this.addSubCommand(this.cmdUnclaim); + this.addSubCommand(this.cmdUnclaimall); + this.addSubCommand(this.cmdVersion); + this.addSubCommand(this.cmdWarunclaimall); + this.addSubCommand(this.cmdSB); + this.addSubCommand(this.cmdShowInvites); + this.addSubCommand(this.cmdAnnounce); + this.addSubCommand(this.cmdSeeChunk); + this.addSubCommand(this.cmdConvert); + this.addSubCommand(this.cmdFWarp); + this.addSubCommand(this.cmdSetFWarp); + this.addSubCommand(this.cmdDelFWarp); + this.addSubCommand(this.cmdModifyPower); + this.addSubCommand(this.cmdLogins); + this.addSubCommand(this.cmdClaimLine); + this.addSubCommand(this.cmdAHome); + this.addSubCommand(this.cmdPerm); + this.addSubCommand(this.cmdPromote); + this.addSubCommand(this.cmdDemote); + this.addSubCommand(this.cmdSetDefaultRole); + this.addSubCommand(this.cmdMapHeight); + this.addSubCommand(this.cmdClaimAt); + this.addSubCommand(this.cmdban); + this.addSubCommand(this.cmdUnban); + this.addSubCommand(this.cmdbanlist); + this.addSubCommand(this.cmdRules); + this.addSubCommand(this.cmdCheckpoint); + this.addSubCommand(this.cmdTnt); + this.addSubCommand(this.cmdNear); + this.addSubCommand(this.cmdUpgrades); + this.addSubCommand(this.cmdVault); + this.addSubCommand(this.cmdGetVault); + this.addSubCommand(this.cmdColeader); + this.addSubCommand(this.cmdBanner); + this.addSubCommand(this.cmdTpBanner); + this.addSubCommand(this.cmdKillHolograms); + this.addSubCommand(this.cmdCoords); + this.addSubCommand(this.cmdShowClaims); + this.addSubCommand(this.cmdLowPower); + this.addSubCommand(this.cmdTntFill); + this.addSubCommand(this.cmdChest); + this.addSubCommand(this.cmdSetBanner); - if (Bukkit.getServer().getPluginManager().getPlugin("CoreProtect") != null) { - SavageFactions.plugin.log("Found CoreProtect, enabling Inspect"); - this.addSubCommand(this.cmdInspect); - } else { - SavageFactions.plugin.log("CoreProtect not found, disabling Inspect"); - } - if (SavageFactions.plugin.getConfig().getBoolean("ffocus.Enabled")) { - addSubCommand(this.cmdFocus); - } + if (Bukkit.getServer().getPluginManager().getPlugin("CoreProtect") != null) { + SavageFactions.plugin.log("Found CoreProtect, enabling Inspect"); + this.addSubCommand(this.cmdInspect); + } else { + SavageFactions.plugin.log("CoreProtect not found, disabling Inspect"); + } + if (SavageFactions.plugin.getConfig().getBoolean("ffocus.Enabled")) { + addSubCommand(this.cmdFocus); + } - if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight", false)) { - this.addSubCommand(this.cmdFly); - } - if (Bukkit.getServer().getPluginManager().getPlugin("FactionsTop") != null) { - SavageFactions.plugin.log(Level.INFO, "Found FactionsTop plugin. Disabling our own /f top command."); - } else { - SavageFactions.plugin.log(Level.INFO, "Enabling FactionsTop command, this is a very basic /f top please get a dedicated /f top resource if you want land calculation etc."); - this.addSubCommand(this.cmdTop); - } - if (SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { - this.addSubCommand(this.cmdPaypalSet); - this.addSubCommand(this.cmdPaypalSee); - } + if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight", false)) { + this.addSubCommand(this.cmdFly); + } + if (Bukkit.getServer().getPluginManager().getPlugin("FactionsTop") != null) { + SavageFactions.plugin.log(Level.INFO, "Found FactionsTop plugin. Disabling our own /f top command."); + } else { + SavageFactions.plugin.log(Level.INFO, "Enabling FactionsTop command, this is a very basic /f top please get a dedicated /f top resource if you want land calculation etc."); + this.addSubCommand(this.cmdTop); + } + if (SavageFactions.plugin.getConfig().getBoolean("fpaypal.Enabled")) { + this.addSubCommand(this.cmdPaypalSet); + this.addSubCommand(this.cmdPaypalSee); + } - } + } - @Override - public void perform() { - this.commandChain.add(this); - this.cmdHelp.execute(this.sender, this.args, this.commandChain); - } + @Override + public void perform() { + this.commandChain.add(this); + this.cmdHelp.execute(this.sender, this.args, this.commandChain); + } - @Override - public TL getUsageTranslation() { - return TL.GENERIC_PLACEHOLDER; - } + @Override + public TL getUsageTranslation() { + return TL.GENERIC_PLACEHOLDER; + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FCommand.java b/src/main/java/com/massivecraft/factions/cmd/FCommand.java index e8e9d635..03aab442 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FCommand.java @@ -15,330 +15,330 @@ import java.util.List; public abstract class FCommand extends MCommand { - public static final SimpleDateFormat sdf = new SimpleDateFormat(TL.DATE_FORMAT.toString()); - - public boolean disableOnLock; - - public FPlayer fme; - public Faction myFaction; - public boolean senderMustBeMember; - public boolean senderMustBeModerator; - public boolean senderMustBeAdmin; - public boolean senderMustBeColeader; - - - public boolean isMoneyCommand; - - public FCommand() { - super(SavageFactions.plugin); - - // Due to safety reasons it defaults to disable on lock. - disableOnLock = true; - - // The money commands must be disabled if money should not be used. - isMoneyCommand = false; - - senderMustBeMember = false; - senderMustBeModerator = false; - senderMustBeColeader = false; - senderMustBeAdmin = false; - } - - @Override - public void setCommandSender(CommandSender sender) { - super.setCommandSender(sender); - if (sender instanceof Player) { - this.fme = FPlayers.getInstance().getByPlayer((Player) sender); - this.myFaction = this.fme.getFaction(); - } else { - this.fme = null; - this.myFaction = null; - } - } - - @Override - public void execute(CommandSender sender, List args, List> commandChain) { - setCommandSender(sender); - super.execute(sender, args, commandChain); - } - - @Override - public boolean isEnabled() { - if (p.getLocked() && this.disableOnLock) { - msg("Factions was locked by an admin. Please try again later."); - return false; - } - - if (this.isMoneyCommand && !Conf.econEnabled) { - msg("Faction economy features are disabled on this server."); - return false; - } - - if (this.isMoneyCommand && !Conf.bankEnabled) { - msg("The faction bank system is disabled on this server."); - return false; - } - - return true; - } - - @Override - public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { - boolean superValid = super.validSenderType(sender, informSenderIfNot); - if (!superValid) { - return false; - } - - if (!(this.senderMustBeMember || this.senderMustBeModerator || this.senderMustBeAdmin || this.senderMustBeColeader)) { - return true; - } - - if (!(sender instanceof Player)) { - return false; - } - - if (!fme.hasFaction()) { - if (informSenderIfNot) { - sender.sendMessage(p.txt.parse("You are not member of any faction.")); - } - return false; - } - - - if (this.senderMustBeModerator && !fme.getRole().isAtLeast(Role.MODERATOR)) { - if (informSenderIfNot) { - sender.sendMessage(p.txt.parse("Only faction moderators can %s.", this.getHelpShort())); - } - return false; - } - - if (this.senderMustBeColeader && !fme.getRole().isAtLeast(Role.COLEADER)) { - if (informSenderIfNot) { - sender.sendMessage(p.txt.parse("Only faction coleaders can %s.", this.getHelpShort())); - } - return false; - } - - if (this.senderMustBeAdmin && !fme.getRole().isAtLeast(Role.LEADER)) { - if (informSenderIfNot) { - sender.sendMessage(p.txt.parse("Only faction admins can %s.", this.getHelpShort())); - } - return false; - } - - - return true; - } - - // -------------------------------------------- // - // Assertions - // -------------------------------------------- // - - public boolean assertHasFaction() { - if (me == null) { - return true; - } - - if (!fme.hasFaction()) { - sendMessage("You are not member of any faction."); - return false; - } - return true; - } - - public boolean assertMinRole(Role role) { - if (me == null) { - return true; - } - - if (fme.getRole().value < role.value) { - msg("You must be " + role + " to " + this.getHelpShort() + "."); - return false; - } - return true; - } - - // -------------------------------------------- // - // Argument Readers - // -------------------------------------------- // - - // FPLAYER ====================== - public FPlayer strAsFPlayer(String name, FPlayer def, boolean msg) { - FPlayer ret = def; - - if (name != null) { - for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { - if (fplayer.getName().equalsIgnoreCase(name)) { - ret = fplayer; - break; - } - } - } - - if (msg && ret == null) { - this.msg("No player \"%s\" could be found.", name); - } - - return ret; - } - - public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) { - return this.strAsFPlayer(this.argAsString(idx), def, msg); - } - - public FPlayer argAsFPlayer(int idx, FPlayer def) { - return this.argAsFPlayer(idx, def, true); - } - - public FPlayer argAsFPlayer(int idx) { - return this.argAsFPlayer(idx, null); - } - - // BEST FPLAYER MATCH ====================== - public FPlayer strAsBestFPlayerMatch(String name, FPlayer def, boolean msg) { - return strAsFPlayer(name, def, msg); - } - - public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def, boolean msg) { - return this.strAsBestFPlayerMatch(this.argAsString(idx), def, msg); - } - - public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) { - return this.argAsBestFPlayerMatch(idx, def, true); - } - - public FPlayer argAsBestFPlayerMatch(int idx) { - return this.argAsBestFPlayerMatch(idx, null); - } - - // FACTION ====================== - public Faction strAsFaction(String name, Faction def, boolean msg) { - Faction ret = def; - - if (name != null) { - // First we try an exact match - Faction faction = Factions.getInstance().getByTag(name); // Checks for faction name match. - - // Now lets try for warzone / safezone. Helpful for custom warzone / safezone names. - // Do this after we check for an exact match in case they rename the warzone / safezone - // and a player created faction took one of the names. - if (faction == null) { - if (name.equalsIgnoreCase("warzone")) { - faction = Factions.getInstance().getWarZone(); - } else if (name.equalsIgnoreCase("safezone")) { - faction = Factions.getInstance().getSafeZone(); - } - } - - // Next we match faction tags - if (faction == null) { - faction = Factions.getInstance().getBestTagMatch(name); - } - - // Next we match player names - if (faction == null) { - FPlayer fplayer = strAsFPlayer(name, null, false); - if (fplayer != null) { - faction = fplayer.getFaction(); - } - } - - if (faction != null) { - ret = faction; - } - } - - if (msg && ret == null) { - this.msg("The faction or player \"%s\" could not be found.", name); - } - - return ret; - } - - public Faction argAsFaction(int idx, Faction def, boolean msg) { - return this.strAsFaction(this.argAsString(idx), def, msg); - } - - public Faction argAsFaction(int idx, Faction def) { - return this.argAsFaction(idx, def, true); - } - - public Faction argAsFaction(int idx) { - return this.argAsFaction(idx, null); - } - - // -------------------------------------------- // - // Commonly used logic - // -------------------------------------------- // - - public boolean canIAdministerYou(FPlayer i, FPlayer you) { - if (!i.getFaction().equals(you.getFaction())) { - i.sendMessage(p.txt.parse("%s is not in the same faction as you.", you.describeTo(i, true))); - return false; - } - - if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.LEADER)) { - return true; - } - - if (you.getRole().equals(Role.LEADER)) { - i.sendMessage(p.txt.parse("Only the faction admin can do that.")); - - } else if ((you.getRole().equals(Role.COLEADER))) { - if (i == you) { - return true; - } else { - i.sendMessage(p.txt.parse("Coleaders can't control each other...")); - } - - } else if (i.getRole().equals(Role.MODERATOR)) { - if (i == you) { - return true; //Moderators can control themselves - } else { - i.sendMessage(p.txt.parse("Moderators can't control each other...")); - } - } else { - i.sendMessage(p.txt.parse("You must be a faction moderator to do that.")); - } - - return false; - } - - // if economy is enabled and they're not on the bypass list, make 'em pay; returns true unless person can't afford the cost - public boolean payForCommand(double cost, String toDoThis, String forDoingThis) { - if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) { - return true; - } - - if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { - return Econ.modifyMoney(myFaction, -cost, toDoThis, forDoingThis); - } else { - return Econ.modifyMoney(fme, -cost, toDoThis, forDoingThis); - } - } - - public boolean payForCommand(double cost, TL toDoThis, TL forDoingThis) { - return payForCommand(cost, toDoThis.toString(), forDoingThis.toString()); - } - - // like above, but just make sure they can pay; returns true unless person can't afford the cost - public boolean canAffordCommand(double cost, String toDoThis) { - if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) { - return true; - } - - if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { - return Econ.hasAtLeast(myFaction, cost, toDoThis); - } else { - return Econ.hasAtLeast(fme, cost, toDoThis); - } - } - - public void doWarmUp(WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { - this.doWarmUp(this.fme, warmup, translationKey, action, runnable, delay); - } - - public void doWarmUp(FPlayer player, WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { - WarmUpUtil.process(player, warmup, translationKey, action, runnable, delay); - } + public static final SimpleDateFormat sdf = new SimpleDateFormat(TL.DATE_FORMAT.toString()); + + public boolean disableOnLock; + + public FPlayer fme; + public Faction myFaction; + public boolean senderMustBeMember; + public boolean senderMustBeModerator; + public boolean senderMustBeAdmin; + public boolean senderMustBeColeader; + + + public boolean isMoneyCommand; + + public FCommand() { + super(SavageFactions.plugin); + + // Due to safety reasons it defaults to disable on lock. + disableOnLock = true; + + // The money commands must be disabled if money should not be used. + isMoneyCommand = false; + + senderMustBeMember = false; + senderMustBeModerator = false; + senderMustBeColeader = false; + senderMustBeAdmin = false; + } + + @Override + public void setCommandSender(CommandSender sender) { + super.setCommandSender(sender); + if (sender instanceof Player) { + this.fme = FPlayers.getInstance().getByPlayer((Player) sender); + this.myFaction = this.fme.getFaction(); + } else { + this.fme = null; + this.myFaction = null; + } + } + + @Override + public void execute(CommandSender sender, List args, List> commandChain) { + setCommandSender(sender); + super.execute(sender, args, commandChain); + } + + @Override + public boolean isEnabled() { + if (p.getLocked() && this.disableOnLock) { + msg("Factions was locked by an admin. Please try again later."); + return false; + } + + if (this.isMoneyCommand && !Conf.econEnabled) { + msg("Faction economy features are disabled on this server."); + return false; + } + + if (this.isMoneyCommand && !Conf.bankEnabled) { + msg("The faction bank system is disabled on this server."); + return false; + } + + return true; + } + + @Override + public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { + boolean superValid = super.validSenderType(sender, informSenderIfNot); + if (!superValid) { + return false; + } + + if (!(this.senderMustBeMember || this.senderMustBeModerator || this.senderMustBeAdmin || this.senderMustBeColeader)) { + return true; + } + + if (!(sender instanceof Player)) { + return false; + } + + if (!fme.hasFaction()) { + if (informSenderIfNot) { + sender.sendMessage(p.txt.parse("You are not member of any faction.")); + } + return false; + } + + + if (this.senderMustBeModerator && !fme.getRole().isAtLeast(Role.MODERATOR)) { + if (informSenderIfNot) { + sender.sendMessage(p.txt.parse("Only faction moderators can %s.", this.getHelpShort())); + } + return false; + } + + if (this.senderMustBeColeader && !fme.getRole().isAtLeast(Role.COLEADER)) { + if (informSenderIfNot) { + sender.sendMessage(p.txt.parse("Only faction coleaders can %s.", this.getHelpShort())); + } + return false; + } + + if (this.senderMustBeAdmin && !fme.getRole().isAtLeast(Role.LEADER)) { + if (informSenderIfNot) { + sender.sendMessage(p.txt.parse("Only faction admins can %s.", this.getHelpShort())); + } + return false; + } + + + return true; + } + + // -------------------------------------------- // + // Assertions + // -------------------------------------------- // + + public boolean assertHasFaction() { + if (me == null) { + return true; + } + + if (!fme.hasFaction()) { + sendMessage("You are not member of any faction."); + return false; + } + return true; + } + + public boolean assertMinRole(Role role) { + if (me == null) { + return true; + } + + if (fme.getRole().value < role.value) { + msg("You must be " + role + " to " + this.getHelpShort() + "."); + return false; + } + return true; + } + + // -------------------------------------------- // + // Argument Readers + // -------------------------------------------- // + + // FPLAYER ====================== + public FPlayer strAsFPlayer(String name, FPlayer def, boolean msg) { + FPlayer ret = def; + + if (name != null) { + for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { + if (fplayer.getName().equalsIgnoreCase(name)) { + ret = fplayer; + break; + } + } + } + + if (msg && ret == null) { + this.msg("No player \"%s\" could be found.", name); + } + + return ret; + } + + public FPlayer argAsFPlayer(int idx, FPlayer def, boolean msg) { + return this.strAsFPlayer(this.argAsString(idx), def, msg); + } + + public FPlayer argAsFPlayer(int idx, FPlayer def) { + return this.argAsFPlayer(idx, def, true); + } + + public FPlayer argAsFPlayer(int idx) { + return this.argAsFPlayer(idx, null); + } + + // BEST FPLAYER MATCH ====================== + public FPlayer strAsBestFPlayerMatch(String name, FPlayer def, boolean msg) { + return strAsFPlayer(name, def, msg); + } + + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def, boolean msg) { + return this.strAsBestFPlayerMatch(this.argAsString(idx), def, msg); + } + + public FPlayer argAsBestFPlayerMatch(int idx, FPlayer def) { + return this.argAsBestFPlayerMatch(idx, def, true); + } + + public FPlayer argAsBestFPlayerMatch(int idx) { + return this.argAsBestFPlayerMatch(idx, null); + } + + // FACTION ====================== + public Faction strAsFaction(String name, Faction def, boolean msg) { + Faction ret = def; + + if (name != null) { + // First we try an exact match + Faction faction = Factions.getInstance().getByTag(name); // Checks for faction name match. + + // Now lets try for warzone / safezone. Helpful for custom warzone / safezone names. + // Do this after we check for an exact match in case they rename the warzone / safezone + // and a player created faction took one of the names. + if (faction == null) { + if (name.equalsIgnoreCase("warzone")) { + faction = Factions.getInstance().getWarZone(); + } else if (name.equalsIgnoreCase("safezone")) { + faction = Factions.getInstance().getSafeZone(); + } + } + + // Next we match faction tags + if (faction == null) { + faction = Factions.getInstance().getBestTagMatch(name); + } + + // Next we match player names + if (faction == null) { + FPlayer fplayer = strAsFPlayer(name, null, false); + if (fplayer != null) { + faction = fplayer.getFaction(); + } + } + + if (faction != null) { + ret = faction; + } + } + + if (msg && ret == null) { + this.msg("The faction or player \"%s\" could not be found.", name); + } + + return ret; + } + + public Faction argAsFaction(int idx, Faction def, boolean msg) { + return this.strAsFaction(this.argAsString(idx), def, msg); + } + + public Faction argAsFaction(int idx, Faction def) { + return this.argAsFaction(idx, def, true); + } + + public Faction argAsFaction(int idx) { + return this.argAsFaction(idx, null); + } + + // -------------------------------------------- // + // Commonly used logic + // -------------------------------------------- // + + public boolean canIAdministerYou(FPlayer i, FPlayer you) { + if (!i.getFaction().equals(you.getFaction())) { + i.sendMessage(p.txt.parse("%s is not in the same faction as you.", you.describeTo(i, true))); + return false; + } + + if (i.getRole().value > you.getRole().value || i.getRole().equals(Role.LEADER)) { + return true; + } + + if (you.getRole().equals(Role.LEADER)) { + i.sendMessage(p.txt.parse("Only the faction admin can do that.")); + + } else if ((you.getRole().equals(Role.COLEADER))) { + if (i == you) { + return true; + } else { + i.sendMessage(p.txt.parse("Coleaders can't control each other...")); + } + + } else if (i.getRole().equals(Role.MODERATOR)) { + if (i == you) { + return true; //Moderators can control themselves + } else { + i.sendMessage(p.txt.parse("Moderators can't control each other...")); + } + } else { + i.sendMessage(p.txt.parse("You must be a faction moderator to do that.")); + } + + return false; + } + + // if economy is enabled and they're not on the bypass list, make 'em pay; returns true unless person can't afford the cost + public boolean payForCommand(double cost, String toDoThis, String forDoingThis) { + if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) { + return true; + } + + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { + return Econ.modifyMoney(myFaction, -cost, toDoThis, forDoingThis); + } else { + return Econ.modifyMoney(fme, -cost, toDoThis, forDoingThis); + } + } + + public boolean payForCommand(double cost, TL toDoThis, TL forDoingThis) { + return payForCommand(cost, toDoThis.toString(), forDoingThis.toString()); + } + + // like above, but just make sure they can pay; returns true unless person can't afford the cost + public boolean canAffordCommand(double cost, String toDoThis) { + if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) { + return true; + } + + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { + return Econ.hasAtLeast(myFaction, cost, toDoThis); + } else { + return Econ.hasAtLeast(fme, cost, toDoThis); + } + } + + public void doWarmUp(WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { + this.doWarmUp(this.fme, warmup, translationKey, action, runnable, delay); + } + + public void doWarmUp(FPlayer player, WarmUpUtil.Warmup warmup, TL translationKey, String action, Runnable runnable, long delay) { + WarmUpUtil.process(player, warmup, translationKey, action, runnable, delay); + } } diff --git a/src/main/java/com/massivecraft/factions/cmd/FPromoteCommand.java b/src/main/java/com/massivecraft/factions/cmd/FPromoteCommand.java index d36779ed..94366584 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FPromoteCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FPromoteCommand.java @@ -9,86 +9,86 @@ import com.massivecraft.factions.zcore.util.TL; public class FPromoteCommand extends FCommand { - public int relative = 0; + public int relative = 0; - public FPromoteCommand() { - super(); + public FPromoteCommand() { + super(); - this.requiredArgs.add("player"); + this.requiredArgs.add("player"); - this.permission = Permission.PROMOTE.node; - this.disableOnLock = true; + this.permission = Permission.PROMOTE.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = true; - senderMustBeModerator = false; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = true; + senderMustBeModerator = false; + senderMustBeAdmin = false; + } - @Override - public void perform() { - FPlayer target = this.argAsBestFPlayerMatch(0); - if (target == null) { - msg(TL.GENERIC_NOPLAYERFOUND, this.argAsString(0)); - return; - } + @Override + public void perform() { + FPlayer target = this.argAsBestFPlayerMatch(0); + if (target == null) { + msg(TL.GENERIC_NOPLAYERFOUND, this.argAsString(0)); + return; + } - if (!target.getFaction().equals(myFaction)) { - msg(TL.COMMAND_PROMOTE_WRONGFACTION, target.getName()); - return; - } + if (!target.getFaction().equals(myFaction)) { + msg(TL.COMMAND_PROMOTE_WRONGFACTION, target.getName()); + return; + } - Role current = target.getRole(); - Role promotion = Role.getRelative(current, +relative); + Role current = target.getRole(); + Role promotion = Role.getRelative(current, +relative); - // Now it ain't that messy - if (!fme.isAdminBypassing()) { - Access access = myFaction.getAccess(fme, PermissableAction.PROMOTE); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_NOPERMISSION, "manage ranks"); - return; - } - if (target == fme) { - fme.msg(TL.COMMAND_PROMOTE_NOTSELF); - return; - } - // Don't allow people to manage role of their same rank - if (fme.getRole() == current) { - fme.msg(TL.COMMAND_PROMOTE_NOT_SAME); - return; - } - // Don't allow people to promote people to their same or higher rank. - if (fme.getRole().value <= promotion.value) { - fme.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); - return; - } - } + // Now it ain't that messy + if (!fme.isAdminBypassing()) { + Access access = myFaction.getAccess(fme, PermissableAction.PROMOTE); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_NOPERMISSION, "manage ranks"); + return; + } + if (target == fme) { + fme.msg(TL.COMMAND_PROMOTE_NOTSELF); + return; + } + // Don't allow people to manage role of their same rank + if (fme.getRole() == current) { + fme.msg(TL.COMMAND_PROMOTE_NOT_SAME); + return; + } + // Don't allow people to promote people to their same or higher rank. + if (fme.getRole().value <= promotion.value) { + fme.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); + return; + } + } - if (promotion == null) { - fme.msg(TL.COMMAND_PROMOTE_NOTTHATPLAYER); - return; - } + if (promotion == null) { + fme.msg(TL.COMMAND_PROMOTE_NOTTHATPLAYER); + return; + } - // Don't allow people to promote people to their same or higher rnak. - if (fme.getRole().value <= promotion.value) { - fme.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); - return; - } + // Don't allow people to promote people to their same or higher rnak. + if (fme.getRole().value <= promotion.value) { + fme.msg(TL.COMMAND_PROMOTE_NOT_ALLOWED); + return; + } - String action = relative > 0 ? TL.COMMAND_PROMOTE_PROMOTED.toString() : TL.COMMAND_PROMOTE_DEMOTED.toString(); + String action = relative > 0 ? TL.COMMAND_PROMOTE_PROMOTED.toString() : TL.COMMAND_PROMOTE_DEMOTED.toString(); - // Success! - target.setRole(promotion); - if (target.isOnline()) { - target.msg(TL.COMMAND_PROMOTE_TARGET, action, promotion.nicename); - } + // Success! + target.setRole(promotion); + if (target.isOnline()) { + target.msg(TL.COMMAND_PROMOTE_TARGET, action, promotion.nicename); + } - fme.msg(TL.COMMAND_PROMOTE_SUCCESS, action, target.getName(), promotion.nicename); - } + fme.msg(TL.COMMAND_PROMOTE_SUCCESS, action, target.getName(), promotion.nicename); + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_PROMOTE_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_PROMOTE_DESCRIPTION; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java b/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java index 9efbff03..07172c9f 100644 --- a/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java +++ b/src/main/java/com/massivecraft/factions/cmd/FRelationCommand.java @@ -14,113 +14,113 @@ import org.bukkit.ChatColor; public abstract class FRelationCommand extends FCommand { - public Relation targetRelation; + public Relation targetRelation; - public FRelationCommand() { - super(); - this.requiredArgs.add("faction tag"); - //this.optionalArgs.put("player name", "you"); + public FRelationCommand() { + super(); + this.requiredArgs.add("faction tag"); + //this.optionalArgs.put("player name", "you"); - this.permission = Permission.RELATION.node; - this.disableOnLock = true; + this.permission = Permission.RELATION.node; + this.disableOnLock = true; - senderMustBePlayer = true; - senderMustBeMember = false; - senderMustBeModerator = true; - senderMustBeAdmin = false; - } + senderMustBePlayer = true; + senderMustBeMember = false; + senderMustBeModerator = true; + senderMustBeAdmin = false; + } - @Override - public void perform() { - Faction them = this.argAsFaction(0); - if (them == null) { - return; - } + @Override + public void perform() { + Faction them = this.argAsFaction(0); + if (them == null) { + return; + } - if (!them.isNormal()) { - msg(TL.COMMAND_RELATIONS_ALLTHENOPE); - return; - } + if (!them.isNormal()) { + msg(TL.COMMAND_RELATIONS_ALLTHENOPE); + return; + } - if (them == myFaction) { - msg(TL.COMMAND_RELATIONS_MORENOPE); - return; - } + if (them == myFaction) { + msg(TL.COMMAND_RELATIONS_MORENOPE); + return; + } - if (myFaction.getRelationWish(them) == targetRelation) { - msg(TL.COMMAND_RELATIONS_ALREADYINRELATIONSHIP, them.getTag()); - return; - } + if (myFaction.getRelationWish(them) == targetRelation) { + msg(TL.COMMAND_RELATIONS_ALREADYINRELATIONSHIP, them.getTag()); + return; + } - if (hasMaxRelations(them, targetRelation)) { - // We message them down there with the count. - return; - } - Relation oldRelation = myFaction.getRelationTo(them, true); - FactionRelationWishEvent wishEvent = new FactionRelationWishEvent(fme, myFaction, them, oldRelation, targetRelation); - Bukkit.getPluginManager().callEvent(wishEvent); - if (wishEvent.isCancelled()) { - return; - } + if (hasMaxRelations(them, targetRelation)) { + // We message them down there with the count. + return; + } + Relation oldRelation = myFaction.getRelationTo(them, true); + FactionRelationWishEvent wishEvent = new FactionRelationWishEvent(fme, myFaction, them, oldRelation, targetRelation); + Bukkit.getPluginManager().callEvent(wishEvent); + if (wishEvent.isCancelled()) { + return; + } - // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay - if (!payForCommand(targetRelation.getRelationCost(), TL.COMMAND_RELATIONS_TOMARRY, TL.COMMAND_RELATIONS_FORMARRY)) { - return; - } + // if economy is enabled, they're not on the bypass list, and this command has a cost set, make 'em pay + if (!payForCommand(targetRelation.getRelationCost(), TL.COMMAND_RELATIONS_TOMARRY, TL.COMMAND_RELATIONS_FORMARRY)) { + return; + } - // try to set the new relation - myFaction.setRelationWish(them, targetRelation); - Relation currentRelation = myFaction.getRelationTo(them, true); - ChatColor currentRelationColor = currentRelation.getColor(); + // try to set the new relation + myFaction.setRelationWish(them, targetRelation); + Relation currentRelation = myFaction.getRelationTo(them, true); + ChatColor currentRelationColor = currentRelation.getColor(); - // if the relation change was successful - if (targetRelation.value == currentRelation.value) { - // trigger the faction relation event - FactionRelationEvent relationEvent = new FactionRelationEvent(myFaction, them, oldRelation, currentRelation); - Bukkit.getServer().getPluginManager().callEvent(relationEvent); + // if the relation change was successful + if (targetRelation.value == currentRelation.value) { + // trigger the faction relation event + FactionRelationEvent relationEvent = new FactionRelationEvent(myFaction, them, oldRelation, currentRelation); + Bukkit.getServer().getPluginManager().callEvent(relationEvent); - them.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + myFaction.getTag()); - myFaction.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + them.getTag()); - } else { - // inform the other faction of your request - them.msg(TL.COMMAND_RELATIONS_PROPOSAL_1, currentRelationColor + myFaction.getTag(), targetRelation.getColor() + targetRelation.getTranslation()); - them.msg(TL.COMMAND_RELATIONS_PROPOSAL_2, Conf.baseCommandAliases.get(0), targetRelation, myFaction.getTag()); - myFaction.msg(TL.COMMAND_RELATIONS_PROPOSAL_SENT, currentRelationColor + them.getTag(), "" + targetRelation.getColor() + targetRelation); - } + them.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + myFaction.getTag()); + myFaction.msg(TL.COMMAND_RELATIONS_MUTUAL, currentRelationColor + targetRelation.getTranslation(), currentRelationColor + them.getTag()); + } else { + // inform the other faction of your request + them.msg(TL.COMMAND_RELATIONS_PROPOSAL_1, currentRelationColor + myFaction.getTag(), targetRelation.getColor() + targetRelation.getTranslation()); + them.msg(TL.COMMAND_RELATIONS_PROPOSAL_2, Conf.baseCommandAliases.get(0), targetRelation, myFaction.getTag()); + myFaction.msg(TL.COMMAND_RELATIONS_PROPOSAL_SENT, currentRelationColor + them.getTag(), "" + targetRelation.getColor() + targetRelation); + } - if (!targetRelation.isNeutral() && them.isPeaceful()) { - them.msg(TL.COMMAND_RELATIONS_PEACEFUL); - myFaction.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); - } + if (!targetRelation.isNeutral() && them.isPeaceful()) { + them.msg(TL.COMMAND_RELATIONS_PEACEFUL); + myFaction.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); + } - if (!targetRelation.isNeutral() && myFaction.isPeaceful()) { - them.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); - myFaction.msg(TL.COMMAND_RELATIONS_PEACEFUL); - } + if (!targetRelation.isNeutral() && myFaction.isPeaceful()) { + them.msg(TL.COMMAND_RELATIONS_PEACEFULOTHER); + myFaction.msg(TL.COMMAND_RELATIONS_PEACEFUL); + } - FTeamWrapper.updatePrefixes(myFaction); - FTeamWrapper.updatePrefixes(them); - } + FTeamWrapper.updatePrefixes(myFaction); + FTeamWrapper.updatePrefixes(them); + } - private boolean hasMaxRelations(Faction them, Relation targetRelation) { - int max = SavageFactions.plugin.getConfig().getInt("max-relations." + targetRelation.toString(), -1); - if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", false)) { - if (max != -1) { - if (myFaction.getRelationCount(targetRelation) >= max) { - msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation()); - return true; - } - if (them.getRelationCount(targetRelation) >= max) { - msg(TL.COMMAND_RELATIONS_EXCEEDS_THEY, max, targetRelation.getPluralTranslation()); - return true; - } - } - } - return false; - } + private boolean hasMaxRelations(Faction them, Relation targetRelation) { + int max = SavageFactions.plugin.getConfig().getInt("max-relations." + targetRelation.toString(), -1); + if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", false)) { + if (max != -1) { + if (myFaction.getRelationCount(targetRelation) >= max) { + msg(TL.COMMAND_RELATIONS_EXCEEDS_ME, max, targetRelation.getPluralTranslation()); + return true; + } + if (them.getRelationCount(targetRelation) >= max) { + msg(TL.COMMAND_RELATIONS_EXCEEDS_THEY, max, targetRelation.getPluralTranslation()); + return true; + } + } + } + return false; + } - @Override - public TL getUsageTranslation() { - return TL.COMMAND_RELATIONS_DESCRIPTION; - } + @Override + public TL getUsageTranslation() { + return TL.COMMAND_RELATIONS_DESCRIPTION; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerEnteredFactionEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerEnteredFactionEvent.java index d22632c1..9e9f8c67 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerEnteredFactionEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerEnteredFactionEvent.java @@ -6,37 +6,37 @@ import org.bukkit.event.HandlerList; public class FPlayerEnteredFactionEvent extends FactionPlayerEvent { - private static final HandlerList handlers = new HandlerList(); - private FPlayer fPlayer; - private Faction factionTo; - private Faction factionFrom; + private static final HandlerList handlers = new HandlerList(); + private FPlayer fPlayer; + private Faction factionTo; + private Faction factionFrom; - public FPlayerEnteredFactionEvent(Faction factionTo, Faction factionFrom, FPlayer fPlayer) { - super(fPlayer.getFaction(), fPlayer); - this.factionFrom = factionFrom; - this.factionTo = factionTo; - this.fPlayer = fPlayer; - } + public FPlayerEnteredFactionEvent(Faction factionTo, Faction factionFrom, FPlayer fPlayer) { + super(fPlayer.getFaction(), fPlayer); + this.factionFrom = factionFrom; + this.factionTo = factionTo; + this.fPlayer = fPlayer; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public HandlerList getHandlers() { - return handlers; - } + public HandlerList getHandlers() { + return handlers; + } - @Override - public FPlayer getfPlayer() { - return fPlayer; - } + @Override + public FPlayer getfPlayer() { + return fPlayer; + } - public Faction getFactionTo() { - return factionTo; - } + public Faction getFactionTo() { + return factionTo; + } - public Faction getFactionFrom() { - return factionFrom; - } + public Faction getFactionFrom() { + return factionFrom; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java index fd9617da..1755bdff 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerJoinEvent.java @@ -9,34 +9,34 @@ import org.bukkit.event.Cancellable; */ public class FPlayerJoinEvent extends FactionPlayerEvent implements Cancellable { - PlayerJoinReason reason; - boolean cancelled = false; + PlayerJoinReason reason; + boolean cancelled = false; - public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) { - super(f, fp); - reason = r; - } + public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) { + super(f, fp); + reason = r; + } - /** - * Get the reason the player joined the faction. - * - * @return reason player joined the faction. - */ - public PlayerJoinReason getReason() { - return reason; - } + /** + * Get the reason the player joined the faction. + * + * @return reason player joined the faction. + */ + public PlayerJoinReason getReason() { + return reason; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - cancelled = c; - } + @Override + public void setCancelled(boolean c) { + cancelled = c; + } - public enum PlayerJoinReason { - CREATE, LEADER, COMMAND - } + public enum PlayerJoinReason { + CREATE, LEADER, COMMAND + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java b/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java index e9b764d9..0ecb80d1 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerLeaveEvent.java @@ -6,35 +6,35 @@ import org.bukkit.event.Cancellable; public class FPlayerLeaveEvent extends FactionPlayerEvent implements Cancellable { - boolean cancelled = false; - private PlayerLeaveReason reason; + boolean cancelled = false; + private PlayerLeaveReason reason; - public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) { - super(f, p); - reason = r; - } + public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) { + super(f, p); + reason = r; + } - /** - * Get the reason the player left the faction. - * - * @return reason player left the faction. - */ - public PlayerLeaveReason getReason() { - return reason; - } + /** + * Get the reason the player left the faction. + * + * @return reason player left the faction. + */ + public PlayerLeaveReason getReason() { + return reason; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - // Don't let them cancel factions disbanding. - cancelled = reason != PlayerLeaveReason.DISBAND && reason != PlayerLeaveReason.RESET && c; - } + @Override + public void setCancelled(boolean c) { + // Don't let them cancel factions disbanding. + cancelled = reason != PlayerLeaveReason.DISBAND && reason != PlayerLeaveReason.RESET && c; + } - public enum PlayerLeaveReason { - KICKED, DISBAND, RESET, JOINOTHER, LEAVE, BANNED - } + public enum PlayerLeaveReason { + KICKED, DISBAND, RESET, JOINOTHER, LEAVE, BANNED + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FPlayerStoppedFlying.java b/src/main/java/com/massivecraft/factions/event/FPlayerStoppedFlying.java index f2f283c8..5a80a15a 100644 --- a/src/main/java/com/massivecraft/factions/event/FPlayerStoppedFlying.java +++ b/src/main/java/com/massivecraft/factions/event/FPlayerStoppedFlying.java @@ -4,25 +4,25 @@ import com.massivecraft.factions.FPlayer; import org.bukkit.event.HandlerList; public class FPlayerStoppedFlying extends FactionPlayerEvent { - private static final HandlerList handlers = new HandlerList(); - private FPlayer fPlayer; + private static final HandlerList handlers = new HandlerList(); + private FPlayer fPlayer; - public FPlayerStoppedFlying(FPlayer fPlayer) { - super(fPlayer.getFaction(), fPlayer); - this.fPlayer = fPlayer; - } + public FPlayerStoppedFlying(FPlayer fPlayer) { + super(fPlayer.getFaction(), fPlayer); + this.fPlayer = fPlayer; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - @Override - public FPlayer getfPlayer() { - return fPlayer; - } + @Override + public FPlayer getfPlayer() { + return fPlayer; + } - public HandlerList getHandlers() { - return handlers; - } + public HandlerList getHandlers() { + return handlers; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java b/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java index afdd1ab4..18791908 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionCreateEvent.java @@ -12,41 +12,41 @@ import org.bukkit.event.HandlerList; */ public class FactionCreateEvent extends Event implements Cancellable { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private String factionTag; - private Player sender; - private boolean cancelled; + private String factionTag; + private Player sender; + private boolean cancelled; - public FactionCreateEvent(Player sender, String tag) { - this.factionTag = tag; - this.sender = sender; - this.cancelled = false; - } + public FactionCreateEvent(Player sender, String tag) { + this.factionTag = tag; + this.sender = sender; + this.cancelled = false; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public FPlayer getFPlayer() { - return FPlayers.getInstance().getByPlayer(sender); - } + public FPlayer getFPlayer() { + return FPlayers.getInstance().getByPlayer(sender); + } - public String getFactionTag() { - return factionTag; - } + public String getFactionTag() { + return factionTag; + } - public HandlerList getHandlers() { - return handlers; - } + public HandlerList getHandlers() { + return handlers; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java b/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java index 1d810c27..0555fa2a 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionDisbandEvent.java @@ -11,42 +11,42 @@ import org.bukkit.event.Cancellable; */ public class FactionDisbandEvent extends FactionEvent implements Cancellable { - private final Player sender; - private final PlayerDisbandReason reason; - private boolean cancelled = false; + private final Player sender; + private final PlayerDisbandReason reason; + private boolean cancelled = false; - public FactionDisbandEvent(Player sender, String factionId, PlayerDisbandReason reason) { - super(Factions.getInstance().getFactionById(factionId)); - this.sender = sender; - this.reason = reason; - } + public FactionDisbandEvent(Player sender, String factionId, PlayerDisbandReason reason) { + super(Factions.getInstance().getFactionById(factionId)); + this.sender = sender; + this.reason = reason; + } - public FPlayer getFPlayer() { - return FPlayers.getInstance().getByPlayer(sender); - } + public FPlayer getFPlayer() { + return FPlayers.getInstance().getByPlayer(sender); + } - public Player getPlayer() { - return sender; - } + public Player getPlayer() { + return sender; + } - public PlayerDisbandReason getReason() { - return reason; - } + public PlayerDisbandReason getReason() { + return reason; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - cancelled = c; - } + @Override + public void setCancelled(boolean c) { + cancelled = c; + } - public enum PlayerDisbandReason { - COMMAND, - PLUGIN, - INACTIVITY, - LEAVE, - } + public enum PlayerDisbandReason { + COMMAND, + PLUGIN, + INACTIVITY, + LEAVE, + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionEvent.java b/src/main/java/com/massivecraft/factions/event/FactionEvent.java index 54595475..892f0ac0 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionEvent.java @@ -9,29 +9,29 @@ import org.bukkit.event.HandlerList; */ public class FactionEvent extends Event { - private static final HandlerList handlers = new HandlerList(); - private final Faction faction; + private static final HandlerList handlers = new HandlerList(); + private final Faction faction; - public FactionEvent(Faction faction) { - this.faction = faction; - } + public FactionEvent(Faction faction) { + this.faction = faction; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - /** - * Get the Faction involved in the event. - * - * @return faction involved in the event. - */ - public Faction getFaction() { - return this.faction; - } + /** + * Get the Faction involved in the event. + * + * @return faction involved in the event. + */ + public Faction getFaction() { + return this.faction; + } - @Override - public HandlerList getHandlers() { - return handlers; - } + @Override + public HandlerList getHandlers() { + return handlers; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java b/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java index ca0f86f4..3a76dcdd 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionPlayerEvent.java @@ -8,14 +8,14 @@ import com.massivecraft.factions.Faction; */ public class FactionPlayerEvent extends FactionEvent { - protected final FPlayer fPlayer; + protected final FPlayer fPlayer; - public FactionPlayerEvent(Faction faction, FPlayer fPlayer) { - super(faction); - this.fPlayer = fPlayer; - } + public FactionPlayerEvent(Faction faction, FPlayer fPlayer) { + super(faction); + this.fPlayer = fPlayer; + } - public FPlayer getfPlayer() { - return this.fPlayer; - } + public FPlayer getfPlayer() { + return this.fPlayer; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java index 93b6cab2..761fd1a4 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRelationEvent.java @@ -10,41 +10,41 @@ import org.bukkit.event.HandlerList; */ public class FactionRelationEvent extends Event { - private static final HandlerList handlers = new HandlerList(); + private static final HandlerList handlers = new HandlerList(); - private Faction fsender; - private Faction ftarget; - private Relation foldrel; - private Relation frel; + private Faction fsender; + private Faction ftarget; + private Relation foldrel; + private Relation frel; - public FactionRelationEvent(Faction sender, Faction target, Relation oldrel, Relation rel) { - fsender = sender; - ftarget = target; - foldrel = oldrel; - frel = rel; - } + public FactionRelationEvent(Faction sender, Faction target, Relation oldrel, Relation rel) { + fsender = sender; + ftarget = target; + foldrel = oldrel; + frel = rel; + } - public static HandlerList getHandlerList() { - return handlers; - } + public static HandlerList getHandlerList() { + return handlers; + } - public HandlerList getHandlers() { - return handlers; - } + public HandlerList getHandlers() { + return handlers; + } - public Relation getOldRelation() { - return foldrel; - } + public Relation getOldRelation() { + return foldrel; + } - public Relation getRelation() { - return frel; - } + public Relation getRelation() { + return frel; + } - public Faction getFaction() { - return fsender; - } + public Faction getFaction() { + return fsender; + } - public Faction getTargetFaction() { - return ftarget; - } + public Faction getTargetFaction() { + return ftarget; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java index 8590f7b4..dfdc6ef6 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRelationWishEvent.java @@ -6,39 +6,39 @@ import com.massivecraft.factions.struct.Relation; import org.bukkit.event.Cancellable; public class FactionRelationWishEvent extends FactionPlayerEvent implements Cancellable { - private final Faction targetFaction; - private final Relation currentRelation; - private final Relation targetRelation; + private final Faction targetFaction; + private final Relation currentRelation; + private final Relation targetRelation; - private boolean cancelled; + private boolean cancelled; - public FactionRelationWishEvent(FPlayer caller, Faction sender, Faction targetFaction, Relation currentRelation, Relation targetRelation) { - super(sender, caller); + public FactionRelationWishEvent(FPlayer caller, Faction sender, Faction targetFaction, Relation currentRelation, Relation targetRelation) { + super(sender, caller); - this.targetFaction = targetFaction; - this.currentRelation = currentRelation; - this.targetRelation = targetRelation; - } + this.targetFaction = targetFaction; + this.currentRelation = currentRelation; + this.targetRelation = targetRelation; + } - public Faction getTargetFaction() { - return targetFaction; - } + public Faction getTargetFaction() { + return targetFaction; + } - public Relation getCurrentRelation() { - return currentRelation; - } + public Relation getCurrentRelation() { + return currentRelation; + } - public Relation getTargetRelation() { - return targetRelation; - } + public Relation getTargetRelation() { + return targetRelation; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } } diff --git a/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java b/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java index 8dc8f022..cedeec77 100644 --- a/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java +++ b/src/main/java/com/massivecraft/factions/event/FactionRenameEvent.java @@ -6,52 +6,52 @@ import org.bukkit.event.Cancellable; public class FactionRenameEvent extends FactionPlayerEvent implements Cancellable { - private boolean cancelled = false; - private String tag; + private boolean cancelled = false; + private String tag; - public FactionRenameEvent(FPlayer sender, String newTag) { - super(sender.getFaction(), sender); - tag = newTag; - } + public FactionRenameEvent(FPlayer sender, String newTag) { + super(sender.getFaction(), sender); + tag = newTag; + } - /** - * Get the player involved in the event. - * - * @return Player involved in the event. - * @deprecated use getfPlayer().getPlayer() instead. - */ - @Deprecated - public Player getPlayer() { - return getfPlayer().getPlayer(); - } + /** + * Get the player involved in the event. + * + * @return Player involved in the event. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } - /** - * Get the faction tag before it was renamed. - * - * @return old faction tag. - * @deprecated use getFaction().getTag() instead. - */ - @Deprecated - public String getOldFactionTag() { - return getFaction().getTag(); - } + /** + * Get the faction tag before it was renamed. + * + * @return old faction tag. + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getOldFactionTag() { + return getFaction().getTag(); + } - /** - * Get the new faction tag. - * - * @return new faction tag as String. - */ - public String getFactionTag() { - return tag; - } + /** + * Get the new faction tag. + * + * @return new faction tag as String. + */ + public String getFactionTag() { + return tag; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java b/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java index 8bef95f0..223d6852 100644 --- a/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandClaimEvent.java @@ -11,64 +11,64 @@ import org.bukkit.event.Cancellable; */ public class LandClaimEvent extends FactionPlayerEvent implements Cancellable { - private boolean cancelled; - private FLocation location; + private boolean cancelled; + private FLocation location; - public LandClaimEvent(FLocation loc, Faction f, FPlayer p) { - super(f, p); - cancelled = false; - location = loc; - } + public LandClaimEvent(FLocation loc, Faction f, FPlayer p) { + super(f, p); + cancelled = false; + location = loc; + } - /** - * Get the FLocation involved in this event. - * - * @return the FLocation (also a chunk) involved in this event. - */ - public FLocation getLocation() { - return this.location; - } + /** + * Get the FLocation involved in this event. + * + * @return the FLocation (also a chunk) involved in this event. + */ + public FLocation getLocation() { + return this.location; + } - /** - * Get the id of the faction. - * - * @return id of faction as String - * @deprecated use getFaction().getId() instead. - */ - @Deprecated - public String getFactionId() { - return getFaction().getId(); - } + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } - /** - * Get the tag of the faction. - * - * @return tag of faction as String - * @deprecated use getFaction().getTag() instead. - */ - @Deprecated - public String getFactionTag() { - return getFaction().getTag(); - } + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } - /** - * Get the Player involved in this event. - * - * @return player from FPlayer. - * @deprecated use getfPlayer().getPlayer() instead. - */ - @Deprecated - public Player getPlayer() { - return getfPlayer().getPlayer(); - } + /** + * Get the Player involved in this event. + * + * @return player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java b/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java index 5b807bfd..47dfa00f 100644 --- a/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandUnclaimAllEvent.java @@ -6,52 +6,52 @@ import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; public class LandUnclaimAllEvent extends FactionPlayerEvent implements Cancellable { - private boolean cancelled; + private boolean cancelled; - public LandUnclaimAllEvent(Faction f, FPlayer p) { - super(f, p); - } + public LandUnclaimAllEvent(Faction f, FPlayer p) { + super(f, p); + } - /** - * Get the id of the faction. - * - * @return id of faction as String - * @deprecated use getFaction().getId() instead. - */ - @Deprecated - public String getFactionId() { - return getFaction().getId(); - } + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } - /** - * Get the tag of the faction. - * - * @return tag of faction as String - * @deprecated use getFaction().getTag() instead. - */ - @Deprecated - public String getFactionTag() { - return getFaction().getTag(); - } + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } - /** - * Get the Player involved in the event. - * - * @return Player from FPlayer. - * @deprecated use getfPlayer().getPlayer() instead. - */ - @Deprecated - public Player getPlayer() { - return getfPlayer().getPlayer(); - } + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } } diff --git a/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java b/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java index 402f50e3..72ae23c3 100644 --- a/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java +++ b/src/main/java/com/massivecraft/factions/event/LandUnclaimEvent.java @@ -11,59 +11,59 @@ import org.bukkit.event.Cancellable; */ public class LandUnclaimEvent extends FactionPlayerEvent implements Cancellable { - private boolean cancelled; - private FLocation location; + private boolean cancelled; + private FLocation location; - public LandUnclaimEvent(FLocation loc, Faction f, FPlayer p) { - super(f, p); - cancelled = false; - location = loc; - } + public LandUnclaimEvent(FLocation loc, Faction f, FPlayer p) { + super(f, p); + cancelled = false; + location = loc; + } - public FLocation getLocation() { - return this.location; - } + public FLocation getLocation() { + return this.location; + } - /** - * Get the id of the faction. - * - * @return id of faction as String - * @deprecated use getFaction().getId() instead. - */ - @Deprecated - public String getFactionId() { - return getFaction().getId(); - } + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } - /** - * Get the tag of the faction. - * - * @return tag of faction as String - * @deprecated use getFaction().getTag() instead. - */ - @Deprecated - public String getFactionTag() { - return getFaction().getTag(); - } + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } - /** - * Get the Player involved in the event. - * - * @return Player from FPlayer. - * @deprecated use getfPlayer().getPlayer() instead. - */ - @Deprecated - public Player getPlayer() { - return getfPlayer().getPlayer(); - } + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - cancelled = c; - } + @Override + public void setCancelled(boolean c) { + cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java b/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java index 45a5b19b..6304e39c 100644 --- a/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java +++ b/src/main/java/com/massivecraft/factions/event/PowerLossEvent.java @@ -10,72 +10,72 @@ import org.bukkit.event.Cancellable; */ public class PowerLossEvent extends FactionPlayerEvent implements Cancellable { - private boolean cancelled = false; - private String message; + private boolean cancelled = false; + private String message; - public PowerLossEvent(Faction f, FPlayer p) { - super(f, p); - } + public PowerLossEvent(Faction f, FPlayer p) { + super(f, p); + } - /** - * Get the id of the faction. - * - * @return id of faction as String - * @deprecated use getFaction().getId() instead. - */ - @Deprecated - public String getFactionId() { - return getFaction().getId(); - } + /** + * Get the id of the faction. + * + * @return id of faction as String + * @deprecated use getFaction().getId() instead. + */ + @Deprecated + public String getFactionId() { + return getFaction().getId(); + } - /** - * Get the tag of the faction. - * - * @return tag of faction as String - * @deprecated use getFaction().getTag() instead. - */ - @Deprecated - public String getFactionTag() { - return getFaction().getTag(); - } + /** + * Get the tag of the faction. + * + * @return tag of faction as String + * @deprecated use getFaction().getTag() instead. + */ + @Deprecated + public String getFactionTag() { + return getFaction().getTag(); + } - /** - * Get the Player involved in the event. - * - * @return Player from FPlayer. - * @deprecated use getfPlayer().getPlayer() instead. - */ - @Deprecated - public Player getPlayer() { - return getfPlayer().getPlayer(); - } + /** + * Get the Player involved in the event. + * + * @return Player from FPlayer. + * @deprecated use getfPlayer().getPlayer() instead. + */ + @Deprecated + public Player getPlayer() { + return getfPlayer().getPlayer(); + } - /** - * Get the power loss message. - * - * @return power loss message as String. - */ - public String getMessage() { - return message; - } + /** + * Get the power loss message. + * + * @return power loss message as String. + */ + public String getMessage() { + return message; + } - /** - * Set the power loss message. - * - * @param message of powerloss - */ - public void setMessage(String message) { - this.message = message; - } + /** + * Set the power loss message. + * + * @param message of powerloss + */ + public void setMessage(String message) { + this.message = message; + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/event/PowerRegenEvent.java b/src/main/java/com/massivecraft/factions/event/PowerRegenEvent.java index b9a7ec2c..e1782b8d 100644 --- a/src/main/java/com/massivecraft/factions/event/PowerRegenEvent.java +++ b/src/main/java/com/massivecraft/factions/event/PowerRegenEvent.java @@ -9,20 +9,20 @@ import org.bukkit.event.Cancellable; */ public class PowerRegenEvent extends FactionPlayerEvent implements Cancellable { - private boolean cancelled = false; + private boolean cancelled = false; - public PowerRegenEvent(Faction f, FPlayer p) { - super(f, p); - } + public PowerRegenEvent(Faction f, FPlayer p) { + super(f, p); + } - @Override - public boolean isCancelled() { - return cancelled; - } + @Override + public boolean isCancelled() { + return cancelled; + } - @Override - public void setCancelled(boolean c) { - this.cancelled = c; - } + @Override + public void setCancelled(boolean c) { + this.cancelled = c; + } } diff --git a/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java b/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java index 9ceeb827..2d8f4624 100644 --- a/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java +++ b/src/main/java/com/massivecraft/factions/iface/EconomyParticipator.java @@ -4,9 +4,9 @@ import com.massivecraft.factions.zcore.util.TL; public interface EconomyParticipator extends RelationParticipator { - String getAccountId(); + String getAccountId(); - void msg(String str, Object... args); + void msg(String str, Object... args); - void msg(TL translation, Object... args); + void msg(TL translation, Object... args); } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java b/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java index a536c43b..781bed18 100644 --- a/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java +++ b/src/main/java/com/massivecraft/factions/iface/RelationParticipator.java @@ -5,13 +5,13 @@ import org.bukkit.ChatColor; public interface RelationParticipator { - String describeTo(RelationParticipator that); + String describeTo(RelationParticipator that); - String describeTo(RelationParticipator that, boolean ucfirst); + String describeTo(RelationParticipator that, boolean ucfirst); - Relation getRelationTo(RelationParticipator that); + Relation getRelationTo(RelationParticipator that); - Relation getRelationTo(RelationParticipator that, boolean ignorePeaceful); + Relation getRelationTo(RelationParticipator that, boolean ignorePeaceful); - ChatColor getColorTo(RelationParticipator to); + ChatColor getColorTo(RelationParticipator to); } diff --git a/src/main/java/com/massivecraft/factions/integration/Econ.java b/src/main/java/com/massivecraft/factions/integration/Econ.java index 064a150c..650a6b02 100644 --- a/src/main/java/com/massivecraft/factions/integration/Econ.java +++ b/src/main/java/com/massivecraft/factions/integration/Econ.java @@ -23,418 +23,418 @@ import java.util.logging.Level; public class Econ { - private static final DecimalFormat format = new DecimalFormat(TL.ECON_FORMAT.toString()); - private static Economy econ = null; + private static final DecimalFormat format = new DecimalFormat(TL.ECON_FORMAT.toString()); + private static Economy econ = null; - public static void setup() { - if (isSetup()) { - return; - } + public static void setup() { + if (isSetup()) { + return; + } - String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" "; + String integrationFail = "Economy integration is " + (Conf.econEnabled ? "enabled, but" : "disabled, and") + " the plugin \"Vault\" "; - if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { - SavageFactions.plugin.log(integrationFail + "is not installed."); - return; - } + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + SavageFactions.plugin.log(integrationFail + "is not installed."); + return; + } - RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); - if (rsp == null) { - SavageFactions.plugin.log(integrationFail + "is not hooked into an economy plugin."); - return; - } - econ = rsp.getProvider(); + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + SavageFactions.plugin.log(integrationFail + "is not hooked into an economy plugin."); + return; + } + econ = rsp.getProvider(); - SavageFactions.plugin.log("Economy integration through Vault plugin successful."); + SavageFactions.plugin.log("Economy integration through Vault plugin successful."); - if (!Conf.econEnabled) { - SavageFactions.plugin.log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); - } + if (!Conf.econEnabled) { + SavageFactions.plugin.log("NOTE: Economy is disabled. You can enable it with the command: f config econEnabled true"); + } - SavageFactions.plugin.cmdBase.cmdHelp.updateHelp(); - } + SavageFactions.plugin.cmdBase.cmdHelp.updateHelp(); + } - public static boolean shouldBeUsed() { - return Conf.econEnabled && econ != null && econ.isEnabled(); - } + public static boolean shouldBeUsed() { + return Conf.econEnabled && econ != null && econ.isEnabled(); + } - public static boolean isSetup() { - return econ != null; - } + public static boolean isSetup() { + return econ != null; + } - public static void modifyUniverseMoney(double delta) { - if (!shouldBeUsed()) { - return; - } + public static void modifyUniverseMoney(double delta) { + if (!shouldBeUsed()) { + return; + } - if (Conf.econUniverseAccount == null) { - return; - } - if (Conf.econUniverseAccount.length() == 0) { - return; - } - if (!econ.hasAccount(Conf.econUniverseAccount)) { - return; - } + if (Conf.econUniverseAccount == null) { + return; + } + if (Conf.econUniverseAccount.length() == 0) { + return; + } + if (!econ.hasAccount(Conf.econUniverseAccount)) { + return; + } - modifyBalance(Conf.econUniverseAccount, delta); - } + modifyBalance(Conf.econUniverseAccount, delta); + } - public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) { - if (!shouldBeUsed()) { - SavageFactions.plugin.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); - return; - } - to.msg("%s's balance is %s.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId()))); - } + public static void sendBalanceInfo(FPlayer to, EconomyParticipator about) { + if (!shouldBeUsed()) { + SavageFactions.plugin.log(Level.WARNING, "Vault does not appear to be hooked into an economy plugin."); + return; + } + to.msg("%s's balance is %s.", about.describeTo(to, true), Econ.moneyString(econ.getBalance(about.getAccountId()))); + } - public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you) { - Faction fI = RelationUtil.getFaction(i); - Faction fYou = RelationUtil.getFaction(you); + public static boolean canIControllYou(EconomyParticipator i, EconomyParticipator you) { + Faction fI = RelationUtil.getFaction(i); + Faction fYou = RelationUtil.getFaction(you); - // This is a system invoker. Accept it. - if (fI == null) { - return true; - } + // This is a system invoker. Accept it. + if (fI == null) { + return true; + } - // Bypassing players can do any kind of transaction - if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) { - return true; - } + // Bypassing players can do any kind of transaction + if (i instanceof FPlayer && ((FPlayer) i).isAdminBypassing()) { + return true; + } - // Players with the any withdraw can do. - if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) { - return true; - } + // Players with the any withdraw can do. + if (i instanceof FPlayer && Permission.MONEY_WITHDRAW_ANY.has(((FPlayer) i).getPlayer())) { + return true; + } - // You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again. - if (i == you) { - return true; - } + // You can deposit to anywhere you feel like. It's your loss if you can't withdraw it again. + if (i == you) { + return true; + } - // A faction can always transfer away the money of it's members and its own money... - // This will however probably never happen as a faction does not have free will. - // Ohh by the way... Yes it could. For daily rent to the faction. - if (i == fI && fI == fYou) { - return true; - } + // A faction can always transfer away the money of it's members and its own money... + // This will however probably never happen as a faction does not have free will. + // Ohh by the way... Yes it could. For daily rent to the faction. + if (i == fI && fI == fYou) { + return true; + } - // Factions can be controlled by members that are moderators... or any member if any member can withdraw. - if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer) i).getRole().value >= Role.MODERATOR.value)) { - return true; - } + // Factions can be controlled by members that are moderators... or any member if any member can withdraw. + if (you instanceof Faction && fI == fYou && (Conf.bankMembersCanWithdraw || ((FPlayer) i).getRole().value >= Role.MODERATOR.value)) { + return true; + } - // Otherwise you may not!;,,; - i.msg("%s lacks permission to control %s's money.", i.describeTo(i, true), you.describeTo(i)); - return false; - } + // Otherwise you may not!;,,; + i.msg("%s lacks permission to control %s's money.", i.describeTo(i, true), you.describeTo(i)); + return false; + } - public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { - return transferMoney(invoker, from, to, amount, true); - } + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { + return transferMoney(invoker, from, to, amount, true); + } - public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) { - if (!shouldBeUsed()) { - return false; - } + public static boolean transferMoney(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount, boolean notify) { + if (!shouldBeUsed()) { + return false; + } - // The amount must be positive. - // If the amount is negative we must flip and multiply amount with -1. - if (amount < 0) { - amount *= -1; - EconomyParticipator temp = from; - from = to; - to = temp; - } + // The amount must be positive. + // If the amount is negative we must flip and multiply amount with -1. + if (amount < 0) { + amount *= -1; + EconomyParticipator temp = from; + from = to; + to = temp; + } - // Check the rights - if (!canIControllYou(invoker, from)) { - return false; - } + // Check the rights + if (!canIControllYou(invoker, from)) { + return false; + } - OfflinePlayer fromAcc; - OfflinePlayer toAcc; + OfflinePlayer fromAcc; + OfflinePlayer toAcc; - if (isUUID(from.getAccountId())) { - fromAcc = Bukkit.getOfflinePlayer(UUID.fromString(from.getAccountId())); - if (fromAcc.getName() == null) { - return false; - } - } else { - fromAcc = Bukkit.getOfflinePlayer(from.getAccountId()); - } + if (isUUID(from.getAccountId())) { + fromAcc = Bukkit.getOfflinePlayer(UUID.fromString(from.getAccountId())); + if (fromAcc.getName() == null) { + return false; + } + } else { + fromAcc = Bukkit.getOfflinePlayer(from.getAccountId()); + } - if (isUUID(to.getAccountId())) { - toAcc = Bukkit.getOfflinePlayer(UUID.fromString(to.getAccountId())); - if (toAcc.getName() == null) { - return false; - } - } else { - toAcc = Bukkit.getOfflinePlayer(to.getAccountId()); - } + if (isUUID(to.getAccountId())) { + toAcc = Bukkit.getOfflinePlayer(UUID.fromString(to.getAccountId())); + if (toAcc.getName() == null) { + return false; + } + } else { + toAcc = Bukkit.getOfflinePlayer(to.getAccountId()); + } - // Is there enough money for the transaction to happen? - if (!econ.has(fromAcc, amount)) { - // There was not enough money to pay - if (invoker != null && notify) { - invoker.msg("%s can't afford to transfer %s to %s.", from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker)); - } + // Is there enough money for the transaction to happen? + if (!econ.has(fromAcc, amount)) { + // There was not enough money to pay + if (invoker != null && notify) { + invoker.msg("%s can't afford to transfer %s to %s.", from.describeTo(invoker, true), moneyString(amount), to.describeTo(invoker)); + } - return false; - } + return false; + } - // Transfer money - EconomyResponse erw = econ.withdrawPlayer(fromAcc, amount); + // Transfer money + EconomyResponse erw = econ.withdrawPlayer(fromAcc, amount); - if (erw.transactionSuccess()) { - EconomyResponse erd = econ.depositPlayer(toAcc, amount); - if (erd.transactionSuccess()) { - if (notify) { - sendTransferInfo(invoker, from, to, amount); - } - return true; - } else { - // transaction failed, refund account - econ.depositPlayer(fromAcc, amount); - } - } + if (erw.transactionSuccess()) { + EconomyResponse erd = econ.depositPlayer(toAcc, amount); + if (erd.transactionSuccess()) { + if (notify) { + sendTransferInfo(invoker, from, to, amount); + } + return true; + } else { + // transaction failed, refund account + econ.depositPlayer(fromAcc, amount); + } + } - // if we get here something with the transaction failed - if (notify) { - invoker.msg("Unable to transfer %s to %s from %s.", moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true)); - } + // if we get here something with the transaction failed + if (notify) { + invoker.msg("Unable to transfer %s to %s from %s.", moneyString(amount), to.describeTo(invoker), from.describeTo(invoker, true)); + } - return false; - } + return false; + } - public static Set getFplayers(EconomyParticipator ep) { - Set fplayers = new HashSet<>(); + public static Set getFplayers(EconomyParticipator ep) { + Set fplayers = new HashSet<>(); - if (ep != null) { - if (ep instanceof FPlayer) { - fplayers.add((FPlayer) ep); - } else if (ep instanceof Faction) { - fplayers.addAll(((Faction) ep).getFPlayers()); - } - } + if (ep != null) { + if (ep instanceof FPlayer) { + fplayers.add((FPlayer) ep); + } else if (ep instanceof Faction) { + fplayers.addAll(((Faction) ep).getFPlayers()); + } + } - return fplayers; - } + return fplayers; + } - public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { - Set recipients = new HashSet<>(); - recipients.addAll(getFplayers(invoker)); - recipients.addAll(getFplayers(from)); - recipients.addAll(getFplayers(to)); + public static void sendTransferInfo(EconomyParticipator invoker, EconomyParticipator from, EconomyParticipator to, double amount) { + Set recipients = new HashSet<>(); + recipients.addAll(getFplayers(invoker)); + recipients.addAll(getFplayers(from)); + recipients.addAll(getFplayers(to)); - if (invoker == null) { - for (FPlayer recipient : recipients) { - recipient.msg("%s was transferred from %s to %s.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); - } - } else if (invoker == from) { - for (FPlayer recipient : recipients) { - recipient.msg("%s gave %s to %s.", from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient)); - } - } else if (invoker == to) { - for (FPlayer recipient : recipients) { - recipient.msg("%s took %s from %s.", to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient)); - } - } else { - for (FPlayer recipient : recipients) { - recipient.msg("%s transferred %s from %s to %s.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); - } - } - } + if (invoker == null) { + for (FPlayer recipient : recipients) { + recipient.msg("%s was transferred from %s to %s.", moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); + } + } else if (invoker == from) { + for (FPlayer recipient : recipients) { + recipient.msg("%s gave %s to %s.", from.describeTo(recipient, true), moneyString(amount), to.describeTo(recipient)); + } + } else if (invoker == to) { + for (FPlayer recipient : recipients) { + recipient.msg("%s took %s from %s.", to.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient)); + } + } else { + for (FPlayer recipient : recipients) { + recipient.msg("%s transferred %s from %s to %s.", invoker.describeTo(recipient, true), moneyString(amount), from.describeTo(recipient), to.describeTo(recipient)); + } + } + } - public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) { - if (!shouldBeUsed()) { - return true; - } + public static boolean hasAtLeast(EconomyParticipator ep, double delta, String toDoThis) { + if (!shouldBeUsed()) { + return true; + } - // going the hard way round as econ.has refuses to work. - boolean affordable = false; - double currentBalance; + // going the hard way round as econ.has refuses to work. + boolean affordable = false; + double currentBalance; - if (isUUID(ep.getAccountId())) { - OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())); - if (offline.getName() != null) { - currentBalance = econ.getBalance(Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId()))); - } else { - currentBalance = 0; - } - } else { - currentBalance = econ.getBalance(ep.getAccountId()); - } + if (isUUID(ep.getAccountId())) { + OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())); + if (offline.getName() != null) { + currentBalance = econ.getBalance(Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId()))); + } else { + currentBalance = 0; + } + } else { + currentBalance = econ.getBalance(ep.getAccountId()); + } - if (currentBalance >= delta) { - affordable = true; - } + if (currentBalance >= delta) { + affordable = true; + } - if (!affordable) { - if (toDoThis != null && !toDoThis.isEmpty()) { - ep.msg("%s can't afford %s %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis); - } - return false; - } - return true; - } + if (!affordable) { + if (toDoThis != null && !toDoThis.isEmpty()) { + ep.msg("%s can't afford %s %s.", ep.describeTo(ep, true), moneyString(delta), toDoThis); + } + return false; + } + return true; + } - public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) { - if (!shouldBeUsed()) { - return false; - } + public static boolean modifyMoney(EconomyParticipator ep, double delta, String toDoThis, String forDoingThis) { + if (!shouldBeUsed()) { + return false; + } - OfflinePlayer acc; + OfflinePlayer acc; - if (isUUID(ep.getAccountId())) { - acc = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())); - if (acc.getName() == null) { - return false; - } - } else { - acc = Bukkit.getOfflinePlayer(ep.getAccountId()); - } + if (isUUID(ep.getAccountId())) { + acc = Bukkit.getOfflinePlayer(UUID.fromString(ep.getAccountId())); + if (acc.getName() == null) { + return false; + } + } else { + acc = Bukkit.getOfflinePlayer(ep.getAccountId()); + } - String You = ep.describeTo(ep, true); + String You = ep.describeTo(ep, true); - if (delta == 0) { - // no money actually transferred? + if (delta == 0) { + // no money actually transferred? // ep.msg("%s didn't have to pay anything %s.", You, forDoingThis); // might be for gains, might be for losses - return true; - } + return true; + } - if (delta > 0) { - // The player should gain money - // The account might not have enough space - EconomyResponse er = econ.depositPlayer(acc, delta); - if (er.transactionSuccess()) { - modifyUniverseMoney(-delta); - if (forDoingThis != null && !forDoingThis.isEmpty()) { - ep.msg("%s gained %s %s.", You, moneyString(delta), forDoingThis); - } - return true; - } else { - // transfer to account failed - if (forDoingThis != null && !forDoingThis.isEmpty()) { - ep.msg("%s would have gained %s %s, but the deposit failed.", You, moneyString(delta), forDoingThis); - } - return false; - } - } else { - // The player should loose money - // The player might not have enough. + if (delta > 0) { + // The player should gain money + // The account might not have enough space + EconomyResponse er = econ.depositPlayer(acc, delta); + if (er.transactionSuccess()) { + modifyUniverseMoney(-delta); + if (forDoingThis != null && !forDoingThis.isEmpty()) { + ep.msg("%s gained %s %s.", You, moneyString(delta), forDoingThis); + } + return true; + } else { + // transfer to account failed + if (forDoingThis != null && !forDoingThis.isEmpty()) { + ep.msg("%s would have gained %s %s, but the deposit failed.", You, moneyString(delta), forDoingThis); + } + return false; + } + } else { + // The player should loose money + // The player might not have enough. - if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) { - // There is enough money to pay - modifyUniverseMoney(-delta); - if (forDoingThis != null && !forDoingThis.isEmpty()) { - ep.msg("%s lost %s %s.", You, moneyString(-delta), forDoingThis); - } - return true; - } else { - // There was not enough money to pay - if (toDoThis != null && !toDoThis.isEmpty()) { - ep.msg("%s can't afford %s %s.", You, moneyString(-delta), toDoThis); - } - return false; - } - } - } + if (econ.has(acc, -delta) && econ.withdrawPlayer(acc, -delta).transactionSuccess()) { + // There is enough money to pay + modifyUniverseMoney(-delta); + if (forDoingThis != null && !forDoingThis.isEmpty()) { + ep.msg("%s lost %s %s.", You, moneyString(-delta), forDoingThis); + } + return true; + } else { + // There was not enough money to pay + if (toDoThis != null && !toDoThis.isEmpty()) { + ep.msg("%s can't afford %s %s.", You, moneyString(-delta), toDoThis); + } + return false; + } + } + } - public static String moneyString(double amount) { - return format.format(amount); - } + public static String moneyString(double amount) { + return format.format(amount); + } - // calculate the cost for claiming land - public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) { - if (!shouldBeUsed()) { - return 0d; - } + // calculate the cost for claiming land + public static double calculateClaimCost(int ownedLand, boolean takingFromAnotherFaction) { + if (!shouldBeUsed()) { + return 0d; + } - // basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction - return Conf.econCostClaimWilderness + (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand) - (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus : 0); - } + // basic claim cost, plus land inflation cost, minus the potential bonus given for claiming from another faction + return Conf.econCostClaimWilderness + (Conf.econCostClaimWilderness * Conf.econClaimAdditionalMultiplier * ownedLand) - (takingFromAnotherFaction ? Conf.econCostClaimFromFactionBonus : 0); + } - // calculate refund amount for unclaiming land - public static double calculateClaimRefund(int ownedLand) { - return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier; - } + // calculate refund amount for unclaiming land + public static double calculateClaimRefund(int ownedLand) { + return calculateClaimCost(ownedLand - 1, false) * Conf.econClaimRefundMultiplier; + } - // calculate value of all owned land - public static double calculateTotalLandValue(int ownedLand) { - double amount = 0; - for (int x = 0; x < ownedLand; x++) { - amount += calculateClaimCost(x, false); - } - return amount; - } + // calculate value of all owned land + public static double calculateTotalLandValue(int ownedLand) { + double amount = 0; + for (int x = 0; x < ownedLand; x++) { + amount += calculateClaimCost(x, false); + } + return amount; + } - // -------------------------------------------- // - // Standard account management methods - // -------------------------------------------- // + // -------------------------------------------- // + // Standard account management methods + // -------------------------------------------- // - // calculate refund amount for all owned land - public static double calculateTotalLandRefund(int ownedLand) { - return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier; - } + // calculate refund amount for all owned land + public static double calculateTotalLandRefund(int ownedLand) { + return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier; + } - public static boolean hasAccount(String name) { - return econ.hasAccount(name); - } + public static boolean hasAccount(String name) { + return econ.hasAccount(name); + } - public static double getBalance(String account) { - return econ.getBalance(account); - } + public static double getBalance(String account) { + return econ.getBalance(account); + } - public static String getFriendlyBalance(UUID uuid) { - OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid); - if (offline.getName() == null) { - return "0"; - } - return format.format(econ.getBalance(offline)); - } + public static String getFriendlyBalance(UUID uuid) { + OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid); + if (offline.getName() == null) { + return "0"; + } + return format.format(econ.getBalance(offline)); + } - public static String getFriendlyBalance(FPlayer player) { - return getFriendlyBalance(UUID.fromString(player.getId())); - } + public static String getFriendlyBalance(FPlayer player) { + return getFriendlyBalance(UUID.fromString(player.getId())); + } - public static boolean setBalance(String account, double amount) { - double current = econ.getBalance(account); - if (current > amount) { - return econ.withdrawPlayer(account, current - amount).transactionSuccess(); - } else { - return econ.depositPlayer(account, amount - current).transactionSuccess(); - } - } + public static boolean setBalance(String account, double amount) { + double current = econ.getBalance(account); + if (current > amount) { + return econ.withdrawPlayer(account, current - amount).transactionSuccess(); + } else { + return econ.depositPlayer(account, amount - current).transactionSuccess(); + } + } - public static boolean modifyBalance(String account, double amount) { - if (amount < 0) { - return econ.withdrawPlayer(account, -amount).transactionSuccess(); - } else { - return econ.depositPlayer(account, amount).transactionSuccess(); - } - } + public static boolean modifyBalance(String account, double amount) { + if (amount < 0) { + return econ.withdrawPlayer(account, -amount).transactionSuccess(); + } else { + return econ.depositPlayer(account, amount).transactionSuccess(); + } + } - public static boolean deposit(String account, double amount) { - return econ.depositPlayer(account, amount).transactionSuccess(); - } + public static boolean deposit(String account, double amount) { + return econ.depositPlayer(account, amount).transactionSuccess(); + } - public static boolean withdraw(String account, double amount) { - return econ.withdrawPlayer(account, amount).transactionSuccess(); - } + public static boolean withdraw(String account, double amount) { + return econ.withdrawPlayer(account, amount).transactionSuccess(); + } - // --------------------------------------- - // Helpful Utilities - // --------------------------------------- + // --------------------------------------- + // Helpful Utilities + // --------------------------------------- - public static boolean isUUID(String uuid) { - try { - UUID.fromString(uuid); - } catch (IllegalArgumentException ex) { - return false; - } + public static boolean isUUID(String uuid) { + try { + UUID.fromString(uuid); + } catch (IllegalArgumentException ex) { + return false; + } - return true; - } + return true; + } } diff --git a/src/main/java/com/massivecraft/factions/integration/Essentials.java b/src/main/java/com/massivecraft/factions/integration/Essentials.java index 8b0f8222..5025515b 100644 --- a/src/main/java/com/massivecraft/factions/integration/Essentials.java +++ b/src/main/java/com/massivecraft/factions/integration/Essentials.java @@ -15,32 +15,32 @@ import java.math.BigDecimal; public class Essentials { - private static IEssentials essentials; + private static IEssentials essentials; - public static void setup() { - Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); - if (ess != null) { - essentials = (IEssentials) ess; - } - } + public static void setup() { + Plugin ess = Bukkit.getPluginManager().getPlugin("Essentials"); + if (ess != null) { + essentials = (IEssentials) ess; + } + } - // return false if feature is disabled or Essentials isn't available - public static boolean handleTeleport(Player player, Location loc) { - if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) { - return false; - } + // return false if feature is disabled or Essentials isn't available + public static boolean handleTeleport(Player player, Location loc) { + if (!Conf.homesTeleportCommandEssentialsIntegration || essentials == null) { + return false; + } - Teleport teleport = essentials.getUser(player).getTeleport(); - Trade trade = new Trade(new BigDecimal(Conf.econCostHome), essentials); - try { - teleport.teleport(loc, trade, TeleportCause.PLUGIN); - } catch (Exception e) { - player.sendMessage(ChatColor.RED.toString() + e.getMessage()); - } - return true; - } + Teleport teleport = essentials.getUser(player).getTeleport(); + Trade trade = new Trade(new BigDecimal(Conf.econCostHome), essentials); + try { + teleport.teleport(loc, trade, TeleportCause.PLUGIN); + } catch (Exception e) { + player.sendMessage(ChatColor.RED.toString() + e.getMessage()); + } + return true; + } - public static boolean isVanished(Player player) { - return essentials != null && essentials.getUser(player).isVanished(); - } + public static boolean isVanished(Player player) { + return essentials != null && essentials.getUser(player).isVanished(); + } } diff --git a/src/main/java/com/massivecraft/factions/integration/Worldguard.java b/src/main/java/com/massivecraft/factions/integration/Worldguard.java index 0e429077..bc80b247 100644 --- a/src/main/java/com/massivecraft/factions/integration/Worldguard.java +++ b/src/main/java/com/massivecraft/factions/integration/Worldguard.java @@ -30,110 +30,110 @@ import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector; public class Worldguard { - private static WorldGuardPlugin wg; - private static boolean enabled = false; + private static WorldGuardPlugin wg; + private static boolean enabled = false; - public static void init(Plugin plugin) { - Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard"); - if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) { - enabled = false; - wg = null; - SavageFactions.plugin.log("Could not hook to WorldGuard. WorldGuard checks are disabled."); - } else { - wg = (WorldGuardPlugin) wgplug; - enabled = true; - SavageFactions.plugin.log("Successfully hooked to WorldGuard."); - } - } + public static void init(Plugin plugin) { + Plugin wgplug = plugin.getServer().getPluginManager().getPlugin("WorldGuard"); + if (wgplug == null || !(wgplug instanceof WorldGuardPlugin)) { + enabled = false; + wg = null; + SavageFactions.plugin.log("Could not hook to WorldGuard. WorldGuard checks are disabled."); + } else { + wg = (WorldGuardPlugin) wgplug; + enabled = true; + SavageFactions.plugin.log("Successfully hooked to WorldGuard."); + } + } - public static boolean isEnabled() { - return enabled; - } + public static boolean isEnabled() { + return enabled; + } - // PVP Flag check - // Returns: - // True: PVP is allowed - // False: PVP is disallowed - @SuppressWarnings("deprecation") - public static boolean isPVP(Player player) { - if (!enabled) { - // No WG hooks so we'll always bypass this check. - return true; - } + // PVP Flag check + // Returns: + // True: PVP is allowed + // False: PVP is disallowed + @SuppressWarnings("deprecation") + public static boolean isPVP(Player player) { + if (!enabled) { + // No WG hooks so we'll always bypass this check. + return true; + } - Location loc = player.getLocation(); - World world = loc.getWorld(); - Vector pt = toVector(loc); + Location loc = player.getLocation(); + World world = loc.getWorld(); + Vector pt = toVector(loc); - RegionManager regionManager = wg.getRegionManager(world); - ApplicableRegionSet set = regionManager.getApplicableRegions(pt); - return set.allows(DefaultFlag.PVP); - } + RegionManager regionManager = wg.getRegionManager(world); + ApplicableRegionSet set = regionManager.getApplicableRegions(pt); + return set.allows(DefaultFlag.PVP); + } - // Check if player can build at location by worldguards rules. - // Returns: - // True: Player can build in the region. - // False: Player can not build in the region. - public static boolean playerCanBuild(Player player, Location loc) { - if (!enabled) { - // No WG hooks so we'll always bypass this check. - return false; - } + // Check if player can build at location by worldguards rules. + // Returns: + // True: Player can build in the region. + // False: Player can not build in the region. + public static boolean playerCanBuild(Player player, Location loc) { + if (!enabled) { + // No WG hooks so we'll always bypass this check. + return false; + } - World world = loc.getWorld(); - Vector pt = toVector(loc); + World world = loc.getWorld(); + Vector pt = toVector(loc); - return wg.getRegionManager(world).getApplicableRegions(pt).size() > 0 && wg.canBuild(player, loc); - } + return wg.getRegionManager(world).getApplicableRegions(pt).size() > 0 && wg.canBuild(player, loc); + } - // Check for Regions in chunk the chunk - // Returns: - // True: Regions found within chunk - // False: No regions found within chunk + // Check for Regions in chunk the chunk + // Returns: + // True: Regions found within chunk + // False: No regions found within chunk - public static boolean checkForRegionsInChunk(FLocation floc) { - Chunk chunk = floc.getWorld().getChunkAt((int) floc.getX(), (int) floc.getZ()); + public static boolean checkForRegionsInChunk(FLocation floc) { + Chunk chunk = floc.getWorld().getChunkAt((int) floc.getX(), (int) floc.getZ()); - return checkForRegionsInChunk(chunk); - } + return checkForRegionsInChunk(chunk); + } - public static boolean checkForRegionsInChunk(Location loc) { - Chunk chunk = loc.getWorld().getChunkAt(loc); + public static boolean checkForRegionsInChunk(Location loc) { + Chunk chunk = loc.getWorld().getChunkAt(loc); - return checkForRegionsInChunk(chunk); - } + return checkForRegionsInChunk(chunk); + } - public static boolean checkForRegionsInChunk(Chunk chunk) { - if (!enabled) { - // No WG hooks so we'll always bypass this check. - return false; - } + public static boolean checkForRegionsInChunk(Chunk chunk) { + if (!enabled) { + // No WG hooks so we'll always bypass this check. + return false; + } - World world = chunk.getWorld(); - int minChunkX = chunk.getX() << 4; - int minChunkZ = chunk.getZ() << 4; - int maxChunkX = minChunkX + 15; - int maxChunkZ = minChunkZ + 15; + World world = chunk.getWorld(); + int minChunkX = chunk.getX() << 4; + int minChunkZ = chunk.getZ() << 4; + int maxChunkX = minChunkX + 15; + int maxChunkZ = minChunkZ + 15; - int worldHeight = world.getMaxHeight(); // Allow for heights other than default + int worldHeight = world.getMaxHeight(); // Allow for heights other than default - BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ); - BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ); + BlockVector minChunk = new BlockVector(minChunkX, 0, minChunkZ); + BlockVector maxChunk = new BlockVector(maxChunkX, worldHeight, maxChunkZ); - RegionManager regionManager = wg.getRegionManager(world); - ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk); - Map allregions = regionManager.getRegions(); - Collection allregionslist = new ArrayList<>(allregions.values()); - List overlaps; - boolean foundregions = false; + RegionManager regionManager = wg.getRegionManager(world); + ProtectedCuboidRegion region = new ProtectedCuboidRegion("wgfactionoverlapcheck", minChunk, maxChunk); + Map allregions = regionManager.getRegions(); + Collection allregionslist = new ArrayList<>(allregions.values()); + List overlaps; + boolean foundregions = false; - try { - overlaps = region.getIntersectingRegions(allregionslist); - foundregions = overlaps != null && !overlaps.isEmpty(); - } catch (Exception e) { - e.printStackTrace(); - } + try { + overlaps = region.getIntersectingRegions(allregionslist); + foundregions = overlaps != null && !overlaps.isEmpty(); + } catch (Exception e) { + e.printStackTrace(); + } - return foundregions; - } + return foundregions; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java b/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java index 7fb28c15..239b04e8 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/DynmapStyle.java @@ -3,105 +3,105 @@ package com.massivecraft.factions.integration.dynmap; import com.massivecraft.factions.Conf; public class DynmapStyle { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public String lineColor = null; - public Double lineOpacity = null; - public Integer lineWeight = null; - public String fillColor = null; - public Double fillOpacity = null; - // NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object. - // The reason is we use this class in the MConf. For serialization to work Dynmap would have to be loaded and we can't require that. - // Using dynmap is optional. - public String homeMarker = null; - public Boolean boost = null; + public String lineColor = null; + public Double lineOpacity = null; + public Integer lineWeight = null; + public String fillColor = null; + public Double fillOpacity = null; + // NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object. + // The reason is we use this class in the MConf. For serialization to work Dynmap would have to be loaded and we can't require that. + // Using dynmap is optional. + public String homeMarker = null; + public Boolean boost = null; - @SafeVarargs - public static T coalesce(T... items) { - for (T item : items) { - if (item != null) { - return item; - } - } - return null; - } + @SafeVarargs + public static T coalesce(T... items) { + for (T item : items) { + if (item != null) { + return item; + } + } + return null; + } - public static int getColor(String string) { - int ret = 0x00FF00; - try { - ret = Integer.parseInt(string.substring(1), 16); - } catch (NumberFormatException ignored) { - } - return ret; - } + public static int getColor(String string) { + int ret = 0x00FF00; + try { + ret = Integer.parseInt(string.substring(1), 16); + } catch (NumberFormatException ignored) { + } + return ret; + } - public int getLineColor() { - return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR)); - } + public int getLineColor() { + return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR)); + } - public DynmapStyle setStrokeColor(String strokeColor) { - this.lineColor = strokeColor; - return this; - } + public DynmapStyle setStrokeColor(String strokeColor) { + this.lineColor = strokeColor; + return this; + } - public double getLineOpacity() { - return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY); - } + public double getLineOpacity() { + return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY); + } - public DynmapStyle setLineOpacity(Double strokeOpacity) { - this.lineOpacity = strokeOpacity; - return this; - } + public DynmapStyle setLineOpacity(Double strokeOpacity) { + this.lineOpacity = strokeOpacity; + return this; + } - public int getLineWeight() { - return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT); - } + public int getLineWeight() { + return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT); + } - public DynmapStyle setLineWeight(Integer strokeWeight) { - this.lineWeight = strokeWeight; - return this; - } + public DynmapStyle setLineWeight(Integer strokeWeight) { + this.lineWeight = strokeWeight; + return this; + } - public int getFillColor() { - return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR)); - } + public int getFillColor() { + return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR)); + } - public DynmapStyle setFillColor(String fillColor) { - this.fillColor = fillColor; - return this; - } + public DynmapStyle setFillColor(String fillColor) { + this.fillColor = fillColor; + return this; + } - public double getFillOpacity() { - return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY); - } + public double getFillOpacity() { + return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY); + } - public DynmapStyle setFillOpacity(Double fillOpacity) { - this.fillOpacity = fillOpacity; - return this; - } + public DynmapStyle setFillOpacity(Double fillOpacity) { + this.fillOpacity = fillOpacity; + return this; + } - public String getHomeMarker() { - return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER); - } + public String getHomeMarker() { + return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER); + } - public DynmapStyle setHomeMarker(String homeMarker) { - this.homeMarker = homeMarker; - return this; - } + public DynmapStyle setHomeMarker(String homeMarker) { + this.homeMarker = homeMarker; + return this; + } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - public boolean getBoost() { - return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST); - } + public boolean getBoost() { + return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST); + } - public DynmapStyle setBoost(Boolean boost) { - this.boost = boost; - return this; - } + public DynmapStyle setBoost(Boolean boost) { + this.boost = boost; + return this; + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java index 6aad4390..0f15ff22 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/EngineDynmap.java @@ -17,750 +17,750 @@ import java.util.Map.Entry; // This source code is a heavily modified version of mikeprimms plugin Dynmap-Factions. public class EngineDynmap { - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // - - public final static int BLOCKS_PER_CHUNK = 16; - - public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; - - public final static String FACTIONS = "factions"; - public final static String FACTIONS_ = FACTIONS + "_"; - - public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; - - public final static String FACTIONS_HOME = FACTIONS_ + "home"; - public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; - - public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; - public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; - - // -------------------------------------------- // - // INSTANCE & CONSTRUCT - // -------------------------------------------- // - - private static final EngineDynmap i = new EngineDynmap(); - public DynmapAPI dynmapApi; - public MarkerAPI markerApi; - public MarkerSet markerset; - - private EngineDynmap() { - } - - public static EngineDynmap getInstance() { - return i; - } - - public static String getHtmlPlayerString(Collection playersOfficersList) { - StringBuilder ret = new StringBuilder(); - for (FPlayer fplayer : playersOfficersList) { - if (ret.length() > 0) { - ret.append(", "); - } - ret.append(getHtmlPlayerName(fplayer)); - } - return ret.toString(); - } - - public static String getHtmlPlayerName(FPlayer fplayer) { - return fplayer != null ? escapeHtml(fplayer.getName()) : "none"; - } - - public static String escapeHtml(String string) { - StringBuilder out = new StringBuilder(Math.max(16, string.length())); - for (int i = 0; i < string.length(); i++) { - char c = string.charAt(i); - if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { - out.append("&#") - .append((int) c) - .append(';'); - } else { - out.append(c); - } - } - return out.toString(); - } - - // Thread Safe / Asynchronous: Yes - public static void info(String msg) { - System.out.println(DYNMAP_INTEGRATION + msg); - } - - // -------------------------------------------- // - // UPDATE: HOMES - // -------------------------------------------- // - - // Thread Safe / Asynchronous: Yes - public static void severe(String msg) { - System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); - } - - public void init() { - Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); - - if (dynmap == null || !dynmap.isEnabled()) { - return; - } - - // Should we even use dynmap? - if (!Conf.dynmapUse) { - if (this.markerset != null) { - this.markerset.deleteMarkerSet(); - this.markerset = null; - } - return; - } - - // Shedule non thread safe sync at the end! - Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - - final Map homes = createHomes(); - final Map areas = createAreas(); - final Map> playerSets = createPlayersets(); - - if (!updateCore()) { - return; - } - - // createLayer() is thread safe but it makes use of fields set in updateCore() so we must have it after. - if (!updateLayer(createLayer())) { - return; - } - - updateHomes(homes); - updateAreas(areas); - updatePlayersets(playerSets); - } - }, 100L, 100L); - } - - // -------------------------------------------- // - // UPDATE: AREAS - // -------------------------------------------- // - - // Thread Safe / Asynchronous: No - public boolean updateCore() { - // Get DynmapAPI - this.dynmapApi = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); - if (this.dynmapApi == null) { - severe("Could not retrieve the DynmapAPI."); - return false; - } - - // Get MarkerAPI - this.markerApi = this.dynmapApi.getMarkerAPI(); - if (this.markerApi == null) { - severe("Could not retrieve the MarkerAPI."); - return false; - } - - return true; - } - - // Thread Safe / Asynchronous: Yes - public TempMarkerSet createLayer() { - TempMarkerSet ret = new TempMarkerSet(); - ret.label = Conf.dynmapLayerName; - ret.minimumZoom = Conf.dynmapLayerMinimumZoom; - ret.priority = Conf.dynmapLayerPriority; - ret.hideByDefault = !Conf.dynmapLayerVisible; - return ret; - } - - // Thread Safe / Asynchronous: No - public boolean updateLayer(TempMarkerSet temp) { - this.markerset = this.markerApi.getMarkerSet(FACTIONS_MARKERSET); - if (this.markerset == null) { - this.markerset = temp.create(this.markerApi, FACTIONS_MARKERSET); - if (this.markerset == null) { - severe("Could not create the Faction Markerset/Layer"); - return false; - } - } else { - temp.update(this.markerset); - } - return true; - } - - // Thread Safe / Asynchronous: Yes - public Map createHomes() { - Map ret = new HashMap<>(); - - // Loop current factions - for (Faction faction : Factions.getInstance().getAllFactions()) { - Location ps = faction.getHome(); - if (ps == null) { - continue; - } - - DynmapStyle style = getStyle(faction); - - String markerId = FACTIONS_HOME_ + faction.getId(); - - TempMarker temp = new TempMarker(); - temp.label = ChatColor.stripColor(faction.getTag()); - temp.world = ps.getWorld().toString(); - temp.x = ps.getX(); - temp.y = ps.getY(); - temp.z = ps.getZ(); - temp.iconName = style.getHomeMarker(); - temp.description = getDescription(faction); - - ret.put(markerId, temp); - } - - return ret; - } - - // Thread Safe / Asynchronous: No - // This method places out the faction home markers into the factions markerset. - public void updateHomes(Map homes) { - // Put all current faction markers in a map - Map markers = new HashMap<>(); - for (Marker marker : this.markerset.getMarkers()) { - markers.put(marker.getMarkerID(), marker); - } - - // Loop homes - for (Entry entry : homes.entrySet()) { - String markerId = entry.getKey(); - TempMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - Marker marker = markers.remove(markerId); - if (marker == null) { - marker = temp.create(this.markerApi, this.markerset, markerId); - if (marker == null) { - EngineDynmap.severe("Could not get/create the home marker " + markerId); - } - } else { - temp.update(this.markerApi, marker); - } - } - - // Delete Deprecated Markers - // Only old markers should now be left - for (Marker marker : markers.values()) { - marker.deleteMarker(); - } - } - - // -------------------------------------------- // - // UPDATE: PLAYERSET - // -------------------------------------------- // - - // Thread Safe: YES - public Map createAreas() { - Map>> worldFactionChunks = createWorldFactionChunks(); - return createAreas(worldFactionChunks); - } - - // Thread Safe: YES - public Map>> createWorldFactionChunks() { - // Create map "world name --> faction --> set of chunk coords" - Map>> worldFactionChunks = new HashMap<>(); - - // Note: The board is the world. The board id is the world name. - MemoryBoard board = (MemoryBoard) Board.getInstance(); - - for (Entry entry : board.flocationIds.entrySet()) { - String world = entry.getKey().getWorldName(); - Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); - - Map> factionChunks = worldFactionChunks.get(world); - if (factionChunks == null) { - factionChunks = new HashMap<>(); - worldFactionChunks.put(world, factionChunks); - } - - Set factionTerritory = factionChunks.get(chunkOwner); - if (factionTerritory == null) { - factionTerritory = new HashSet<>(); - factionChunks.put(chunkOwner, factionTerritory); - } - - factionTerritory.add(entry.getKey()); - } - - return worldFactionChunks; - } - - // Thread Safe: YES - public Map createAreas(Map>> worldFactionChunks) { - Map ret = new HashMap<>(); - - // For each world - for (Entry>> entry : worldFactionChunks.entrySet()) { - String world = entry.getKey(); - Map> factionChunks = entry.getValue(); - - // For each faction and its chunks in that world - for (Entry> entry1 : factionChunks.entrySet()) { - Faction faction = entry1.getKey(); - Set chunks = entry1.getValue(); - Map worldFactionMarkers = createAreas(world, faction, chunks); - ret.putAll(worldFactionMarkers); - } - } - - return ret; - } - - // Thread Safe: YES - // Handle specific faction on specific world - // "handle faction on world" - public Map createAreas(String world, Faction faction, Set chunks) { - Map ret = new HashMap<>(); - - // If the faction is visible ... - if (!isVisible(faction, world)) { - return ret; - } - - // ... and has any chunks ... - if (chunks.isEmpty()) { - return ret; - } - - // Index of polygon for given faction - int markerIndex = 0; - - // Create the info window - String description = getDescription(faction); - - // Fetch Style - DynmapStyle style = this.getStyle(faction); - - // Loop through chunks: set flags on chunk map - TileFlags allChunkFlags = new TileFlags(); - LinkedList allChunks = new LinkedList<>(); - for (FLocation chunk : chunks) { - allChunkFlags.setFlag((int) chunk.getX(), (int) chunk.getZ(), true); // Set flag for chunk - allChunks.addLast(chunk); - } - - // Loop through until we don't find more areas - while (allChunks != null) { - TileFlags ourChunkFlags = null; - LinkedList ourChunks = null; - LinkedList newChunks = null; - - int minimumX = Integer.MAX_VALUE; - int minimumZ = Integer.MAX_VALUE; - for (FLocation chunk : allChunks) { - int chunkX = (int) chunk.getX(); - int chunkZ = (int) chunk.getZ(); - - // If we need to start shape, and this block is not part of one yet - if (ourChunkFlags == null && allChunkFlags.getFlag(chunkX, chunkZ)) { - ourChunkFlags = new TileFlags(); // Create map for shape - ourChunks = new LinkedList<>(); - floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape - ourChunks.add(chunk); // Add it to our chunk list - minimumX = chunkX; - minimumZ = chunkZ; - } - // If shape found, and we're in it, add to our node list - else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) { - ourChunks.add(chunk); - if (chunkX < minimumX) { - minimumX = chunkX; - minimumZ = chunkZ; - } else if (chunkX == minimumX && chunkZ < minimumZ) { - minimumZ = chunkZ; - } - } - // Else, keep it in the list for the next polygon - else { - if (newChunks == null) { - newChunks = new LinkedList<>(); - } - newChunks.add(chunk); - } - } - - // Replace list (null if no more to process) - allChunks = newChunks; - - if (ourChunkFlags == null) { - continue; - } - - // Trace outline of blocks - start from minx, minz going to x+ - int initialX = minimumX; - int initialZ = minimumZ; - int currentX = minimumX; - int currentZ = minimumZ; - Direction direction = Direction.XPLUS; - ArrayList linelist = new ArrayList<>(); - linelist.add(new int[]{initialX, initialZ}); // Add start point - while ((currentX != initialX) || (currentZ != initialZ) || (direction != Direction.ZMINUS)) { - switch (direction) { - case XPLUS: // Segment in X+ direction - if (!ourChunkFlags.getFlag(currentX + 1, currentZ)) { // Right turn? - linelist.add(new int[]{currentX + 1, currentZ}); // Finish line - direction = Direction.ZPLUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ - 1)) { // Straight? - currentX++; - } else { // Left turn - linelist.add(new int[]{currentX + 1, currentZ}); // Finish line - direction = Direction.ZMINUS; - currentX++; - currentZ--; - } - break; - case ZPLUS: // Segment in Z+ direction - if (!ourChunkFlags.getFlag(currentX, currentZ + 1)) { // Right turn? - linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line - direction = Direction.XMINUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ + 1)) { // Straight? - currentZ++; - } else { // Left turn - linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line - direction = Direction.XPLUS; - currentX++; - currentZ++; - } - break; - case XMINUS: // Segment in X- direction - if (!ourChunkFlags.getFlag(currentX - 1, currentZ)) { // Right turn? - linelist.add(new int[]{currentX, currentZ + 1}); // Finish line - direction = Direction.ZMINUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ + 1)) { // Straight? - currentX--; - } else { // Left turn - linelist.add(new int[]{currentX, currentZ + 1}); // Finish line - direction = Direction.ZPLUS; - currentX--; - currentZ++; - } - break; - case ZMINUS: // Segment in Z- direction - if (!ourChunkFlags.getFlag(currentX, currentZ - 1)) { // Right turn? - linelist.add(new int[]{currentX, currentZ}); // Finish line - direction = Direction.XPLUS; // Change direction - } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ - 1)) { // Straight? - currentZ--; - } else { // Left turn - linelist.add(new int[]{currentX, currentZ}); // Finish line - direction = Direction.XMINUS; - currentX--; - currentZ--; - } - break; - } - } - - int sz = linelist.size(); - double[] x = new double[sz]; - double[] z = new double[sz]; - for (int i = 0; i < sz; i++) { - int[] line = linelist.get(i); - x[i] = (double) line[0] * (double) BLOCKS_PER_CHUNK; - z[i] = (double) line[1] * (double) BLOCKS_PER_CHUNK; - } - - // Build information for specific area - String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; - - TempAreaMarker temp = new TempAreaMarker(); - temp.label = faction.getTag(); - temp.world = world; - temp.x = x; - temp.z = z; - temp.description = description; - - temp.lineColor = style.getLineColor(); - temp.lineOpacity = style.getLineOpacity(); - temp.lineWeight = style.getLineWeight(); - - temp.fillColor = style.getFillColor(); - temp.fillOpacity = style.getFillOpacity(); - - temp.boost = style.getBoost(); - - ret.put(markerId, temp); - - markerIndex++; - } - - return ret; - } - - // -------------------------------------------- // - // UTIL & SHARED - // -------------------------------------------- // - - // Thread Safe: NO - public void updateAreas(Map areas) { - // Map Current - Map markers = new HashMap<>(); - for (AreaMarker marker : this.markerset.getAreaMarkers()) { - markers.put(marker.getMarkerID(), marker); - } - - // Loop New - for (Entry entry : areas.entrySet()) { - String markerId = entry.getKey(); - TempAreaMarker temp = entry.getValue(); - - // Get Creative - // NOTE: I remove from the map created just in the beginning of this method. - // NOTE: That way what is left at the end will be outdated markers to remove. - AreaMarker marker = markers.remove(markerId); - if (marker == null) { - marker = temp.create(this.markerset, markerId); - if (marker == null) { - severe("Could not get/create the area marker " + markerId); - } - } else { - temp.update(marker); - } - } - - // Only old/outdated should now be left. Delete them. - for (AreaMarker marker : markers.values()) { - marker.deleteMarker(); - } - } - - // Thread Safe / Asynchronous: Yes - public String createPlayersetId(Faction faction) { - if (faction == null) { - return null; - } - if (faction.isWilderness()) { - return null; - } - String factionId = faction.getId(); - if (factionId == null) { - return null; - } - return FACTIONS_PLAYERSET_ + factionId; - } - - // Thread Safe / Asynchronous: Yes - public Set createPlayerset(Faction faction) { - if (faction == null) { - return null; - } - if (faction.isWilderness()) { - return null; - } - - Set ret = new HashSet<>(); - - for (FPlayer fplayer : faction.getFPlayers()) { - // NOTE: We add both UUID and name. This might be a good idea for future proofing. - ret.add(fplayer.getId()); - ret.add(fplayer.getName()); - } - - return ret; - } - - // Thread Safe / Asynchronous: Yes - public Map> createPlayersets() { - if (!Conf.dynmapVisibilityByFaction) { - return null; - } - - Map> ret = new HashMap<>(); - - for (Faction faction : Factions.getInstance().getAllFactions()) { - String playersetId = createPlayersetId(faction); - if (playersetId == null) { - continue; - } - Set playerIds = createPlayerset(faction); - if (playerIds == null) { - continue; - } - ret.put(playersetId, playerIds); - } - - return ret; - } - - // Thread Safe / Asynchronous: No - public void updatePlayersets(Map> playersets) { - if (playersets == null) { - return; - } - - // Remove - for (PlayerSet set : this.markerApi.getPlayerSets()) { - if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) { - continue; - } - - // (Null means remove all) - if (playersets.containsKey(set.getSetID())) { - continue; - } - - set.deleteSet(); - } - - // Add / Update - for (Entry> entry : playersets.entrySet()) { - // Extract from Entry - String setId = entry.getKey(); - Set playerIds = entry.getValue(); - - // Get Creatively - PlayerSet set = this.markerApi.getPlayerSet(setId); - if (set == null) { - set = this.markerApi.createPlayerSet(setId, // id - true, // symmetric - playerIds, // players - false // persistent - ); - } - if (set == null) { - severe("Could not get/create the player set " + setId); - continue; - } - - // Set Content - set.setPlayers(playerIds); - } - } - - // Thread Safe / Asynchronous: Yes - private String getDescription(Faction faction) { - String ret = "
" + Conf.dynmapDescription + "
"; - - // Name - String name = faction.getTag(); - name = escapeHtml(ChatColor.stripColor(name)); - ret = ret.replace("%name%", name); - - // Description - String description = faction.getDescription(); - description = escapeHtml(ChatColor.stripColor(description)); - ret = ret.replace("%description%", description); - - // Money - - String money = "unavailable"; - if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) - money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); - ret = ret.replace("%money%", money); - - - // Players - Set playersList = faction.getFPlayers(); - String playersCount = String.valueOf(playersList.size()); - String players = getHtmlPlayerString(playersList); - - FPlayer playersLeaderObject = faction.getFPlayerAdmin(); - String playersLeader = getHtmlPlayerName(playersLeaderObject); - - ArrayList playersCoAdminsList = faction.getFPlayersWhereRole(Role.COLEADER); - String playersCoAdminsCount = String.valueOf(playersCoAdminsList.size()); - String playersCoAdmins = getHtmlPlayerString(playersCoAdminsList); - - ArrayList playersModeratorsList = faction.getFPlayersWhereRole(Role.MODERATOR); - String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); - String playersModerators = getHtmlPlayerString(playersModeratorsList); - - - ArrayList playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); - String playersNormalsCount = String.valueOf(playersNormalsList.size()); - String playersNormals = getHtmlPlayerString(playersNormalsList); - - ret = ret.replace("%players%", players); - ret = ret.replace("%players.count%", playersCount); - ret = ret.replace("%players.leader%", playersLeader); - ret = ret.replace("%players.admins%", playersCoAdmins); - ret = ret.replace("%players.admins.count%", playersCoAdminsCount); - ret = ret.replace("%players.moderators%", playersModerators); - ret = ret.replace("%players.moderators.count%", playersModeratorsCount); - ret = ret.replace("%players.normals%", playersNormals); - ret = ret.replace("%players.normals.count%", playersNormalsCount); - - return ret; - } - - // Thread Safe / Asynchronous: Yes - private boolean isVisible(Faction faction, String world) { - if (faction == null) { - return false; - } - final String factionId = faction.getId(); - if (factionId == null) { - return false; - } - final String factionName = faction.getTag(); - if (factionName == null) { - return false; - } - - Set visible = Conf.dynmapVisibleFactions; - Set hidden = Conf.dynmapHiddenFactions; - - if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) { - return false; - } - - return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); - } - - // Thread Safe / Asynchronous: Yes - public DynmapStyle getStyle(Faction faction) { - DynmapStyle ret; - - ret = Conf.dynmapFactionStyles.get(faction.getId()); - if (ret != null) { - return ret; - } - - ret = Conf.dynmapFactionStyles.get(faction.getTag()); - if (ret != null) { - return ret; - } - - return Conf.dynmapDefaultStyle; - } - - // Find all contiguous blocks, set in target and clear in source - private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { - int cnt = 0; - ArrayDeque stack = new ArrayDeque<>(); - stack.push(new int[]{x, y}); - - while (!stack.isEmpty()) { - int[] nxt = stack.pop(); - x = nxt[0]; - y = nxt[1]; - if (source.getFlag(x, y)) { // Set in src - source.setFlag(x, y, false); // Clear source - destination.setFlag(x, y, true); // Set in destination - cnt++; - if (source.getFlag(x + 1, y)) { - stack.push(new int[]{x + 1, y}); - } - if (source.getFlag(x - 1, y)) { - stack.push(new int[]{x - 1, y}); - } - if (source.getFlag(x, y + 1)) { - stack.push(new int[]{x, y + 1}); - } - if (source.getFlag(x, y - 1)) { - stack.push(new int[]{x, y - 1}); - } - } - } - return cnt; - } - - enum Direction { - XPLUS, ZPLUS, XMINUS, ZMINUS - } + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // + + public final static int BLOCKS_PER_CHUNK = 16; + + public final static String DYNMAP_INTEGRATION = "\u00A7dDynmap Integration: \u00A7e"; + + public final static String FACTIONS = "factions"; + public final static String FACTIONS_ = FACTIONS + "_"; + + public final static String FACTIONS_MARKERSET = FACTIONS_ + "markerset"; + + public final static String FACTIONS_HOME = FACTIONS_ + "home"; + public final static String FACTIONS_HOME_ = FACTIONS_HOME + "_"; + + public final static String FACTIONS_PLAYERSET = FACTIONS_ + "playerset"; + public final static String FACTIONS_PLAYERSET_ = FACTIONS_PLAYERSET + "_"; + + // -------------------------------------------- // + // INSTANCE & CONSTRUCT + // -------------------------------------------- // + + private static final EngineDynmap i = new EngineDynmap(); + public DynmapAPI dynmapApi; + public MarkerAPI markerApi; + public MarkerSet markerset; + + private EngineDynmap() { + } + + public static EngineDynmap getInstance() { + return i; + } + + public static String getHtmlPlayerString(Collection playersOfficersList) { + StringBuilder ret = new StringBuilder(); + for (FPlayer fplayer : playersOfficersList) { + if (ret.length() > 0) { + ret.append(", "); + } + ret.append(getHtmlPlayerName(fplayer)); + } + return ret.toString(); + } + + public static String getHtmlPlayerName(FPlayer fplayer) { + return fplayer != null ? escapeHtml(fplayer.getName()) : "none"; + } + + public static String escapeHtml(String string) { + StringBuilder out = new StringBuilder(Math.max(16, string.length())); + for (int i = 0; i < string.length(); i++) { + char c = string.charAt(i); + if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') { + out.append("&#") + .append((int) c) + .append(';'); + } else { + out.append(c); + } + } + return out.toString(); + } + + // Thread Safe / Asynchronous: Yes + public static void info(String msg) { + System.out.println(DYNMAP_INTEGRATION + msg); + } + + // -------------------------------------------- // + // UPDATE: HOMES + // -------------------------------------------- // + + // Thread Safe / Asynchronous: Yes + public static void severe(String msg) { + System.out.println(DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg); + } + + public void init() { + Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); + + if (dynmap == null || !dynmap.isEnabled()) { + return; + } + + // Should we even use dynmap? + if (!Conf.dynmapUse) { + if (this.markerset != null) { + this.markerset.deleteMarkerSet(); + this.markerset = null; + } + return; + } + + // Shedule non thread safe sync at the end! + Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + + final Map homes = createHomes(); + final Map areas = createAreas(); + final Map> playerSets = createPlayersets(); + + if (!updateCore()) { + return; + } + + // createLayer() is thread safe but it makes use of fields set in updateCore() so we must have it after. + if (!updateLayer(createLayer())) { + return; + } + + updateHomes(homes); + updateAreas(areas); + updatePlayersets(playerSets); + } + }, 100L, 100L); + } + + // -------------------------------------------- // + // UPDATE: AREAS + // -------------------------------------------- // + + // Thread Safe / Asynchronous: No + public boolean updateCore() { + // Get DynmapAPI + this.dynmapApi = (DynmapAPI) Bukkit.getPluginManager().getPlugin("dynmap"); + if (this.dynmapApi == null) { + severe("Could not retrieve the DynmapAPI."); + return false; + } + + // Get MarkerAPI + this.markerApi = this.dynmapApi.getMarkerAPI(); + if (this.markerApi == null) { + severe("Could not retrieve the MarkerAPI."); + return false; + } + + return true; + } + + // Thread Safe / Asynchronous: Yes + public TempMarkerSet createLayer() { + TempMarkerSet ret = new TempMarkerSet(); + ret.label = Conf.dynmapLayerName; + ret.minimumZoom = Conf.dynmapLayerMinimumZoom; + ret.priority = Conf.dynmapLayerPriority; + ret.hideByDefault = !Conf.dynmapLayerVisible; + return ret; + } + + // Thread Safe / Asynchronous: No + public boolean updateLayer(TempMarkerSet temp) { + this.markerset = this.markerApi.getMarkerSet(FACTIONS_MARKERSET); + if (this.markerset == null) { + this.markerset = temp.create(this.markerApi, FACTIONS_MARKERSET); + if (this.markerset == null) { + severe("Could not create the Faction Markerset/Layer"); + return false; + } + } else { + temp.update(this.markerset); + } + return true; + } + + // Thread Safe / Asynchronous: Yes + public Map createHomes() { + Map ret = new HashMap<>(); + + // Loop current factions + for (Faction faction : Factions.getInstance().getAllFactions()) { + Location ps = faction.getHome(); + if (ps == null) { + continue; + } + + DynmapStyle style = getStyle(faction); + + String markerId = FACTIONS_HOME_ + faction.getId(); + + TempMarker temp = new TempMarker(); + temp.label = ChatColor.stripColor(faction.getTag()); + temp.world = ps.getWorld().toString(); + temp.x = ps.getX(); + temp.y = ps.getY(); + temp.z = ps.getZ(); + temp.iconName = style.getHomeMarker(); + temp.description = getDescription(faction); + + ret.put(markerId, temp); + } + + return ret; + } + + // Thread Safe / Asynchronous: No + // This method places out the faction home markers into the factions markerset. + public void updateHomes(Map homes) { + // Put all current faction markers in a map + Map markers = new HashMap<>(); + for (Marker marker : this.markerset.getMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop homes + for (Entry entry : homes.entrySet()) { + String markerId = entry.getKey(); + TempMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + Marker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerApi, this.markerset, markerId); + if (marker == null) { + EngineDynmap.severe("Could not get/create the home marker " + markerId); + } + } else { + temp.update(this.markerApi, marker); + } + } + + // Delete Deprecated Markers + // Only old markers should now be left + for (Marker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // -------------------------------------------- // + // UPDATE: PLAYERSET + // -------------------------------------------- // + + // Thread Safe: YES + public Map createAreas() { + Map>> worldFactionChunks = createWorldFactionChunks(); + return createAreas(worldFactionChunks); + } + + // Thread Safe: YES + public Map>> createWorldFactionChunks() { + // Create map "world name --> faction --> set of chunk coords" + Map>> worldFactionChunks = new HashMap<>(); + + // Note: The board is the world. The board id is the world name. + MemoryBoard board = (MemoryBoard) Board.getInstance(); + + for (Entry entry : board.flocationIds.entrySet()) { + String world = entry.getKey().getWorldName(); + Faction chunkOwner = Factions.getInstance().getFactionById(entry.getValue()); + + Map> factionChunks = worldFactionChunks.get(world); + if (factionChunks == null) { + factionChunks = new HashMap<>(); + worldFactionChunks.put(world, factionChunks); + } + + Set factionTerritory = factionChunks.get(chunkOwner); + if (factionTerritory == null) { + factionTerritory = new HashSet<>(); + factionChunks.put(chunkOwner, factionTerritory); + } + + factionTerritory.add(entry.getKey()); + } + + return worldFactionChunks; + } + + // Thread Safe: YES + public Map createAreas(Map>> worldFactionChunks) { + Map ret = new HashMap<>(); + + // For each world + for (Entry>> entry : worldFactionChunks.entrySet()) { + String world = entry.getKey(); + Map> factionChunks = entry.getValue(); + + // For each faction and its chunks in that world + for (Entry> entry1 : factionChunks.entrySet()) { + Faction faction = entry1.getKey(); + Set chunks = entry1.getValue(); + Map worldFactionMarkers = createAreas(world, faction, chunks); + ret.putAll(worldFactionMarkers); + } + } + + return ret; + } + + // Thread Safe: YES + // Handle specific faction on specific world + // "handle faction on world" + public Map createAreas(String world, Faction faction, Set chunks) { + Map ret = new HashMap<>(); + + // If the faction is visible ... + if (!isVisible(faction, world)) { + return ret; + } + + // ... and has any chunks ... + if (chunks.isEmpty()) { + return ret; + } + + // Index of polygon for given faction + int markerIndex = 0; + + // Create the info window + String description = getDescription(faction); + + // Fetch Style + DynmapStyle style = this.getStyle(faction); + + // Loop through chunks: set flags on chunk map + TileFlags allChunkFlags = new TileFlags(); + LinkedList allChunks = new LinkedList<>(); + for (FLocation chunk : chunks) { + allChunkFlags.setFlag((int) chunk.getX(), (int) chunk.getZ(), true); // Set flag for chunk + allChunks.addLast(chunk); + } + + // Loop through until we don't find more areas + while (allChunks != null) { + TileFlags ourChunkFlags = null; + LinkedList ourChunks = null; + LinkedList newChunks = null; + + int minimumX = Integer.MAX_VALUE; + int minimumZ = Integer.MAX_VALUE; + for (FLocation chunk : allChunks) { + int chunkX = (int) chunk.getX(); + int chunkZ = (int) chunk.getZ(); + + // If we need to start shape, and this block is not part of one yet + if (ourChunkFlags == null && allChunkFlags.getFlag(chunkX, chunkZ)) { + ourChunkFlags = new TileFlags(); // Create map for shape + ourChunks = new LinkedList<>(); + floodFillTarget(allChunkFlags, ourChunkFlags, chunkX, chunkZ); // Copy shape + ourChunks.add(chunk); // Add it to our chunk list + minimumX = chunkX; + minimumZ = chunkZ; + } + // If shape found, and we're in it, add to our node list + else if (ourChunkFlags != null && ourChunkFlags.getFlag(chunkX, chunkZ)) { + ourChunks.add(chunk); + if (chunkX < minimumX) { + minimumX = chunkX; + minimumZ = chunkZ; + } else if (chunkX == minimumX && chunkZ < minimumZ) { + minimumZ = chunkZ; + } + } + // Else, keep it in the list for the next polygon + else { + if (newChunks == null) { + newChunks = new LinkedList<>(); + } + newChunks.add(chunk); + } + } + + // Replace list (null if no more to process) + allChunks = newChunks; + + if (ourChunkFlags == null) { + continue; + } + + // Trace outline of blocks - start from minx, minz going to x+ + int initialX = minimumX; + int initialZ = minimumZ; + int currentX = minimumX; + int currentZ = minimumZ; + Direction direction = Direction.XPLUS; + ArrayList linelist = new ArrayList<>(); + linelist.add(new int[]{initialX, initialZ}); // Add start point + while ((currentX != initialX) || (currentZ != initialZ) || (direction != Direction.ZMINUS)) { + switch (direction) { + case XPLUS: // Segment in X+ direction + if (!ourChunkFlags.getFlag(currentX + 1, currentZ)) { // Right turn? + linelist.add(new int[]{currentX + 1, currentZ}); // Finish line + direction = Direction.ZPLUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ - 1)) { // Straight? + currentX++; + } else { // Left turn + linelist.add(new int[]{currentX + 1, currentZ}); // Finish line + direction = Direction.ZMINUS; + currentX++; + currentZ--; + } + break; + case ZPLUS: // Segment in Z+ direction + if (!ourChunkFlags.getFlag(currentX, currentZ + 1)) { // Right turn? + linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line + direction = Direction.XMINUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX + 1, currentZ + 1)) { // Straight? + currentZ++; + } else { // Left turn + linelist.add(new int[]{currentX + 1, currentZ + 1}); // Finish line + direction = Direction.XPLUS; + currentX++; + currentZ++; + } + break; + case XMINUS: // Segment in X- direction + if (!ourChunkFlags.getFlag(currentX - 1, currentZ)) { // Right turn? + linelist.add(new int[]{currentX, currentZ + 1}); // Finish line + direction = Direction.ZMINUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ + 1)) { // Straight? + currentX--; + } else { // Left turn + linelist.add(new int[]{currentX, currentZ + 1}); // Finish line + direction = Direction.ZPLUS; + currentX--; + currentZ++; + } + break; + case ZMINUS: // Segment in Z- direction + if (!ourChunkFlags.getFlag(currentX, currentZ - 1)) { // Right turn? + linelist.add(new int[]{currentX, currentZ}); // Finish line + direction = Direction.XPLUS; // Change direction + } else if (!ourChunkFlags.getFlag(currentX - 1, currentZ - 1)) { // Straight? + currentZ--; + } else { // Left turn + linelist.add(new int[]{currentX, currentZ}); // Finish line + direction = Direction.XMINUS; + currentX--; + currentZ--; + } + break; + } + } + + int sz = linelist.size(); + double[] x = new double[sz]; + double[] z = new double[sz]; + for (int i = 0; i < sz; i++) { + int[] line = linelist.get(i); + x[i] = (double) line[0] * (double) BLOCKS_PER_CHUNK; + z[i] = (double) line[1] * (double) BLOCKS_PER_CHUNK; + } + + // Build information for specific area + String markerId = FACTIONS_ + world + "__" + faction.getId() + "__" + markerIndex; + + TempAreaMarker temp = new TempAreaMarker(); + temp.label = faction.getTag(); + temp.world = world; + temp.x = x; + temp.z = z; + temp.description = description; + + temp.lineColor = style.getLineColor(); + temp.lineOpacity = style.getLineOpacity(); + temp.lineWeight = style.getLineWeight(); + + temp.fillColor = style.getFillColor(); + temp.fillOpacity = style.getFillOpacity(); + + temp.boost = style.getBoost(); + + ret.put(markerId, temp); + + markerIndex++; + } + + return ret; + } + + // -------------------------------------------- // + // UTIL & SHARED + // -------------------------------------------- // + + // Thread Safe: NO + public void updateAreas(Map areas) { + // Map Current + Map markers = new HashMap<>(); + for (AreaMarker marker : this.markerset.getAreaMarkers()) { + markers.put(marker.getMarkerID(), marker); + } + + // Loop New + for (Entry entry : areas.entrySet()) { + String markerId = entry.getKey(); + TempAreaMarker temp = entry.getValue(); + + // Get Creative + // NOTE: I remove from the map created just in the beginning of this method. + // NOTE: That way what is left at the end will be outdated markers to remove. + AreaMarker marker = markers.remove(markerId); + if (marker == null) { + marker = temp.create(this.markerset, markerId); + if (marker == null) { + severe("Could not get/create the area marker " + markerId); + } + } else { + temp.update(marker); + } + } + + // Only old/outdated should now be left. Delete them. + for (AreaMarker marker : markers.values()) { + marker.deleteMarker(); + } + } + + // Thread Safe / Asynchronous: Yes + public String createPlayersetId(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } + String factionId = faction.getId(); + if (factionId == null) { + return null; + } + return FACTIONS_PLAYERSET_ + factionId; + } + + // Thread Safe / Asynchronous: Yes + public Set createPlayerset(Faction faction) { + if (faction == null) { + return null; + } + if (faction.isWilderness()) { + return null; + } + + Set ret = new HashSet<>(); + + for (FPlayer fplayer : faction.getFPlayers()) { + // NOTE: We add both UUID and name. This might be a good idea for future proofing. + ret.add(fplayer.getId()); + ret.add(fplayer.getName()); + } + + return ret; + } + + // Thread Safe / Asynchronous: Yes + public Map> createPlayersets() { + if (!Conf.dynmapVisibilityByFaction) { + return null; + } + + Map> ret = new HashMap<>(); + + for (Faction faction : Factions.getInstance().getAllFactions()) { + String playersetId = createPlayersetId(faction); + if (playersetId == null) { + continue; + } + Set playerIds = createPlayerset(faction); + if (playerIds == null) { + continue; + } + ret.put(playersetId, playerIds); + } + + return ret; + } + + // Thread Safe / Asynchronous: No + public void updatePlayersets(Map> playersets) { + if (playersets == null) { + return; + } + + // Remove + for (PlayerSet set : this.markerApi.getPlayerSets()) { + if (!set.getSetID().startsWith(FACTIONS_PLAYERSET_)) { + continue; + } + + // (Null means remove all) + if (playersets.containsKey(set.getSetID())) { + continue; + } + + set.deleteSet(); + } + + // Add / Update + for (Entry> entry : playersets.entrySet()) { + // Extract from Entry + String setId = entry.getKey(); + Set playerIds = entry.getValue(); + + // Get Creatively + PlayerSet set = this.markerApi.getPlayerSet(setId); + if (set == null) { + set = this.markerApi.createPlayerSet(setId, // id + true, // symmetric + playerIds, // players + false // persistent + ); + } + if (set == null) { + severe("Could not get/create the player set " + setId); + continue; + } + + // Set Content + set.setPlayers(playerIds); + } + } + + // Thread Safe / Asynchronous: Yes + private String getDescription(Faction faction) { + String ret = "
" + Conf.dynmapDescription + "
"; + + // Name + String name = faction.getTag(); + name = escapeHtml(ChatColor.stripColor(name)); + ret = ret.replace("%name%", name); + + // Description + String description = faction.getDescription(); + description = escapeHtml(ChatColor.stripColor(description)); + ret = ret.replace("%description%", description); + + // Money + + String money = "unavailable"; + if (Conf.bankEnabled && Conf.dynmapDescriptionMoney) + money = String.format("%.2f", Econ.getBalance(faction.getAccountId())); + ret = ret.replace("%money%", money); + + + // Players + Set playersList = faction.getFPlayers(); + String playersCount = String.valueOf(playersList.size()); + String players = getHtmlPlayerString(playersList); + + FPlayer playersLeaderObject = faction.getFPlayerAdmin(); + String playersLeader = getHtmlPlayerName(playersLeaderObject); + + ArrayList playersCoAdminsList = faction.getFPlayersWhereRole(Role.COLEADER); + String playersCoAdminsCount = String.valueOf(playersCoAdminsList.size()); + String playersCoAdmins = getHtmlPlayerString(playersCoAdminsList); + + ArrayList playersModeratorsList = faction.getFPlayersWhereRole(Role.MODERATOR); + String playersModeratorsCount = String.valueOf(playersModeratorsList.size()); + String playersModerators = getHtmlPlayerString(playersModeratorsList); + + + ArrayList playersNormalsList = faction.getFPlayersWhereRole(Role.NORMAL); + String playersNormalsCount = String.valueOf(playersNormalsList.size()); + String playersNormals = getHtmlPlayerString(playersNormalsList); + + ret = ret.replace("%players%", players); + ret = ret.replace("%players.count%", playersCount); + ret = ret.replace("%players.leader%", playersLeader); + ret = ret.replace("%players.admins%", playersCoAdmins); + ret = ret.replace("%players.admins.count%", playersCoAdminsCount); + ret = ret.replace("%players.moderators%", playersModerators); + ret = ret.replace("%players.moderators.count%", playersModeratorsCount); + ret = ret.replace("%players.normals%", playersNormals); + ret = ret.replace("%players.normals.count%", playersNormalsCount); + + return ret; + } + + // Thread Safe / Asynchronous: Yes + private boolean isVisible(Faction faction, String world) { + if (faction == null) { + return false; + } + final String factionId = faction.getId(); + if (factionId == null) { + return false; + } + final String factionName = faction.getTag(); + if (factionName == null) { + return false; + } + + Set visible = Conf.dynmapVisibleFactions; + Set hidden = Conf.dynmapHiddenFactions; + + if (!visible.isEmpty() && !visible.contains(factionId) && !visible.contains(factionName) && !visible.contains("world:" + world)) { + return false; + } + + return !hidden.contains(factionId) && !hidden.contains(factionName) && !hidden.contains("world:" + world); + } + + // Thread Safe / Asynchronous: Yes + public DynmapStyle getStyle(Faction faction) { + DynmapStyle ret; + + ret = Conf.dynmapFactionStyles.get(faction.getId()); + if (ret != null) { + return ret; + } + + ret = Conf.dynmapFactionStyles.get(faction.getTag()); + if (ret != null) { + return ret; + } + + return Conf.dynmapDefaultStyle; + } + + // Find all contiguous blocks, set in target and clear in source + private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { + int cnt = 0; + ArrayDeque stack = new ArrayDeque<>(); + stack.push(new int[]{x, y}); + + while (!stack.isEmpty()) { + int[] nxt = stack.pop(); + x = nxt[0]; + y = nxt[1]; + if (source.getFlag(x, y)) { // Set in src + source.setFlag(x, y, false); // Clear source + destination.setFlag(x, y, true); // Set in destination + cnt++; + if (source.getFlag(x + 1, y)) { + stack.push(new int[]{x + 1, y}); + } + if (source.getFlag(x - 1, y)) { + stack.push(new int[]{x - 1, y}); + } + if (source.getFlag(x, y + 1)) { + stack.push(new int[]{x, y + 1}); + } + if (source.getFlag(x, y - 1)) { + stack.push(new int[]{x, y - 1}); + } + } + } + return cnt; + } + + enum Direction { + XPLUS, ZPLUS, XMINUS, ZMINUS + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java index ec346d53..33e695b4 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempAreaMarker.java @@ -4,113 +4,113 @@ import org.dynmap.markers.AreaMarker; import org.dynmap.markers.MarkerSet; public class TempAreaMarker { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public String label; - public String world; - public double[] x; - public double[] z; - public String description; + public String label; + public String world; + public double[] x; + public double[] z; + public String description; - public int lineColor; - public double lineOpacity; - public int lineWeight; + public int lineColor; + public double lineOpacity; + public int lineWeight; - public int fillColor; - public double fillOpacity; + public int fillColor; + public double fillOpacity; - public boolean boost; + public boolean boost; - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // - public static boolean equals(AreaMarker marker, double[] x, double[] z) { - int length = marker.getCornerCount(); + public static boolean equals(AreaMarker marker, double[] x, double[] z) { + int length = marker.getCornerCount(); - if (x.length != length) { - return false; - } - if (z.length != length) { - return false; - } + if (x.length != length) { + return false; + } + if (z.length != length) { + return false; + } - for (int i = 0; i < length; i++) { - if (marker.getCornerX(i) != x[i]) { - return false; - } - if (marker.getCornerZ(i) != z[i]) { - return false; - } - } + for (int i = 0; i < length; i++) { + if (marker.getCornerX(i) != x[i]) { + return false; + } + if (marker.getCornerZ(i) != z[i]) { + return false; + } + } - return true; - } + return true; + } - // -------------------------------------------- // - // UPDATE - // -------------------------------------------- // + // -------------------------------------------- // + // UPDATE + // -------------------------------------------- // - public AreaMarker create(MarkerSet markerset, String markerId) { - AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent - ); + public AreaMarker create(MarkerSet markerset, String markerId) { + AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent + ); - if (ret == null) { - return null; - } + if (ret == null) { + return null; + } - // Description - ret.setDescription(this.description); + // Description + ret.setDescription(this.description); - // Line Style - ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + // Line Style + ret.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - // Fill Style - ret.setFillStyle(this.fillOpacity, this.fillColor); + // Fill Style + ret.setFillStyle(this.fillOpacity, this.fillColor); - // Boost Flag - ret.setBoostFlag(this.boost); + // Boost Flag + ret.setBoostFlag(this.boost); - return ret; - } + return ret; + } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - public void update(AreaMarker marker) { - // Corner Locations - if (!equals(marker, this.x, this.z)) { - marker.setCornerLocations(this.x, this.z); - } + public void update(AreaMarker marker) { + // Corner Locations + if (!equals(marker, this.x, this.z)) { + marker.setCornerLocations(this.x, this.z); + } - // Label - if (!marker.getLabel().equals(this.label)) { - marker.setLabel(this.label); - } + // Label + if (!marker.getLabel().equals(this.label)) { + marker.setLabel(this.label); + } - // Description - if (!marker.getDescription().equals(this.description)) { - marker.setDescription(this.description); - } + // Description + if (!marker.getDescription().equals(this.description)) { + marker.setDescription(this.description); + } - // Line Style - if (marker.getLineWeight() != this.lineWeight || - marker.getLineOpacity() != this.lineOpacity || - marker.getLineColor() != this.lineColor) { - marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); - } + // Line Style + if (marker.getLineWeight() != this.lineWeight || + marker.getLineOpacity() != this.lineOpacity || + marker.getLineColor() != this.lineColor) { + marker.setLineStyle(this.lineWeight, this.lineOpacity, this.lineColor); + } - // Fill Style - if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { - marker.setFillStyle(this.fillOpacity, this.fillColor); - } - // Boost Flag - if (marker.getBoostFlag() != this.boost) { - marker.setBoostFlag(this.boost); - } - } + // Fill Style + if ((marker.getFillOpacity() != this.fillOpacity) || (marker.getFillColor() != this.fillColor)) { + marker.setFillStyle(this.fillOpacity, this.fillColor); + } + // Boost Flag + if (marker.getBoostFlag() != this.boost) { + marker.setBoostFlag(this.boost); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java index b8eefdbe..d977ae9f 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarker.java @@ -7,68 +7,68 @@ import org.dynmap.markers.MarkerIcon; import org.dynmap.markers.MarkerSet; public class TempMarker { - // -------------------------------------------- // - // FIELDS - // -------------------------------------------- // + // -------------------------------------------- // + // FIELDS + // -------------------------------------------- // - public String label; - public String world; - public double x; - public double y; - public double z; - public String iconName; - public String description; + public String label; + public String world; + public double x; + public double y; + public double z; + public String iconName; + public String description; - // -------------------------------------------- // - // CREATE - // -------------------------------------------- // + // -------------------------------------------- // + // CREATE + // -------------------------------------------- // - public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) { - MarkerIcon ret = markerApi.getMarkerIcon(name); - if (ret == null) { - ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER); - } - return ret; - } + public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) { + MarkerIcon ret = markerApi.getMarkerIcon(name); + if (ret == null) { + ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER); + } + return ret; + } - // -------------------------------------------- // - // UPDATE - // -------------------------------------------- // + // -------------------------------------------- // + // UPDATE + // -------------------------------------------- // - public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) { - Marker ret = markerset.createMarker(markerId, this.label, this.world, this.x, this.y, this.z, getMarkerIcon(markerApi, this.iconName), false // not persistent - ); + public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) { + Marker ret = markerset.createMarker(markerId, this.label, this.world, this.x, this.y, this.z, getMarkerIcon(markerApi, this.iconName), false // not persistent + ); - if (ret == null) { - return null; - } + if (ret == null) { + return null; + } - ret.setDescription(this.description); + ret.setDescription(this.description); - return ret; - } + return ret; + } - // -------------------------------------------- // - // UTIL - // -------------------------------------------- // + // -------------------------------------------- // + // UTIL + // -------------------------------------------- // - public void update(MarkerAPI markerApi, Marker marker) { - if (!this.world.equals(marker.getWorld()) || this.x != marker.getX() || this.y != marker.getY() || this.z != marker.getZ()) { - marker.setLocation(this.world, this.x, this.y, this.z); - } + public void update(MarkerAPI markerApi, Marker marker) { + if (!this.world.equals(marker.getWorld()) || this.x != marker.getX() || this.y != marker.getY() || this.z != marker.getZ()) { + marker.setLocation(this.world, this.x, this.y, this.z); + } - if (!marker.getLabel().equals(this.label)) { - marker.setLabel(this.label); - } + if (!marker.getLabel().equals(this.label)) { + marker.setLabel(this.label); + } - MarkerIcon icon = getMarkerIcon(markerApi, this.iconName); - if (marker.getMarkerIcon() == null || marker.getMarkerIcon().equals(icon)) { - marker.setMarkerIcon(icon); - } + MarkerIcon icon = getMarkerIcon(markerApi, this.iconName); + if (marker.getMarkerIcon() == null || marker.getMarkerIcon().equals(icon)) { + marker.setMarkerIcon(icon); + } - if (!marker.getDescription().equals(this.description)) { - marker.setDescription(this.description); - } - } + if (!marker.getDescription().equals(this.description)) { + marker.setDescription(this.description); + } + } } diff --git a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java index 553bbde6..828a2f58 100644 --- a/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java +++ b/src/main/java/com/massivecraft/factions/integration/dynmap/TempMarkerSet.java @@ -5,51 +5,51 @@ import org.dynmap.markers.MarkerSet; public class TempMarkerSet { - public String label; - public int minimumZoom; - public int priority; - public boolean hideByDefault; + public String label; + public int minimumZoom; + public int priority; + public boolean hideByDefault; - public MarkerSet create(MarkerAPI markerApi, String id) { - MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not perisistent") + public MarkerSet create(MarkerAPI markerApi, String id) { + MarkerSet ret = markerApi.createMarkerSet(id, this.label, null, false); // ("null, false" at the end means "all icons allowed, not perisistent") - if (ret == null) { - return null; - } + if (ret == null) { + return null; + } - // Minimum Zoom - if (this.minimumZoom > 0) { - ret.setMinZoom(this.minimumZoom); - } + // Minimum Zoom + if (this.minimumZoom > 0) { + ret.setMinZoom(this.minimumZoom); + } - // Priority - ret.setLayerPriority(this.priority); + // Priority + ret.setLayerPriority(this.priority); - // Hide by Default - ret.setHideByDefault(this.hideByDefault); + // Hide by Default + ret.setHideByDefault(this.hideByDefault); - return ret; - } + return ret; + } - public void update(MarkerSet markerset) { - // Name - if (!markerset.getMarkerSetLabel().equals(this.label)) { - markerset.setMarkerSetLabel(this.label); - } + public void update(MarkerSet markerset) { + // Name + if (!markerset.getMarkerSetLabel().equals(this.label)) { + markerset.setMarkerSetLabel(this.label); + } - if (this.minimumZoom > 0) { - if (markerset.getMinZoom() != this.minimumZoom) { - markerset.setMinZoom(this.minimumZoom); - } - } + if (this.minimumZoom > 0) { + if (markerset.getMinZoom() != this.minimumZoom) { + markerset.setMinZoom(this.minimumZoom); + } + } - if (markerset.getLayerPriority() != this.priority) { - markerset.setLayerPriority(this.priority); - } + if (markerset.getLayerPriority() != this.priority) { + markerset.setLayerPriority(this.priority); + } - if (markerset.getHideByDefault() != this.hideByDefault) { - markerset.setHideByDefault(this.hideByDefault); - } - } + if (markerset.getHideByDefault() != this.hideByDefault) { + markerset.setHideByDefault(this.hideByDefault); + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java index 0d2ef465..1d7709b2 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsBlockListener.java @@ -33,490 +33,490 @@ import java.util.List; public class FactionsBlockListener implements Listener { - public static HashMap bannerLocations = new HashMap<>(); - private HashMap bannerCooldownMap = new HashMap<>(); + public static HashMap bannerLocations = new HashMap<>(); + private HashMap bannerCooldownMap = new HashMap<>(); - public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) { - String name = player.getName(); - - if (Conf.playersWhoBypassAllProtection.contains(name)) - return true; - - FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); - if (me.isAdminBypassing()) - return true; - - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getInstance().getFactionAt(loc); - - if (otherFaction.isWilderness()) { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; - - if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) - return true; // This is not faction territory. Use whatever you like here. - - if (!justCheck) - me.msg("You can't " + action + " in the wilderness."); - - return false; - } else if (otherFaction.isSafeZone()) { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; - - if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) - return true; - - if (!justCheck) - me.msg("You can't " + action + " in a safe zone."); - - return false; - } else if (otherFaction.isWarZone()) { - if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) - return true; - - if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) - return true; - - if (!justCheck) - me.msg("You can't " + action + " in a war zone."); - - return false; - } - - if (SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) - return true; - - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - boolean online = otherFaction.hasPlayersOnline(); - boolean pain = !justCheck && rel.confPainBuild(online); - boolean deny = rel.confDenyBuild(online); - - Access access = otherFaction.getAccess(me, PermissableAction.fromString(action)); - if (access == Access.ALLOW && ((rel == Relation.ALLY) || (rel == Relation.ENEMY) || (rel == Relation.NEUTRAL) || (rel == Relation.TRUCE))) - deny = false; - - // hurt the player for building/destroying in other territory? - if (pain) { - player.damage(Conf.actionDeniedPainAmount); - - if (!deny) { - me.msg("It is painful to try to " + action + " in the territory of " + otherFaction.getTag(myFaction)); - } - } - - - // cancel building/destroying in other territory? - if (deny) { - if (!justCheck) { - me.msg("You can't " + action + " in the territory of " + otherFaction.getTag(myFaction)); - } - - return false; - } - - // Also cancel and/or cause pain if player doesn't have ownership rights for this claim - if (Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc)) { - if (!pain && Conf.ownedAreaPainBuild && !justCheck) { - player.damage(Conf.actionDeniedPainAmount); - if (!Conf.ownedAreaDenyBuild) { - me.msg("It is painful to try to " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); - } - } - if (Conf.ownedAreaDenyBuild) { - if (!justCheck) { - me.msg("You can't " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); - return false; - } - } - } - - // Check the permission just after making sure the land isn't owned by someone else to avoid bypass. - - if (access != Access.ALLOW && me.getRole() != Role.LEADER) { - // TODO: Update this once new access values are added other than just allow / deny. - if (access == Access.DENY) { - if (!justCheck) - me.msg(TL.GENERIC_NOPERMISSION, action); - return false; - } else if (myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && !myFaction.getOwnerListString(loc).contains(player.getName())) { - if (!justCheck) - me.msg("You can't " + action + " in this territory, it is owned by: " + myFaction.getOwnerListString(loc)); - return false; - } - } - return true; - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - if (!event.canBuild()) { - return; - } - - // special case for flint&steel, which should only be prevented by DenyUsage list - if (event.getBlockPlaced().getType() == Material.FIRE) { - return; - } - - if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockFromTo(BlockFromToEvent event) { - if (!Conf.handleExploitLiquidFlow) { - return; - } - if (event.getBlock().isLiquid()) { - if (event.getToBlock().isEmpty()) { - Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock())); - if (from == to) { - // not concerned with inter-faction events - return; - } - // from faction != to faction - if (to.isNormal()) { - if (from.isNormal() && from.getRelationTo(to).isAlly()) { - return; - } - event.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockDamage(BlockDamageEvent event) { - if (event.getInstaBreak() && !playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPistonExtend(BlockPistonExtendEvent event) { - if (!Conf.pistonProtectionThroughDenyBuild) { - return; - } - - Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - - // target end-of-the-line empty (air) block which is being pushed into, including if piston itself would extend into air - Block targetBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1); - - // if potentially pushing into air/water/lava in another territory, we need to check it out - if ((targetBlock.isEmpty() || targetBlock.isLiquid()) && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation())) { - event.setCancelled(true); - } - - /* - * note that I originally was testing the territory of each affected block, but since I found that pistons can only push - * up to 12 blocks and the width of any territory is 16 blocks, it should be safe (and much more lightweight) to test - * only the final target block as done above - */ - } - - @EventHandler - public void onVaultPlace(BlockPlaceEvent e) { - if (e.getItemInHand().getType() == Material.CHEST) { - ItemStack vault = SavageFactions.plugin.createItem(Material.CHEST, 1, (short) 0, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fvault.Item.Name")), SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fvault.Item.Lore"))); - if (e.getItemInHand().isSimilar(vault)) { - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - if (fme.getFaction().getVault() != null) { - fme.msg(TL.COMMAND_GETVAULT_ALREADYSET); - e.setCancelled(true); - return; - } - FLocation flocation = new FLocation(e.getBlockPlaced().getLocation()); - if (Board.getInstance().getFactionAt(flocation) != fme.getFaction()) { - fme.msg(TL.COMMAND_GETVAULT_INVALIDLOCATION); - e.setCancelled(true); - return; - } - Block start = e.getBlockPlaced(); - int radius = 1; - for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) { - for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) { - for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) { - Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); - if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) { - continue; - } - - Material blockMaterial = blockLoc.getBlock().getType(); - - if (blockMaterial == Material.CHEST || (SavageFactions.plugin.getConfig().getBoolean("fvault.No-Hoppers-near-vault") && blockMaterial == Material.HOPPER)) { - e.setCancelled(true); - fme.msg(TL.COMMAND_GETVAULT_CHESTNEAR); - return; - } - } - } - } - - fme.msg(TL.COMMAND_GETVAULT_SUCCESS); - fme.getFaction().setVault(e.getBlockPlaced().getLocation()); - - } - } - } - - @EventHandler - public void onHopperPlace(BlockPlaceEvent e) { - - if (e.getItemInHand().getType() != Material.HOPPER && !SavageFactions.plugin.getConfig().getBoolean("fvault.No-Hoppers-near-vault")) { - return; - } - - Faction factionAt = Board.getInstance().getFactionAt(new FLocation(e.getBlockPlaced().getLocation())); - - if (factionAt.isWilderness() || factionAt.getVault() == null) { - return; - } - - - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - - Block start = e.getBlockPlaced(); - int radius = 1; - for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) { - for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) { - for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) { - Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); - if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) { - continue; - } - - if (blockLoc.getBlock().getType() == Material.CHEST) { - if (factionAt.getVault().equals(blockLoc)) { - e.setCancelled(true); - fme.msg(TL.COMMAND_VAULT_NO_HOPPER); - return; - } - } - } - } - } - - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockPistonRetract(BlockPistonRetractEvent event) { - // if not a sticky piston, retraction should be fine - if (!event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) { - return; - } - - Location targetLoc = event.getRetractLocation(); - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(targetLoc)); - - // Check if the piston is moving in a faction's territory. This disables pistons entirely in faction territory. - if (otherFaction.isNormal() && SavageFactions.plugin.getConfig().getBoolean("disable-pistons-in-territory", false)) { - event.setCancelled(true); - return; - } - - // if potentially retracted block is just air/water/lava, no worries - if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) { - return; - } - - Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); - - if (!canPistonMoveBlock(pistonFaction, targetLoc)) { - event.setCancelled(true); - } - } - - @EventHandler - public void onBannerPlace(BlockPlaceEvent e) { - if (SavageFactions.plugin.mc17) { - return; - } - - if (e.getItemInHand().getType() == SavageFactions.plugin.BANNER) { - ItemStack bannerInHand = e.getItemInHand(); - FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); - ItemStack warBanner = fme.getFaction().getBanner(); - if (warBanner != null) { - ItemMeta warmeta = warBanner.getItemMeta(); - warmeta.setDisplayName(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"))); - warmeta.setLore(SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore"))); - warBanner.setItemMeta(warmeta); - } else { - warBanner = SavageFactions.plugin.createItem(SavageFactions.plugin.BANNER, 1, (short) 1, SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"), SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore")); - } - if (warBanner.isSimilar(bannerInHand)) { - - if (fme.getFaction().isWilderness()) { - fme.msg(TL.WARBANNER_NOFACTION); - e.setCancelled(true); - return; - } - int bannerTime = SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Time") * 20; - - Location placedLoc = e.getBlockPlaced().getLocation(); - FLocation fplacedLoc = new FLocation(placedLoc); - if ((Board.getInstance().getFactionAt(fplacedLoc).isWarZone() && SavageFactions.plugin.getConfig().getBoolean("fbanners.Placeable.Warzone")) - || (fme.getFaction().getRelationTo(Board.getInstance().getFactionAt(fplacedLoc)) == Relation.ENEMY) && SavageFactions.plugin.getConfig().getBoolean("fbanners.Placeable.Enemy")) { - if (bannerCooldownMap.containsKey(fme.getTag())) { - fme.msg(TL.WARBANNER_COOLDOWN); - e.setCancelled(true); - return; - } - for (FPlayer fplayer : fme.getFaction().getFPlayers()) { - // if (fplayer == fme) { continue; } //Idk if I wanna not send the title to the player - fplayer.getPlayer().sendTitle(SavageFactions.plugin.color(fme.getTag() + " Placed A WarBanner!"), SavageFactions.plugin.color("&7use &c/f tpbanner&7 to tp to the banner!"), 10, 70, 20); - } - - bannerCooldownMap.put(fme.getTag(), true); - bannerLocations.put(fme.getTag(), e.getBlockPlaced().getLocation()); - final int bannerCooldown = SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Place-Cooldown"); - final ArmorStand as = (ArmorStand) e.getBlockPlaced().getLocation().add(0.5, 1, 0.5).getWorld().spawnEntity(e.getBlockPlaced().getLocation().add(0.5, 1, 0.5), EntityType.ARMOR_STAND); //Spawn the ArmorStand - as.setVisible(false); //Makes the ArmorStand invisible - as.setGravity(false); //Make sure it doesn't fall - as.setCanPickupItems(false); //I'm not sure what happens if you leave this as it is, but you might as well disable it - as.setCustomName(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fbanners.BannerHolo").replace("{Faction}", fme.getTag()))); //Set this to the text you want - as.setCustomNameVisible(true); //This makes the text appear no matter if your looking at the entity or not - final ArmorStand armorStand = as; - final String tag = fme.getTag(); - Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - bannerCooldownMap.remove(tag); - } - }, Long.parseLong(bannerCooldown + "")); - final Block banner = e.getBlockPlaced(); - final Material bannerType = banner.getType(); - final Faction bannerFaction = fme.getFaction(); - banner.getWorld().strikeLightningEffect(banner.getLocation()); - // e.getPlayer().getWorld().playSound(e.getPlayer().getLocation(), Sound.ENTITY_LIGHTNING_IMPACT,2.0F,0.5F); - final int radius = SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Effect-Radius"); - final List effects = SavageFactions.plugin.getConfig().getStringList("fbanners.Effects"); - final int affectorTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - - for (Entity e : banner.getLocation().getWorld().getNearbyEntities(banner.getLocation(), radius, 255, radius)) { - if (e instanceof Player) { - Player player = (Player) e; - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fplayer.getFaction() == bannerFaction) { - for (String effect : effects) { - String[] components = effect.split(":"); - player.addPotionEffect(new PotionEffect(PotionEffectType.getByName(components[0]), 100, Integer.parseInt(components[1]))); - } - ParticleEffect.LAVA.display(1, 1, 1, 1, 10, banner.getLocation(), 16); - ParticleEffect.FLAME.display(1, 1, 1, 1, 10, banner.getLocation(), 16); - - if (banner.getType() != bannerType) { - banner.setType(bannerType); - } - } - } - } - } - }, 0L, 20L); - Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - banner.setType(Material.AIR); - as.remove(); - banner.getWorld().strikeLightningEffect(banner.getLocation()); - Bukkit.getScheduler().cancelTask(affectorTask); - bannerLocations.remove(bannerFaction.getTag()); - } - }, Long.parseLong(bannerTime + "")); - } else { - fme.msg(TL.WARBANNER_INVALIDLOC); - e.setCancelled(true); - } - } - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onFrostWalker(EntityBlockFormEvent event) { - if (event.getEntity() == null || event.getEntity().getType() != EntityType.PLAYER || event.getBlock() == null) { - return; - } - - Player player = (Player) event.getEntity(); - Location location = event.getBlock().getLocation(); - - // only notify every 10 seconds - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis(); - if (!justCheck) { - fPlayer.setLastFrostwalkerMessage(); - } - - // Check if they have build permissions here. If not, block this from happening. - if (!playerCanBuildDestroyBlock(player, location, "frostwalk", justCheck)) { - event.setCancelled(true); - } - } - - private boolean canPistonMoveBlock(Faction pistonFaction, Location target) { - - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(target)); - - if (pistonFaction == otherFaction) { - return true; - } - - if (otherFaction.isWilderness()) { - return !Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName()); - - } else if (otherFaction.isSafeZone()) { - return !Conf.safeZoneDenyBuild; - - } else if (otherFaction.isWarZone()) { - return !Conf.warZoneDenyBuild; - - } - - Relation rel = pistonFaction.getRelationTo(otherFaction); - - return !rel.confDenyBuild(otherFaction.hasPlayersOnline()); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { - event.setCancelled(true); - return; - } - FPlayer fme = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (!fme.hasFaction()) { - return; - } - if (event.getBlock().getType() == SavageFactions.plugin.MOB_SPANWER) { - if (!fme.isAdminBypassing()) { - Access access = fme.getFaction().getAccess(fme, PermissableAction.SPAWNER); - if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { - fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "mine spawners"); - return; - } - } - } - } - - @EventHandler - public void onFarmLandDamage(EntityChangeBlockEvent event) { - if (event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - if (!playerCanBuildDestroyBlock(player, event.getBlock().getLocation(), PermissableAction.DESTROY.name(), true)) { - FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())); - Faction myFaction = me.getFaction(); - - me.msg("You can't jump on farmland in the territory of " + otherFaction.getTag(myFaction)); - event.setCancelled(true); - } - } - } + public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) { + String name = player.getName(); + + if (Conf.playersWhoBypassAllProtection.contains(name)) + return true; + + FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); + if (me.isAdminBypassing()) + return true; + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + + if (otherFaction.isWilderness()) { + if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) + return true; + + if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) + return true; // This is not faction territory. Use whatever you like here. + + if (!justCheck) + me.msg("You can't " + action + " in the wilderness."); + + return false; + } else if (otherFaction.isSafeZone()) { + if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) + return true; + + if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) + return true; + + if (!justCheck) + me.msg("You can't " + action + " in a safe zone."); + + return false; + } else if (otherFaction.isWarZone()) { + if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) + return true; + + if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) + return true; + + if (!justCheck) + me.msg("You can't " + action + " in a war zone."); + + return false; + } + + if (SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) + return true; + + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + boolean online = otherFaction.hasPlayersOnline(); + boolean pain = !justCheck && rel.confPainBuild(online); + boolean deny = rel.confDenyBuild(online); + + Access access = otherFaction.getAccess(me, PermissableAction.fromString(action)); + if (access == Access.ALLOW && ((rel == Relation.ALLY) || (rel == Relation.ENEMY) || (rel == Relation.NEUTRAL) || (rel == Relation.TRUCE))) + deny = false; + + // hurt the player for building/destroying in other territory? + if (pain) { + player.damage(Conf.actionDeniedPainAmount); + + if (!deny) { + me.msg("It is painful to try to " + action + " in the territory of " + otherFaction.getTag(myFaction)); + } + } + + + // cancel building/destroying in other territory? + if (deny) { + if (!justCheck) { + me.msg("You can't " + action + " in the territory of " + otherFaction.getTag(myFaction)); + } + + return false; + } + + // Also cancel and/or cause pain if player doesn't have ownership rights for this claim + if (Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc)) { + if (!pain && Conf.ownedAreaPainBuild && !justCheck) { + player.damage(Conf.actionDeniedPainAmount); + if (!Conf.ownedAreaDenyBuild) { + me.msg("It is painful to try to " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); + } + } + if (Conf.ownedAreaDenyBuild) { + if (!justCheck) { + me.msg("You can't " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); + return false; + } + } + } + + // Check the permission just after making sure the land isn't owned by someone else to avoid bypass. + + if (access != Access.ALLOW && me.getRole() != Role.LEADER) { + // TODO: Update this once new access values are added other than just allow / deny. + if (access == Access.DENY) { + if (!justCheck) + me.msg(TL.GENERIC_NOPERMISSION, action); + return false; + } else if (myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && !myFaction.getOwnerListString(loc).contains(player.getName())) { + if (!justCheck) + me.msg("You can't " + action + " in this territory, it is owned by: " + myFaction.getOwnerListString(loc)); + return false; + } + } + return true; + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + if (!event.canBuild()) { + return; + } + + // special case for flint&steel, which should only be prevented by DenyUsage list + if (event.getBlockPlaced().getType() == Material.FIRE) { + return; + } + + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "build", false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockFromTo(BlockFromToEvent event) { + if (!Conf.handleExploitLiquidFlow) { + return; + } + if (event.getBlock().isLiquid()) { + if (event.getToBlock().isEmpty()) { + Faction from = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + Faction to = Board.getInstance().getFactionAt(new FLocation(event.getToBlock())); + if (from == to) { + // not concerned with inter-faction events + return; + } + // from faction != to faction + if (to.isNormal()) { + if (from.isNormal() && from.getRelationTo(to).isAlly()) { + return; + } + event.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockDamage(BlockDamageEvent event) { + if (event.getInstaBreak() && !playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + if (!Conf.pistonProtectionThroughDenyBuild) { + return; + } + + Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + + // target end-of-the-line empty (air) block which is being pushed into, including if piston itself would extend into air + Block targetBlock = event.getBlock().getRelative(event.getDirection(), event.getLength() + 1); + + // if potentially pushing into air/water/lava in another territory, we need to check it out + if ((targetBlock.isEmpty() || targetBlock.isLiquid()) && !canPistonMoveBlock(pistonFaction, targetBlock.getLocation())) { + event.setCancelled(true); + } + + /* + * note that I originally was testing the territory of each affected block, but since I found that pistons can only push + * up to 12 blocks and the width of any territory is 16 blocks, it should be safe (and much more lightweight) to test + * only the final target block as done above + */ + } + + @EventHandler + public void onVaultPlace(BlockPlaceEvent e) { + if (e.getItemInHand().getType() == Material.CHEST) { + ItemStack vault = SavageFactions.plugin.createItem(Material.CHEST, 1, (short) 0, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fvault.Item.Name")), SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fvault.Item.Lore"))); + if (e.getItemInHand().isSimilar(vault)) { + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + if (fme.getFaction().getVault() != null) { + fme.msg(TL.COMMAND_GETVAULT_ALREADYSET); + e.setCancelled(true); + return; + } + FLocation flocation = new FLocation(e.getBlockPlaced().getLocation()); + if (Board.getInstance().getFactionAt(flocation) != fme.getFaction()) { + fme.msg(TL.COMMAND_GETVAULT_INVALIDLOCATION); + e.setCancelled(true); + return; + } + Block start = e.getBlockPlaced(); + int radius = 1; + for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) { + for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) { + for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) { + Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); + if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) { + continue; + } + + Material blockMaterial = blockLoc.getBlock().getType(); + + if (blockMaterial == Material.CHEST || (SavageFactions.plugin.getConfig().getBoolean("fvault.No-Hoppers-near-vault") && blockMaterial == Material.HOPPER)) { + e.setCancelled(true); + fme.msg(TL.COMMAND_GETVAULT_CHESTNEAR); + return; + } + } + } + } + + fme.msg(TL.COMMAND_GETVAULT_SUCCESS); + fme.getFaction().setVault(e.getBlockPlaced().getLocation()); + + } + } + } + + @EventHandler + public void onHopperPlace(BlockPlaceEvent e) { + + if (e.getItemInHand().getType() != Material.HOPPER && !SavageFactions.plugin.getConfig().getBoolean("fvault.No-Hoppers-near-vault")) { + return; + } + + Faction factionAt = Board.getInstance().getFactionAt(new FLocation(e.getBlockPlaced().getLocation())); + + if (factionAt.isWilderness() || factionAt.getVault() == null) { + return; + } + + + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + + Block start = e.getBlockPlaced(); + int radius = 1; + for (double x = start.getLocation().getX() - radius; x <= start.getLocation().getX() + radius; x++) { + for (double y = start.getLocation().getY() - radius; y <= start.getLocation().getY() + radius; y++) { + for (double z = start.getLocation().getZ() - radius; z <= start.getLocation().getZ() + radius; z++) { + Location blockLoc = new Location(e.getPlayer().getWorld(), x, y, z); + if (blockLoc.getX() == start.getLocation().getX() && blockLoc.getY() == start.getLocation().getY() && blockLoc.getZ() == start.getLocation().getZ()) { + continue; + } + + if (blockLoc.getBlock().getType() == Material.CHEST) { + if (factionAt.getVault().equals(blockLoc)) { + e.setCancelled(true); + fme.msg(TL.COMMAND_VAULT_NO_HOPPER); + return; + } + } + } + } + } + + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + // if not a sticky piston, retraction should be fine + if (!event.isSticky() || !Conf.pistonProtectionThroughDenyBuild) { + return; + } + + Location targetLoc = event.getRetractLocation(); + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(targetLoc)); + + // Check if the piston is moving in a faction's territory. This disables pistons entirely in faction territory. + if (otherFaction.isNormal() && SavageFactions.plugin.getConfig().getBoolean("disable-pistons-in-territory", false)) { + event.setCancelled(true); + return; + } + + // if potentially retracted block is just air/water/lava, no worries + if (targetLoc.getBlock().isEmpty() || targetLoc.getBlock().isLiquid()) { + return; + } + + Faction pistonFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock())); + + if (!canPistonMoveBlock(pistonFaction, targetLoc)) { + event.setCancelled(true); + } + } + + @EventHandler + public void onBannerPlace(BlockPlaceEvent e) { + if (SavageFactions.plugin.mc17) { + return; + } + + if (e.getItemInHand().getType() == SavageFactions.plugin.BANNER) { + ItemStack bannerInHand = e.getItemInHand(); + FPlayer fme = FPlayers.getInstance().getByPlayer(e.getPlayer()); + ItemStack warBanner = fme.getFaction().getBanner(); + if (warBanner != null) { + ItemMeta warmeta = warBanner.getItemMeta(); + warmeta.setDisplayName(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"))); + warmeta.setLore(SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore"))); + warBanner.setItemMeta(warmeta); + } else { + warBanner = SavageFactions.plugin.createItem(SavageFactions.plugin.BANNER, 1, (short) 1, SavageFactions.plugin.getConfig().getString("fbanners.Item.Name"), SavageFactions.plugin.getConfig().getStringList("fbanners.Item.Lore")); + } + if (warBanner.isSimilar(bannerInHand)) { + + if (fme.getFaction().isWilderness()) { + fme.msg(TL.WARBANNER_NOFACTION); + e.setCancelled(true); + return; + } + int bannerTime = SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Time") * 20; + + Location placedLoc = e.getBlockPlaced().getLocation(); + FLocation fplacedLoc = new FLocation(placedLoc); + if ((Board.getInstance().getFactionAt(fplacedLoc).isWarZone() && SavageFactions.plugin.getConfig().getBoolean("fbanners.Placeable.Warzone")) + || (fme.getFaction().getRelationTo(Board.getInstance().getFactionAt(fplacedLoc)) == Relation.ENEMY) && SavageFactions.plugin.getConfig().getBoolean("fbanners.Placeable.Enemy")) { + if (bannerCooldownMap.containsKey(fme.getTag())) { + fme.msg(TL.WARBANNER_COOLDOWN); + e.setCancelled(true); + return; + } + for (FPlayer fplayer : fme.getFaction().getFPlayers()) { + // if (fplayer == fme) { continue; } //Idk if I wanna not send the title to the player + fplayer.getPlayer().sendTitle(SavageFactions.plugin.color(fme.getTag() + " Placed A WarBanner!"), SavageFactions.plugin.color("&7use &c/f tpbanner&7 to tp to the banner!"), 10, 70, 20); + } + + bannerCooldownMap.put(fme.getTag(), true); + bannerLocations.put(fme.getTag(), e.getBlockPlaced().getLocation()); + final int bannerCooldown = SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Place-Cooldown"); + final ArmorStand as = (ArmorStand) e.getBlockPlaced().getLocation().add(0.5, 1, 0.5).getWorld().spawnEntity(e.getBlockPlaced().getLocation().add(0.5, 1, 0.5), EntityType.ARMOR_STAND); //Spawn the ArmorStand + as.setVisible(false); //Makes the ArmorStand invisible + as.setGravity(false); //Make sure it doesn't fall + as.setCanPickupItems(false); //I'm not sure what happens if you leave this as it is, but you might as well disable it + as.setCustomName(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fbanners.BannerHolo").replace("{Faction}", fme.getTag()))); //Set this to the text you want + as.setCustomNameVisible(true); //This makes the text appear no matter if your looking at the entity or not + final ArmorStand armorStand = as; + final String tag = fme.getTag(); + Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + bannerCooldownMap.remove(tag); + } + }, Long.parseLong(bannerCooldown + "")); + final Block banner = e.getBlockPlaced(); + final Material bannerType = banner.getType(); + final Faction bannerFaction = fme.getFaction(); + banner.getWorld().strikeLightningEffect(banner.getLocation()); + // e.getPlayer().getWorld().playSound(e.getPlayer().getLocation(), Sound.ENTITY_LIGHTNING_IMPACT,2.0F,0.5F); + final int radius = SavageFactions.plugin.getConfig().getInt("fbanners.Banner-Effect-Radius"); + final List effects = SavageFactions.plugin.getConfig().getStringList("fbanners.Effects"); + final int affectorTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + + for (Entity e : banner.getLocation().getWorld().getNearbyEntities(banner.getLocation(), radius, 255, radius)) { + if (e instanceof Player) { + Player player = (Player) e; + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer.getFaction() == bannerFaction) { + for (String effect : effects) { + String[] components = effect.split(":"); + player.addPotionEffect(new PotionEffect(PotionEffectType.getByName(components[0]), 100, Integer.parseInt(components[1]))); + } + ParticleEffect.LAVA.display(1, 1, 1, 1, 10, banner.getLocation(), 16); + ParticleEffect.FLAME.display(1, 1, 1, 1, 10, banner.getLocation(), 16); + + if (banner.getType() != bannerType) { + banner.setType(bannerType); + } + } + } + } + } + }, 0L, 20L); + Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + banner.setType(Material.AIR); + as.remove(); + banner.getWorld().strikeLightningEffect(banner.getLocation()); + Bukkit.getScheduler().cancelTask(affectorTask); + bannerLocations.remove(bannerFaction.getTag()); + } + }, Long.parseLong(bannerTime + "")); + } else { + fme.msg(TL.WARBANNER_INVALIDLOC); + e.setCancelled(true); + } + } + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onFrostWalker(EntityBlockFormEvent event) { + if (event.getEntity() == null || event.getEntity().getType() != EntityType.PLAYER || event.getBlock() == null) { + return; + } + + Player player = (Player) event.getEntity(); + Location location = event.getBlock().getLocation(); + + // only notify every 10 seconds + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + boolean justCheck = fPlayer.getLastFrostwalkerMessage() + 10000 > System.currentTimeMillis(); + if (!justCheck) { + fPlayer.setLastFrostwalkerMessage(); + } + + // Check if they have build permissions here. If not, block this from happening. + if (!playerCanBuildDestroyBlock(player, location, "frostwalk", justCheck)) { + event.setCancelled(true); + } + } + + private boolean canPistonMoveBlock(Faction pistonFaction, Location target) { + + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(target)); + + if (pistonFaction == otherFaction) { + return true; + } + + if (otherFaction.isWilderness()) { + return !Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(target.getWorld().getName()); + + } else if (otherFaction.isSafeZone()) { + return !Conf.safeZoneDenyBuild; + + } else if (otherFaction.isWarZone()) { + return !Conf.warZoneDenyBuild; + + } + + Relation rel = pistonFaction.getRelationTo(otherFaction); + + return !rel.confDenyBuild(otherFaction.hasPlayersOnline()); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onBlockBreak(BlockBreakEvent event) { + if (!playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "destroy", false)) { + event.setCancelled(true); + return; + } + FPlayer fme = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (!fme.hasFaction()) { + return; + } + if (event.getBlock().getType() == SavageFactions.plugin.MOB_SPANWER) { + if (!fme.isAdminBypassing()) { + Access access = fme.getFaction().getAccess(fme, PermissableAction.SPAWNER); + if (access != Access.ALLOW && fme.getRole() != Role.LEADER) { + fme.msg(TL.GENERIC_FPERM_NOPERMISSION, "mine spawners"); + return; + } + } + } + } + + @EventHandler + public void onFarmLandDamage(EntityChangeBlockEvent event) { + if (event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + if (!playerCanBuildDestroyBlock(player, event.getBlock().getLocation(), PermissableAction.DESTROY.name(), true)) { + FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString()); + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(event.getBlock().getLocation())); + Faction myFaction = me.getFaction(); + + me.msg("You can't jump on farmland in the territory of " + otherFaction.getTag(myFaction)); + event.setCancelled(true); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java index ff710b86..36505c0c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsChatListener.java @@ -19,192 +19,192 @@ import java.util.logging.Level; public class FactionsChatListener implements Listener { - // this is for handling slashless command usage and faction/alliance chat, set at lowest priority so Factions gets to them first - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerEarlyChat(AsyncPlayerChatEvent event) { - Player talkingPlayer = event.getPlayer(); - String msg = event.getMessage(); - FPlayer me = FPlayers.getInstance().getByPlayer(talkingPlayer); - ChatMode chat = me.getChatMode(); - // Is the player entering a password for a warp? - if (me.isEnteringPassword()) { - event.setCancelled(true); - me.sendMessage(ChatColor.DARK_GRAY + event.getMessage().replaceAll("(?s).", "*")); - if (me.getFaction().isWarpPassword(me.getEnteringWarp(), event.getMessage())) { - doWarmup(me.getEnteringWarp(), me); - } else { - // Invalid Password - me.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); - } - me.setEnteringPassword(false, ""); - return; - } + // this is for handling slashless command usage and faction/alliance chat, set at lowest priority so Factions gets to them first + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerEarlyChat(AsyncPlayerChatEvent event) { + Player talkingPlayer = event.getPlayer(); + String msg = event.getMessage(); + FPlayer me = FPlayers.getInstance().getByPlayer(talkingPlayer); + ChatMode chat = me.getChatMode(); + // Is the player entering a password for a warp? + if (me.isEnteringPassword()) { + event.setCancelled(true); + me.sendMessage(ChatColor.DARK_GRAY + event.getMessage().replaceAll("(?s).", "*")); + if (me.getFaction().isWarpPassword(me.getEnteringWarp(), event.getMessage())) { + doWarmup(me.getEnteringWarp(), me); + } else { + // Invalid Password + me.msg(TL.COMMAND_FWARP_INVALID_PASSWORD); + } + me.setEnteringPassword(false, ""); + return; + } - //Is it a MOD chat - if (chat == ChatMode.MOD) { - Faction myFaction = me.getFaction(); + //Is it a MOD chat + if (chat == ChatMode.MOD) { + Faction myFaction = me.getFaction(); - String message = String.format(Conf.modChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); + String message = String.format(Conf.modChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); - //Send to all mods - if (me.getRole().isAtLeast(Role.MODERATOR)) { - // Iterates only through the factions' members so we enhance performance. - for (FPlayer fplayer : myFaction.getFPlayers()) { - if (fplayer.getRole().isAtLeast(Role.MODERATOR)) { - fplayer.sendMessage(message); - } else if (fplayer.isSpyingChat() && me != fplayer) { - fplayer.sendMessage("[MCspy]: " + message); - } - } - } else { - // Just in case player gets demoted while in faction chat. - me.msg(TL.COMMAND_CHAT_MOD_ONLY); - event.setCancelled(true); - return; - } + //Send to all mods + if (me.getRole().isAtLeast(Role.MODERATOR)) { + // Iterates only through the factions' members so we enhance performance. + for (FPlayer fplayer : myFaction.getFPlayers()) { + if (fplayer.getRole().isAtLeast(Role.MODERATOR)) { + fplayer.sendMessage(message); + } else if (fplayer.isSpyingChat() && me != fplayer) { + fplayer.sendMessage("[MCspy]: " + message); + } + } + } else { + // Just in case player gets demoted while in faction chat. + me.msg(TL.COMMAND_CHAT_MOD_ONLY); + event.setCancelled(true); + return; + } - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("Mod Chat: " + message)); + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("Mod Chat: " + message)); - event.setCancelled(true); - } else if (chat == ChatMode.FACTION) { - Faction myFaction = me.getFaction(); + event.setCancelled(true); + } else if (chat == ChatMode.FACTION) { + Faction myFaction = me.getFaction(); - String message = String.format(Conf.factionChatFormat, me.describeTo(myFaction), msg); - myFaction.sendMessage(message); + String message = String.format(Conf.factionChatFormat, me.describeTo(myFaction), msg); + myFaction.sendMessage(message); - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("FactionChat " + myFaction.getTag() + ": " + message)); + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("FactionChat " + myFaction.getTag() + ": " + message)); - //Send to any players who are spying chat - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (fplayer.isSpyingChat() && fplayer.getFaction() != myFaction && me != fplayer) { - fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + message); - } - } + //Send to any players who are spying chat + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (fplayer.isSpyingChat() && fplayer.getFaction() != myFaction && me != fplayer) { + fplayer.sendMessage("[FCspy] " + myFaction.getTag() + ": " + message); + } + } - event.setCancelled(true); - } else if (chat == ChatMode.ALLIANCE) { - Faction myFaction = me.getFaction(); + event.setCancelled(true); + } else if (chat == ChatMode.ALLIANCE) { + Faction myFaction = me.getFaction(); - String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); + String message = String.format(Conf.allianceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); - //Send message to our own faction - myFaction.sendMessage(message); + //Send message to our own faction + myFaction.sendMessage(message); - //Send to all our allies - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (myFaction.getRelationTo(fplayer) == Relation.ALLY && !fplayer.isIgnoreAllianceChat()) { - fplayer.sendMessage(message); - } else if (fplayer.isSpyingChat() && me != fplayer) { - fplayer.sendMessage("[ACspy]: " + message); - } - } + //Send to all our allies + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (myFaction.getRelationTo(fplayer) == Relation.ALLY && !fplayer.isIgnoreAllianceChat()) { + fplayer.sendMessage(message); + } else if (fplayer.isSpyingChat() && me != fplayer) { + fplayer.sendMessage("[ACspy]: " + message); + } + } - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("AllianceChat: " + message)); - event.setCancelled(true); - } else if (chat == ChatMode.TRUCE) { - Faction myFaction = me.getFaction(); + event.setCancelled(true); + } else if (chat == ChatMode.TRUCE) { + Faction myFaction = me.getFaction(); - String message = String.format(Conf.truceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); + String message = String.format(Conf.truceChatFormat, ChatColor.stripColor(me.getNameAndTag()), msg); - //Send message to our own faction - myFaction.sendMessage(message); + //Send message to our own faction + myFaction.sendMessage(message); - //Send to all our truces - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - if (myFaction.getRelationTo(fplayer) == Relation.TRUCE) { - fplayer.sendMessage(message); - } else if (fplayer.isSpyingChat() && fplayer != me) { - fplayer.sendMessage("[TCspy]: " + message); - } - } + //Send to all our truces + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + if (myFaction.getRelationTo(fplayer) == Relation.TRUCE) { + fplayer.sendMessage(message); + } else if (fplayer.isSpyingChat() && fplayer != me) { + fplayer.sendMessage("[TCspy]: " + message); + } + } - Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("TruceChat: " + message)); - event.setCancelled(true); - } - } + Bukkit.getLogger().log(Level.INFO, ChatColor.stripColor("TruceChat: " + message)); + event.setCancelled(true); + } + } - // this is for handling insertion of the player's faction tag, set at highest priority to give other plugins a chance to modify chat first - @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) { - // Are we to insert the Faction tag into the format? - // If we are not to insert it - we are done. - if (!Conf.chatTagEnabled || Conf.chatTagHandledByAnotherPlugin) { - return; - } + // this is for handling insertion of the player's faction tag, set at highest priority to give other plugins a chance to modify chat first + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerChat(AsyncPlayerChatEvent event) { + // Are we to insert the Faction tag into the format? + // If we are not to insert it - we are done. + if (!Conf.chatTagEnabled || Conf.chatTagHandledByAnotherPlugin) { + return; + } - Player talkingPlayer = event.getPlayer(); - String msg = event.getMessage(); - String eventFormat = event.getFormat(); - FPlayer me = FPlayers.getInstance().getByPlayer(talkingPlayer); - int InsertIndex; + Player talkingPlayer = event.getPlayer(); + String msg = event.getMessage(); + String eventFormat = event.getFormat(); + FPlayer me = FPlayers.getInstance().getByPlayer(talkingPlayer); + int InsertIndex; - if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString)) { - // we're using the "replace" method of inserting the faction tags - if (eventFormat.contains("[FACTION_TITLE]")) { - eventFormat = eventFormat.replace("[FACTION_TITLE]", me.getTitle()); - } + if (!Conf.chatTagReplaceString.isEmpty() && eventFormat.contains(Conf.chatTagReplaceString)) { + // we're using the "replace" method of inserting the faction tags + if (eventFormat.contains("[FACTION_TITLE]")) { + eventFormat = eventFormat.replace("[FACTION_TITLE]", me.getTitle()); + } - InsertIndex = eventFormat.indexOf(Conf.chatTagReplaceString); - eventFormat = eventFormat.replace(Conf.chatTagReplaceString, ""); - Conf.chatTagPadAfter = false; - Conf.chatTagPadBefore = false; - } else if (!Conf.chatTagInsertAfterString.isEmpty() && eventFormat.contains(Conf.chatTagInsertAfterString)) { - // we're using the "insert after string" method - InsertIndex = eventFormat.indexOf(Conf.chatTagInsertAfterString) + Conf.chatTagInsertAfterString.length(); - } else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString)) { - // we're using the "insert before string" method - InsertIndex = eventFormat.indexOf(Conf.chatTagInsertBeforeString); - } else { - // we'll fall back to using the index place method - InsertIndex = Conf.chatTagInsertIndex; - if (InsertIndex > eventFormat.length()) { - return; - } - } + InsertIndex = eventFormat.indexOf(Conf.chatTagReplaceString); + eventFormat = eventFormat.replace(Conf.chatTagReplaceString, ""); + Conf.chatTagPadAfter = false; + Conf.chatTagPadBefore = false; + } else if (!Conf.chatTagInsertAfterString.isEmpty() && eventFormat.contains(Conf.chatTagInsertAfterString)) { + // we're using the "insert after string" method + InsertIndex = eventFormat.indexOf(Conf.chatTagInsertAfterString) + Conf.chatTagInsertAfterString.length(); + } else if (!Conf.chatTagInsertBeforeString.isEmpty() && eventFormat.contains(Conf.chatTagInsertBeforeString)) { + // we're using the "insert before string" method + InsertIndex = eventFormat.indexOf(Conf.chatTagInsertBeforeString); + } else { + // we'll fall back to using the index place method + InsertIndex = Conf.chatTagInsertIndex; + if (InsertIndex > eventFormat.length()) { + return; + } + } - String formatStart = eventFormat.substring(0, InsertIndex) + ((Conf.chatTagPadBefore && !me.getChatTag().isEmpty()) ? " " : ""); - String formatEnd = ((Conf.chatTagPadAfter && !me.getChatTag().isEmpty()) ? " " : "") + eventFormat.substring(InsertIndex); + String formatStart = eventFormat.substring(0, InsertIndex) + ((Conf.chatTagPadBefore && !me.getChatTag().isEmpty()) ? " " : ""); + String formatEnd = ((Conf.chatTagPadAfter && !me.getChatTag().isEmpty()) ? " " : "") + eventFormat.substring(InsertIndex); - String nonColoredMsgFormat = formatStart + me.getChatTag().trim() + formatEnd; + String nonColoredMsgFormat = formatStart + me.getChatTag().trim() + formatEnd; - // Relation Colored? - if (Conf.chatTagRelationColored) { - for (Player listeningPlayer : event.getRecipients()) { - FPlayer you = FPlayers.getInstance().getByPlayer(listeningPlayer); - String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; - try { - listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg)); - } catch (UnknownFormatConversionException ex) { - Conf.chatTagInsertIndex = 0; - SavageFactions.plugin.log(Level.SEVERE, "Critical error in chat message formatting!"); - SavageFactions.plugin.log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); - SavageFactions.plugin.log(Level.SEVERE, "For a more proper fix, please read this regarding chat configuration: http://massivecraft.com/plugins/factions/config#Chat_configuration"); - return; - } - } + // Relation Colored? + if (Conf.chatTagRelationColored) { + for (Player listeningPlayer : event.getRecipients()) { + FPlayer you = FPlayers.getInstance().getByPlayer(listeningPlayer); + String yourFormat = formatStart + me.getChatTag(you).trim() + formatEnd; + try { + listeningPlayer.sendMessage(String.format(yourFormat, talkingPlayer.getDisplayName(), msg)); + } catch (UnknownFormatConversionException ex) { + Conf.chatTagInsertIndex = 0; + SavageFactions.plugin.log(Level.SEVERE, "Critical error in chat message formatting!"); + SavageFactions.plugin.log(Level.SEVERE, "NOTE: This has been automatically fixed right now by setting chatTagInsertIndex to 0."); + SavageFactions.plugin.log(Level.SEVERE, "For a more proper fix, please read this regarding chat configuration: http://massivecraft.com/plugins/factions/config#Chat_configuration"); + return; + } + } - // Messages are sent to players individually - // This still leaves a chance for other plugins to pick it up - event.getRecipients().clear(); - } - // Message with no relation color. - event.setFormat(nonColoredMsgFormat); - } + // Messages are sent to players individually + // This still leaves a chance for other plugins to pick it up + event.getRecipients().clear(); + } + // Message with no relation color. + event.setFormat(nonColoredMsgFormat); + } - private void doWarmup(final String warp, final FPlayer fme) { - WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, new Runnable() { - @Override - public void run() { - Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); - if (player != null) { - player.teleport(fme.getFaction().getWarp(warp).getLocation()); - fme.msg(TL.COMMAND_FWARP_WARPED, warp); - } - } - }, SavageFactions.plugin.getConfig().getLong("warmups.f-warp", 0)); - } + private void doWarmup(final String warp, final FPlayer fme) { + WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, new Runnable() { + @Override + public void run() { + Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); + if (player != null) { + player.teleport(fme.getFaction().getWarp(warp).getLocation()); + fme.msg(TL.COMMAND_FWARP_WARPED, warp); + } + } + }, SavageFactions.plugin.getConfig().getLong("warmups.f-warp", 0)); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java index 7ba67a2d..c54a7894 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsEntityListener.java @@ -31,504 +31,504 @@ import java.util.*; public class FactionsEntityListener implements Listener { - private static final Set badPotionEffects = new LinkedHashSet<>(Arrays.asList(PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, PotionEffectType.WITHER)); - - @EventHandler(priority = EventPriority.NORMAL) - public void onEntityDeath(EntityDeathEvent event) { - Entity entity = event.getEntity(); - if (!(entity instanceof Player)) { - return; - } - - Player player = (Player) entity; - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - Faction faction = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); - - PowerLossEvent powerLossEvent = new PowerLossEvent(faction, fplayer); - // Check for no power loss conditions - if (faction.isWarZone()) { - // war zones always override worldsNoPowerLoss either way, thus this layout - if (!Conf.warZonePowerLoss) { - powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WARZONE.toString()); - powerLossEvent.setCancelled(true); - } - if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { - powerLossEvent.setMessage(TL.PLAYER_POWER_LOSS_WARZONE.toString()); - } - } else if (faction.isWilderness() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) { - powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WILDERNESS.toString()); - powerLossEvent.setCancelled(true); - } else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { - powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WORLD.toString()); - powerLossEvent.setCancelled(true); - } else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) { - powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_PEACEFUL.toString()); - powerLossEvent.setCancelled(true); - } else { - powerLossEvent.setMessage(TL.PLAYER_POWER_NOW.toString()); - } - - // call Event - Bukkit.getPluginManager().callEvent(powerLossEvent); - - // Call player onDeath if the event is not cancelled - if (!powerLossEvent.isCancelled()) { - fplayer.onDeath(); - } - // Send the message from the powerLossEvent - final String msg = powerLossEvent.getMessage(); - if (msg != null && !msg.isEmpty()) { - fplayer.msg(msg, fplayer.getPowerRounded(), fplayer.getPowerMaxRounded()); - } - } - - /** - * Who can I hurt? I can never hurt members or allies. I can always hurt enemies. I can hurt neutrals as long as - * they are outside their own territory. - */ - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityDamage(EntityDamageEvent event) { - if (event instanceof EntityDamageByEntityEvent) { - EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event; - if (!this.canDamagerHurtDamagee(sub, true)) { - event.setCancelled(true); - } - // event is not cancelled by factions - - Entity damagee = sub.getEntity(); - Entity damager = sub.getDamager(); - if (damagee instanceof Player) { - if (damager instanceof Player) { - FPlayer fdamager = FPlayers.getInstance().getByPlayer((Player) damager); - FPlayer fdamagee = FPlayers.getInstance().getByPlayer((Player) damagee); - if ((fdamagee.getRelationTo(fdamager) == Relation.ALLY) || - (fdamagee.getRelationTo(fdamager) == Relation.TRUCE) || - (fdamagee.getFaction() == fdamager.getFaction())) { - return; - } - } else { - - // this triggers if damagee is a player and damager is mob ( so like if a skeleton hits u ) - if (damager instanceof Projectile) { - // this will trigger if the damager is a projectile - if (((Projectile) damager).getShooter() instanceof Player) { - Player damagerPlayer = (Player) ((Projectile) damager).getShooter(); - FPlayer fdamager = FPlayers.getInstance().getByPlayer(damagerPlayer); - FPlayer fdamagee = FPlayers.getInstance().getByPlayer((Player) damagee); - Relation relation = fdamager.getRelationTo(fdamagee); - if (relation == Relation.ALLY || relation == Relation.TRUCE || - fdamager.getFaction() == fdamagee.getFaction()) { - // this should disable the fly so - return; - } - } else { - // this should trigger if the attacker shootin the arrow is a mob - return; - } - - } - } - } else { - // Protect armor stands/item frames from being damaged in protected territories - if (damagee.getType() == EntityType.ITEM_FRAME || damagee.getType() == EntityType.ARMOR_STAND) { - // Manage projectiles launched by players - if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Entity) { - damager = (Entity) ((Projectile) damager).getShooter(); - } - - // Run the check for a player - if (damager instanceof Player) { - // Generate the action message. - String entityAction; - - if (damagee.getType() == EntityType.ITEM_FRAME) { - entityAction = "item frames"; - } else { - entityAction = "armor stands"; - } - - if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) damager, damagee.getLocation(), "destroy " + entityAction, false)) { - event.setCancelled(true); - } - } else { - // we don't want to let mobs/arrows destroy item frames/armor stands - // so we only have to run the check as if there had been an explosion at the damager location - if (!this.checkExplosionForBlock(damager, damagee.getLocation().getBlock())) { - event.setCancelled(true); - } - } - - // we don't need to go after - return; - } - - //this one should trigger if something other than a player takes damage - if (damager instanceof Player) { - // now itll only go here if the damage is dealt by a player - return; - // we cancel it so fly isnt removed when you hit a mob etc - } - } - if (damagee != null && damagee instanceof Player) { - cancelFStuckTeleport((Player) damagee); - cancelFFly((Player) damagee); - FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damagee); - if (fplayer.isInspectMode()) { - fplayer.setInspectMode(false); - fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG); - } - } - if (damager instanceof Player) { - cancelFStuckTeleport((Player) damager); - cancelFFly((Player) damager); - FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damager); - if (fplayer.isInspectMode()) { - fplayer.setInspectMode(false); - fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG); - } - } - } else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) { - // Players can not take any damage in a Safe Zone - event.setCancelled(true); - } else if (event.getCause() == EntityDamageEvent.DamageCause.FALL && event.getEntity() instanceof Player) { - Player player = (Player) event.getEntity(); - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - if (fPlayer != null && !fPlayer.shouldTakeFallDamage()) { - event.setCancelled(true); // Falling after /f fly - } - } - - // entity took generic damage? - Entity entity = event.getEntity(); - if (entity instanceof Player) { - Player player = (Player) entity; - FPlayer me = FPlayers.getInstance().getByPlayer(player); - cancelFStuckTeleport(player); - if (me.isWarmingUp()) { - me.clearWarmup(); - me.msg(TL.WARMUPS_CANCELLED); - } - } - } - - private void cancelFFly(Player player) { - if (player == null) { - return; - } - - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - if (fPlayer.isFlying()) { - fPlayer.setFFlying(false, true); - } - } - - public void cancelFStuckTeleport(Player player) { - if (player == null) { - return; - } - UUID uuid = player.getUniqueId(); - if (SavageFactions.plugin.getStuckMap().containsKey(uuid)) { - FPlayers.getInstance().getByPlayer(player).msg(TL.COMMAND_STUCK_CANCELLED); - SavageFactions.plugin.getStuckMap().remove(uuid); - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityExplode(EntityExplodeEvent event) { - Entity boomer = event.getEntity(); - - // Before we need to check the location where the block is placed - if (!this.checkExplosionForBlock(boomer, event.getLocation().getBlock())) { - event.setCancelled(true); - return; - } - - // Loop the blocklist to run checks on each aimed block - Iterator blockList = event.blockList().iterator(); - - while (blockList.hasNext()) { - Block block = blockList.next(); - - if (!this.checkExplosionForBlock(boomer, block)) { - // The block don't have to explode - blockList.remove(); - } - } - - // Cancel the event if no block will explode - if (event.blockList().isEmpty()) { - event.setCancelled(true); - - // Or handle the exploit of TNT in water/lava - } else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) { - // TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but... - // this change below provides workaround for waterwalling providing perfect protection, - // and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots - Block center = event.getLocation().getBlock(); - - if (center.isLiquid()) { - // a single surrounding block in all 6 directions is broken if the material is weak enough - List targets = new ArrayList<>(); - targets.add(center.getRelative(0, 0, 1)); - targets.add(center.getRelative(0, 0, -1)); - targets.add(center.getRelative(0, 1, 0)); - targets.add(center.getRelative(0, -1, 0)); - targets.add(center.getRelative(1, 0, 0)); - targets.add(center.getRelative(-1, 0, 0)); - - for (Block target : targets) { - @SuppressWarnings("deprecation") - int id = target.getType().getId(); - // ignore air, bedrock, water, lava, obsidian, enchanting table, etc.... too bad we can't get a blast resistance value through Bukkit yet - if (id != 0 && (id < 7 || id > 11) && id != 49 && id != 90 && id != 116 && id != 119 && id != 120 && id != 130) { - target.breakNaturally(); - } - } - } - } - } - - private boolean checkExplosionForBlock(Entity boomer, Block block) { - Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); - - if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom)) { - // faction is peaceful and has explosions set to disabled - return false; - } - - boolean online = faction.hasPlayersOnline(); - - if (boomer instanceof Creeper && ((faction.isWilderness() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) || - (faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) || - (faction.isWarZone() && Conf.warZoneBlockCreepers) || - faction.isSafeZone())) { - // creeper which needs prevention - return false; - } else if ( - // it's a bit crude just using fireball protection for Wither boss too, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever - (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) && ((faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) || - (faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) || - (faction.isWarZone() && Conf.warZoneBlockFireballs) || - faction.isSafeZone())) { - // ghast fireball which needs prevention - return false; - } else - return (!(boomer instanceof TNTPrimed) && !(boomer instanceof ExplosiveMinecart)) || ((!faction.isWilderness() || !Conf.wildernessBlockTNT || Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) && - (!faction.isNormal() || (online ? !Conf.territoryBlockTNT : !Conf.territoryBlockTNTWhenOffline)) && - (!faction.isWarZone() || !Conf.warZoneBlockTNT) && - (!faction.isSafeZone() || !Conf.safeZoneBlockTNT)); - - // No condition retained, destroy the block! - } - - // mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { - EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0d); - if (!this.canDamagerHurtDamagee(sub, false)) { - event.setCancelled(true); - } - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPotionSplashEvent(PotionSplashEvent event) { - // see if the potion has a harmful effect - boolean badjuju = false; - for (PotionEffect effect : event.getPotion().getEffects()) { - if (badPotionEffects.contains(effect.getType())) { - badjuju = true; - break; - } - } - if (!badjuju) { - return; - } - - ProjectileSource thrower = event.getPotion().getShooter(); - if (!(thrower instanceof Entity)) { - return; - } - - if (thrower instanceof Player) { - Player player = (Player) thrower; - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - if (badjuju && fPlayer.getFaction().isPeaceful()) { - event.setCancelled(true); - return; - } - } - - // scan through affected entities to make sure they're all valid targets - for (LivingEntity target : event.getAffectedEntities()) { - EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent((Entity) thrower, target, EntityDamageEvent.DamageCause.CUSTOM, 0); - if (!this.canDamagerHurtDamagee(sub, true)) { - event.setIntensity(target, 0.0); // affected entity list doesn't accept modification (so no iter.remove()), but this works - } - } - } - - public boolean isPlayerInSafeZone(Entity damagee) { - if (!(damagee instanceof Player)) { - return false; - } - return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone(); - } - - public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { - return canDamagerHurtDamagee(sub, true); - } - - public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { - Entity damager = sub.getDamager(); - Entity damagee = sub.getEntity(); - - if (!(damagee instanceof Player)) { - return true; - } - - FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee); - - if (defender == null || defender.getPlayer() == null) { - return true; - } - - Location defenderLoc = defender.getPlayer().getLocation(); - Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc)); - - // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source - if (damager instanceof Projectile) { - Projectile projectile = (Projectile) damager; - - if (!(projectile.getShooter() instanceof Entity)) { - return true; - } - - damager = (Entity) projectile.getShooter(); - } - - if (damager == damagee) // ender pearl usage and other self-inflicted damage - { - return true; - } - - // Players can not take attack damage in a SafeZone, or possibly peaceful territory - if (defLocFaction.noPvPInTerritory()) { - if (damager instanceof Player) { - if (notify) { - FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); - attacker.msg(TL.PLAYER_CANTHURT, (defLocFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); - } - return false; - } - return !defLocFaction.noMonstersInTerritory(); - } - - if (!(damager instanceof Player)) { - return true; - } - - FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); - - if (attacker == null || attacker.getPlayer() == null) { - return true; - } - - if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) { - return true; - } - - if (attacker.hasLoginPvpDisabled()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_LOGIN, Conf.noPVPDamageToOthersForXSecondsAfterLogin); - } - return false; - } - - Faction locFaction = Board.getInstance().getFactionAt(new FLocation(attacker)); - - // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? - if (locFaction.noPvPInTerritory()) { - if (notify) { - attacker.msg(TL.PLAYER_CANTHURT, (locFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); - } - return false; - } - - if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) { - return true; - } - - if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { - return true; - } - - Faction defendFaction = defender.getFaction(); - Faction attackFaction = attacker.getFaction(); - - if (attackFaction.isWilderness() && Conf.disablePVPForFactionlessPlayers) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_REQUIREFACTION); - } - return false; - } else if (defendFaction.isWilderness()) { - if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { - // Allow PVP vs. Factionless in attacker's faction territory - return true; - } else if (Conf.disablePVPForFactionlessPlayers) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_FACTIONLESS); - } - return false; - } - } - - if (defendFaction.isPeaceful()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_PEACEFUL); - } - return false; - } else if (attackFaction.isPeaceful()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_PEACEFUL); - } - return false; - } - - Relation relation = defendFaction.getRelationTo(attackFaction); - - // You can not hurt neutral factions - if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_NEUTRAL); - } - return false; - } - - // Players without faction may be hurt anywhere - if (!defender.hasFaction()) { - return true; - } - - // You can never hurt faction members or allies - if (relation.isMember() || relation.isAlly()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_CANTHURT, defender.describeTo(attacker)); - } - return false; - } - - boolean ownTerritory = defender.isInOwnTerritory(); - - // You can not hurt neutrals in their own territory. - if (ownTerritory && relation.isNeutral()) { - if (notify) { - attacker.msg(TL.PLAYER_PVP_NEUTRALFAIL, defender.describeTo(attacker)); - defender.msg(TL.PLAYER_PVP_TRIED, attacker.describeTo(defender, true)); - } - return false; - } - - // Damage will be dealt. However check if the damage should be reduced. + private static final Set badPotionEffects = new LinkedHashSet<>(Arrays.asList(PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, PotionEffectType.WITHER)); + + @EventHandler(priority = EventPriority.NORMAL) + public void onEntityDeath(EntityDeathEvent event) { + Entity entity = event.getEntity(); + if (!(entity instanceof Player)) { + return; + } + + Player player = (Player) entity; + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); + + PowerLossEvent powerLossEvent = new PowerLossEvent(faction, fplayer); + // Check for no power loss conditions + if (faction.isWarZone()) { + // war zones always override worldsNoPowerLoss either way, thus this layout + if (!Conf.warZonePowerLoss) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WARZONE.toString()); + powerLossEvent.setCancelled(true); + } + if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { + powerLossEvent.setMessage(TL.PLAYER_POWER_LOSS_WARZONE.toString()); + } + } else if (faction.isWilderness() && !Conf.wildernessPowerLoss && !Conf.worldsNoWildernessProtection.contains(player.getWorld().getName())) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WILDERNESS.toString()); + powerLossEvent.setCancelled(true); + } else if (Conf.worldsNoPowerLoss.contains(player.getWorld().getName())) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_WORLD.toString()); + powerLossEvent.setCancelled(true); + } else if (Conf.peacefulMembersDisablePowerLoss && fplayer.hasFaction() && fplayer.getFaction().isPeaceful()) { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOLOSS_PEACEFUL.toString()); + powerLossEvent.setCancelled(true); + } else { + powerLossEvent.setMessage(TL.PLAYER_POWER_NOW.toString()); + } + + // call Event + Bukkit.getPluginManager().callEvent(powerLossEvent); + + // Call player onDeath if the event is not cancelled + if (!powerLossEvent.isCancelled()) { + fplayer.onDeath(); + } + // Send the message from the powerLossEvent + final String msg = powerLossEvent.getMessage(); + if (msg != null && !msg.isEmpty()) { + fplayer.msg(msg, fplayer.getPowerRounded(), fplayer.getPowerMaxRounded()); + } + } + + /** + * Who can I hurt? I can never hurt members or allies. I can always hurt enemies. I can hurt neutrals as long as + * they are outside their own territory. + */ + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityDamage(EntityDamageEvent event) { + if (event instanceof EntityDamageByEntityEvent) { + EntityDamageByEntityEvent sub = (EntityDamageByEntityEvent) event; + if (!this.canDamagerHurtDamagee(sub, true)) { + event.setCancelled(true); + } + // event is not cancelled by factions + + Entity damagee = sub.getEntity(); + Entity damager = sub.getDamager(); + if (damagee instanceof Player) { + if (damager instanceof Player) { + FPlayer fdamager = FPlayers.getInstance().getByPlayer((Player) damager); + FPlayer fdamagee = FPlayers.getInstance().getByPlayer((Player) damagee); + if ((fdamagee.getRelationTo(fdamager) == Relation.ALLY) || + (fdamagee.getRelationTo(fdamager) == Relation.TRUCE) || + (fdamagee.getFaction() == fdamager.getFaction())) { + return; + } + } else { + + // this triggers if damagee is a player and damager is mob ( so like if a skeleton hits u ) + if (damager instanceof Projectile) { + // this will trigger if the damager is a projectile + if (((Projectile) damager).getShooter() instanceof Player) { + Player damagerPlayer = (Player) ((Projectile) damager).getShooter(); + FPlayer fdamager = FPlayers.getInstance().getByPlayer(damagerPlayer); + FPlayer fdamagee = FPlayers.getInstance().getByPlayer((Player) damagee); + Relation relation = fdamager.getRelationTo(fdamagee); + if (relation == Relation.ALLY || relation == Relation.TRUCE || + fdamager.getFaction() == fdamagee.getFaction()) { + // this should disable the fly so + return; + } + } else { + // this should trigger if the attacker shootin the arrow is a mob + return; + } + + } + } + } else { + // Protect armor stands/item frames from being damaged in protected territories + if (damagee.getType() == EntityType.ITEM_FRAME || damagee.getType() == EntityType.ARMOR_STAND) { + // Manage projectiles launched by players + if (damager instanceof Projectile && ((Projectile) damager).getShooter() instanceof Entity) { + damager = (Entity) ((Projectile) damager).getShooter(); + } + + // Run the check for a player + if (damager instanceof Player) { + // Generate the action message. + String entityAction; + + if (damagee.getType() == EntityType.ITEM_FRAME) { + entityAction = "item frames"; + } else { + entityAction = "armor stands"; + } + + if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) damager, damagee.getLocation(), "destroy " + entityAction, false)) { + event.setCancelled(true); + } + } else { + // we don't want to let mobs/arrows destroy item frames/armor stands + // so we only have to run the check as if there had been an explosion at the damager location + if (!this.checkExplosionForBlock(damager, damagee.getLocation().getBlock())) { + event.setCancelled(true); + } + } + + // we don't need to go after + return; + } + + //this one should trigger if something other than a player takes damage + if (damager instanceof Player) { + // now itll only go here if the damage is dealt by a player + return; + // we cancel it so fly isnt removed when you hit a mob etc + } + } + if (damagee != null && damagee instanceof Player) { + cancelFStuckTeleport((Player) damagee); + cancelFFly((Player) damagee); + FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damagee); + if (fplayer.isInspectMode()) { + fplayer.setInspectMode(false); + fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG); + } + } + if (damager instanceof Player) { + cancelFStuckTeleport((Player) damager); + cancelFFly((Player) damager); + FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damager); + if (fplayer.isInspectMode()) { + fplayer.setInspectMode(false); + fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG); + } + } + } else if (Conf.safeZonePreventAllDamageToPlayers && isPlayerInSafeZone(event.getEntity())) { + // Players can not take any damage in a Safe Zone + event.setCancelled(true); + } else if (event.getCause() == EntityDamageEvent.DamageCause.FALL && event.getEntity() instanceof Player) { + Player player = (Player) event.getEntity(); + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (fPlayer != null && !fPlayer.shouldTakeFallDamage()) { + event.setCancelled(true); // Falling after /f fly + } + } + + // entity took generic damage? + Entity entity = event.getEntity(); + if (entity instanceof Player) { + Player player = (Player) entity; + FPlayer me = FPlayers.getInstance().getByPlayer(player); + cancelFStuckTeleport(player); + if (me.isWarmingUp()) { + me.clearWarmup(); + me.msg(TL.WARMUPS_CANCELLED); + } + } + } + + private void cancelFFly(Player player) { + if (player == null) { + return; + } + + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (fPlayer.isFlying()) { + fPlayer.setFFlying(false, true); + } + } + + public void cancelFStuckTeleport(Player player) { + if (player == null) { + return; + } + UUID uuid = player.getUniqueId(); + if (SavageFactions.plugin.getStuckMap().containsKey(uuid)) { + FPlayers.getInstance().getByPlayer(player).msg(TL.COMMAND_STUCK_CANCELLED); + SavageFactions.plugin.getStuckMap().remove(uuid); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityExplode(EntityExplodeEvent event) { + Entity boomer = event.getEntity(); + + // Before we need to check the location where the block is placed + if (!this.checkExplosionForBlock(boomer, event.getLocation().getBlock())) { + event.setCancelled(true); + return; + } + + // Loop the blocklist to run checks on each aimed block + Iterator blockList = event.blockList().iterator(); + + while (blockList.hasNext()) { + Block block = blockList.next(); + + if (!this.checkExplosionForBlock(boomer, block)) { + // The block don't have to explode + blockList.remove(); + } + } + + // Cancel the event if no block will explode + if (event.blockList().isEmpty()) { + event.setCancelled(true); + + // Or handle the exploit of TNT in water/lava + } else if ((boomer instanceof TNTPrimed || boomer instanceof ExplosiveMinecart) && Conf.handleExploitTNTWaterlog) { + // TNT in water/lava doesn't normally destroy any surrounding blocks, which is usually desired behavior, but... + // this change below provides workaround for waterwalling providing perfect protection, + // and makes cheap (non-obsidian) TNT cannons require minor maintenance between shots + Block center = event.getLocation().getBlock(); + + if (center.isLiquid()) { + // a single surrounding block in all 6 directions is broken if the material is weak enough + List targets = new ArrayList<>(); + targets.add(center.getRelative(0, 0, 1)); + targets.add(center.getRelative(0, 0, -1)); + targets.add(center.getRelative(0, 1, 0)); + targets.add(center.getRelative(0, -1, 0)); + targets.add(center.getRelative(1, 0, 0)); + targets.add(center.getRelative(-1, 0, 0)); + + for (Block target : targets) { + @SuppressWarnings("deprecation") + int id = target.getType().getId(); + // ignore air, bedrock, water, lava, obsidian, enchanting table, etc.... too bad we can't get a blast resistance value through Bukkit yet + if (id != 0 && (id < 7 || id > 11) && id != 49 && id != 90 && id != 116 && id != 119 && id != 120 && id != 130) { + target.breakNaturally(); + } + } + } + } + } + + private boolean checkExplosionForBlock(Entity boomer, Block block) { + Faction faction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); + + if (faction.noExplosionsInTerritory() || (faction.isPeaceful() && Conf.peacefulTerritoryDisableBoom)) { + // faction is peaceful and has explosions set to disabled + return false; + } + + boolean online = faction.hasPlayersOnline(); + + if (boomer instanceof Creeper && ((faction.isWilderness() && Conf.wildernessBlockCreepers && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) || + (faction.isNormal() && (online ? Conf.territoryBlockCreepers : Conf.territoryBlockCreepersWhenOffline)) || + (faction.isWarZone() && Conf.warZoneBlockCreepers) || + faction.isSafeZone())) { + // creeper which needs prevention + return false; + } else if ( + // it's a bit crude just using fireball protection for Wither boss too, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever + (boomer instanceof Fireball || boomer instanceof WitherSkull || boomer instanceof Wither) && ((faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) || + (faction.isNormal() && (online ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) || + (faction.isWarZone() && Conf.warZoneBlockFireballs) || + faction.isSafeZone())) { + // ghast fireball which needs prevention + return false; + } else + return (!(boomer instanceof TNTPrimed) && !(boomer instanceof ExplosiveMinecart)) || ((!faction.isWilderness() || !Conf.wildernessBlockTNT || Conf.worldsNoWildernessProtection.contains(block.getWorld().getName())) && + (!faction.isNormal() || (online ? !Conf.territoryBlockTNT : !Conf.territoryBlockTNTWhenOffline)) && + (!faction.isWarZone() || !Conf.warZoneBlockTNT) && + (!faction.isSafeZone() || !Conf.safeZoneBlockTNT)); + + // No condition retained, destroy the block! + } + + // mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { + EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent(event.getCombuster(), event.getEntity(), EntityDamageEvent.DamageCause.FIRE, 0d); + if (!this.canDamagerHurtDamagee(sub, false)) { + event.setCancelled(true); + } + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPotionSplashEvent(PotionSplashEvent event) { + // see if the potion has a harmful effect + boolean badjuju = false; + for (PotionEffect effect : event.getPotion().getEffects()) { + if (badPotionEffects.contains(effect.getType())) { + badjuju = true; + break; + } + } + if (!badjuju) { + return; + } + + ProjectileSource thrower = event.getPotion().getShooter(); + if (!(thrower instanceof Entity)) { + return; + } + + if (thrower instanceof Player) { + Player player = (Player) thrower; + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (badjuju && fPlayer.getFaction().isPeaceful()) { + event.setCancelled(true); + return; + } + } + + // scan through affected entities to make sure they're all valid targets + for (LivingEntity target : event.getAffectedEntities()) { + EntityDamageByEntityEvent sub = new EntityDamageByEntityEvent((Entity) thrower, target, EntityDamageEvent.DamageCause.CUSTOM, 0); + if (!this.canDamagerHurtDamagee(sub, true)) { + event.setIntensity(target, 0.0); // affected entity list doesn't accept modification (so no iter.remove()), but this works + } + } + } + + public boolean isPlayerInSafeZone(Entity damagee) { + if (!(damagee instanceof Player)) { + return false; + } + return Board.getInstance().getFactionAt(new FLocation(damagee.getLocation())).isSafeZone(); + } + + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub) { + return canDamagerHurtDamagee(sub, true); + } + + public boolean canDamagerHurtDamagee(EntityDamageByEntityEvent sub, boolean notify) { + Entity damager = sub.getDamager(); + Entity damagee = sub.getEntity(); + + if (!(damagee instanceof Player)) { + return true; + } + + FPlayer defender = FPlayers.getInstance().getByPlayer((Player) damagee); + + if (defender == null || defender.getPlayer() == null) { + return true; + } + + Location defenderLoc = defender.getPlayer().getLocation(); + Faction defLocFaction = Board.getInstance().getFactionAt(new FLocation(defenderLoc)); + + // for damage caused by projectiles, getDamager() returns the projectile... what we need to know is the source + if (damager instanceof Projectile) { + Projectile projectile = (Projectile) damager; + + if (!(projectile.getShooter() instanceof Entity)) { + return true; + } + + damager = (Entity) projectile.getShooter(); + } + + if (damager == damagee) // ender pearl usage and other self-inflicted damage + { + return true; + } + + // Players can not take attack damage in a SafeZone, or possibly peaceful territory + if (defLocFaction.noPvPInTerritory()) { + if (damager instanceof Player) { + if (notify) { + FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); + attacker.msg(TL.PLAYER_CANTHURT, (defLocFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); + } + return false; + } + return !defLocFaction.noMonstersInTerritory(); + } + + if (!(damager instanceof Player)) { + return true; + } + + FPlayer attacker = FPlayers.getInstance().getByPlayer((Player) damager); + + if (attacker == null || attacker.getPlayer() == null) { + return true; + } + + if (Conf.playersWhoBypassAllProtection.contains(attacker.getName())) { + return true; + } + + if (attacker.hasLoginPvpDisabled()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_LOGIN, Conf.noPVPDamageToOthersForXSecondsAfterLogin); + } + return false; + } + + Faction locFaction = Board.getInstance().getFactionAt(new FLocation(attacker)); + + // so we know from above that the defender isn't in a safezone... what about the attacker, sneaky dog that he might be? + if (locFaction.noPvPInTerritory()) { + if (notify) { + attacker.msg(TL.PLAYER_CANTHURT, (locFaction.isSafeZone() ? TL.REGION_SAFEZONE.toString() : TL.REGION_PEACEFUL.toString())); + } + return false; + } + + if (locFaction.isWarZone() && Conf.warZoneFriendlyFire) { + return true; + } + + if (Conf.worldsIgnorePvP.contains(defenderLoc.getWorld().getName())) { + return true; + } + + Faction defendFaction = defender.getFaction(); + Faction attackFaction = attacker.getFaction(); + + if (attackFaction.isWilderness() && Conf.disablePVPForFactionlessPlayers) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_REQUIREFACTION); + } + return false; + } else if (defendFaction.isWilderness()) { + if (defLocFaction == attackFaction && Conf.enablePVPAgainstFactionlessInAttackersLand) { + // Allow PVP vs. Factionless in attacker's faction territory + return true; + } else if (Conf.disablePVPForFactionlessPlayers) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_FACTIONLESS); + } + return false; + } + } + + if (defendFaction.isPeaceful()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_PEACEFUL); + } + return false; + } else if (attackFaction.isPeaceful()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_PEACEFUL); + } + return false; + } + + Relation relation = defendFaction.getRelationTo(attackFaction); + + // You can not hurt neutral factions + if (Conf.disablePVPBetweenNeutralFactions && relation.isNeutral()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_NEUTRAL); + } + return false; + } + + // Players without faction may be hurt anywhere + if (!defender.hasFaction()) { + return true; + } + + // You can never hurt faction members or allies + if (relation.isMember() || relation.isAlly()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_CANTHURT, defender.describeTo(attacker)); + } + return false; + } + + boolean ownTerritory = defender.isInOwnTerritory(); + + // You can not hurt neutrals in their own territory. + if (ownTerritory && relation.isNeutral()) { + if (notify) { + attacker.msg(TL.PLAYER_PVP_NEUTRALFAIL, defender.describeTo(attacker)); + defender.msg(TL.PLAYER_PVP_TRIED, attacker.describeTo(defender, true)); + } + return false; + } + + // Damage will be dealt. However check if the damage should be reduced. /* if (damage > 0.0 && ownTerritory && Conf.territoryShieldFactor > 0) { double newDamage = Math.ceil(damage * (1D - Conf.territoryShieldFactor)); @@ -541,236 +541,236 @@ public class FactionsEntityListener implements Listener { } } */ - return true; - } + return true; + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onCreatureSpawn(CreatureSpawnEvent event) { - if (event.getLocation() == null) { - return; - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onCreatureSpawn(CreatureSpawnEvent event) { + if (event.getLocation() == null) { + return; + } - if (Conf.safeZoneNerfedCreatureTypes.contains(event.getEntityType()) && Board.getInstance().getFactionAt(new FLocation(event.getLocation())).noMonstersInTerritory()) { - event.setCancelled(true); - } - } + if (Conf.safeZoneNerfedCreatureTypes.contains(event.getEntityType()) && Board.getInstance().getFactionAt(new FLocation(event.getLocation())).noMonstersInTerritory()) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityTarget(EntityTargetEvent event) { - // if there is a target - Entity target = event.getTarget(); - if (target == null) { - return; - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityTarget(EntityTargetEvent event) { + // if there is a target + Entity target = event.getTarget(); + if (target == null) { + return; + } - // We are interested in blocking targeting for certain mobs: - if (!Conf.safeZoneNerfedCreatureTypes.contains(MiscUtil.creatureTypeFromEntity(event.getEntity()))) { - return; - } + // We are interested in blocking targeting for certain mobs: + if (!Conf.safeZoneNerfedCreatureTypes.contains(MiscUtil.creatureTypeFromEntity(event.getEntity()))) { + return; + } - // in case the target is in a safe zone. - if (Board.getInstance().getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory()) { - event.setCancelled(true); - } - } + // in case the target is in a safe zone. + if (Board.getInstance().getFactionAt(new FLocation(target.getLocation())).noMonstersInTerritory()) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPaintingBreak(HangingBreakEvent event) { - if (event.getCause() == RemoveCause.EXPLOSION) { - Location loc = event.getEntity().getLocation(); - Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); - if (faction.noExplosionsInTerritory()) { - // faction is peaceful and has explosions set to disabled - event.setCancelled(true); - return; - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPaintingBreak(HangingBreakEvent event) { + if (event.getCause() == RemoveCause.EXPLOSION) { + Location loc = event.getEntity().getLocation(); + Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); + if (faction.noExplosionsInTerritory()) { + // faction is peaceful and has explosions set to disabled + event.setCancelled(true); + return; + } - boolean online = faction.hasPlayersOnline(); + boolean online = faction.hasPlayersOnline(); - if ((faction.isWilderness() && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName()) && (Conf.wildernessBlockCreepers || Conf.wildernessBlockFireballs || Conf.wildernessBlockTNT)) || - (faction.isNormal() && (online ? (Conf.territoryBlockCreepers || Conf.territoryBlockFireballs || Conf.territoryBlockTNT) : (Conf.territoryBlockCreepersWhenOffline || Conf.territoryBlockFireballsWhenOffline || Conf.territoryBlockTNTWhenOffline))) || - (faction.isWarZone() && (Conf.warZoneBlockCreepers || Conf.warZoneBlockFireballs || Conf.warZoneBlockTNT)) || - faction.isSafeZone()) { - // explosion which needs prevention - event.setCancelled(true); - } - } + if ((faction.isWilderness() && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName()) && (Conf.wildernessBlockCreepers || Conf.wildernessBlockFireballs || Conf.wildernessBlockTNT)) || + (faction.isNormal() && (online ? (Conf.territoryBlockCreepers || Conf.territoryBlockFireballs || Conf.territoryBlockTNT) : (Conf.territoryBlockCreepersWhenOffline || Conf.territoryBlockFireballsWhenOffline || Conf.territoryBlockTNTWhenOffline))) || + (faction.isWarZone() && (Conf.warZoneBlockCreepers || Conf.warZoneBlockFireballs || Conf.warZoneBlockTNT)) || + faction.isSafeZone()) { + // explosion which needs prevention + event.setCancelled(true); + } + } - if (!(event instanceof HangingBreakByEntityEvent)) { - return; - } + if (!(event instanceof HangingBreakByEntityEvent)) { + return; + } - Entity breaker = ((HangingBreakByEntityEvent) event).getRemover(); - if (!(breaker instanceof Player)) { - return; - } + Entity breaker = ((HangingBreakByEntityEvent) event).getRemover(); + if (!(breaker instanceof Player)) { + return; + } - if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) breaker, event.getEntity().getLocation(), "remove paintings", false)) { - event.setCancelled(true); - } - } + if (!FactionsBlockListener.playerCanBuildDestroyBlock((Player) breaker, event.getEntity().getLocation(), "remove paintings", false)) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPaintingPlace(HangingPlaceEvent event) { - if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "place paintings", false)) { - event.setCancelled(true); - // Fix: update player's inventory to avoid items glitches - event.getPlayer().updateInventory(); - } - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPaintingPlace(HangingPlaceEvent event) { + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), event.getBlock().getLocation(), "place paintings", false)) { + event.setCancelled(true); + // Fix: update player's inventory to avoid items glitches + event.getPlayer().updateInventory(); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onEntityChangeBlock(EntityChangeBlockEvent event) { - Entity entity = event.getEntity(); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onEntityChangeBlock(EntityChangeBlockEvent event) { + Entity entity = event.getEntity(); - // for now, only interested in Enderman and Wither boss tomfoolery - if (!(entity instanceof Enderman) && !(entity instanceof Wither)) { - return; - } + // for now, only interested in Enderman and Wither boss tomfoolery + if (!(entity instanceof Enderman) && !(entity instanceof Wither)) { + return; + } - Location loc = event.getBlock().getLocation(); + Location loc = event.getBlock().getLocation(); - if (entity instanceof Enderman) { - if (stopEndermanBlockManipulation(loc)) { - event.setCancelled(true); - } - } else if (entity instanceof Wither) { - Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); - // it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever - if ((faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) || - (faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) || - (faction.isWarZone() && Conf.warZoneBlockFireballs) || - faction.isSafeZone()) { - event.setCancelled(true); - } - } - } + if (entity instanceof Enderman) { + if (stopEndermanBlockManipulation(loc)) { + event.setCancelled(true); + } + } else if (entity instanceof Wither) { + Faction faction = Board.getInstance().getFactionAt(new FLocation(loc)); + // it's a bit crude just using fireball protection, but I'd rather not add in a whole new set of xxxBlockWitherExplosion or whatever + if ((faction.isWilderness() && Conf.wildernessBlockFireballs && !Conf.worldsNoWildernessProtection.contains(loc.getWorld().getName())) || + (faction.isNormal() && (faction.hasPlayersOnline() ? Conf.territoryBlockFireballs : Conf.territoryBlockFireballsWhenOffline)) || + (faction.isWarZone() && Conf.warZoneBlockFireballs) || + faction.isSafeZone()) { + event.setCancelled(true); + } + } + } - @EventHandler - public void onTravel(PlayerPortalEvent event) { - if (!SavageFactions.plugin.getConfig().getBoolean("portals.limit", false)) { - return; // Don't do anything if they don't want us to. - } + @EventHandler + public void onTravel(PlayerPortalEvent event) { + if (!SavageFactions.plugin.getConfig().getBoolean("portals.limit", false)) { + return; // Don't do anything if they don't want us to. + } - TravelAgent agent = event.getPortalTravelAgent(); + TravelAgent agent = event.getPortalTravelAgent(); - // If they aren't able to find a portal, it'll try to create one. - if (event.useTravelAgent() && agent.getCanCreatePortal() && agent.findPortal(event.getTo()) == null) { - FLocation loc = new FLocation(event.getTo()); - Faction faction = Board.getInstance().getFactionAt(loc); - if (faction.isWilderness()) { - return; // We don't care about wilderness. - } else if (!faction.isNormal() && !event.getPlayer().isOp()) { - // Don't let non ops make portals in safezone or warzone. - event.setCancelled(true); - return; - } + // If they aren't able to find a portal, it'll try to create one. + if (event.useTravelAgent() && agent.getCanCreatePortal() && agent.findPortal(event.getTo()) == null) { + FLocation loc = new FLocation(event.getTo()); + Faction faction = Board.getInstance().getFactionAt(loc); + if (faction.isWilderness()) { + return; // We don't care about wilderness. + } else if (!faction.isNormal() && !event.getPlayer().isOp()) { + // Don't let non ops make portals in safezone or warzone. + event.setCancelled(true); + return; + } - FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer()); - String mininumRelation = SavageFactions.plugin.getConfig().getString("portals.minimum-relation", "MEMBER"); // Defaults to Neutral if typed wrong. - if (!fp.getFaction().getRelationTo(faction).isAtLeast(Relation.fromString(mininumRelation))) { - event.setCancelled(true); - } - } - } + FPlayer fp = FPlayers.getInstance().getByPlayer(event.getPlayer()); + String mininumRelation = SavageFactions.plugin.getConfig().getString("portals.minimum-relation", "MEMBER"); // Defaults to Neutral if typed wrong. + if (!fp.getFaction().getRelationTo(faction).isAtLeast(Relation.fromString(mininumRelation))) { + event.setCancelled(true); + } + } + } - @EventHandler - public void onHit(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Player) { - if (e.getEntity() instanceof Player) { - Player victim = (Player) e.getEntity(); - Player attacker = (Player) e.getDamager(); - FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); - FPlayer fattacker = FPlayers.getInstance().getByPlayer(attacker); - if (fattacker.getRelationTo(fvictim) == Relation.TRUCE) { - fattacker.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fattacker)); - e.setCancelled(true); - } - } - } - } + @EventHandler + public void onHit(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Player) { + if (e.getEntity() instanceof Player) { + Player victim = (Player) e.getEntity(); + Player attacker = (Player) e.getDamager(); + FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); + FPlayer fattacker = FPlayers.getInstance().getByPlayer(attacker); + if (fattacker.getRelationTo(fvictim) == Relation.TRUCE) { + fattacker.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fattacker)); + e.setCancelled(true); + } + } + } + } - @EventHandler - public void onBowHit(EntityDamageByEntityEvent e) { - if (e.getDamager() instanceof Projectile) { - if (e.getEntity() instanceof Player) { - Projectile arrow = ((Projectile) e.getDamager()); - if (arrow.getShooter() instanceof Player) { - Player damager = (Player) ((Projectile) e.getDamager()).getShooter(); - Player victim = (Player) e.getEntity(); - FPlayer fdamager = FPlayers.getInstance().getByPlayer(damager); - FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); - if (fvictim.getRelationTo(fdamager) == Relation.TRUCE) { - fdamager.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fdamager)); - e.setCancelled(true); - } - if (fvictim.getRelationTo(fdamager) == Relation.ENEMY) { - if (fvictim.isFlying()) { - fvictim.setFFlying(false, true); - } - } - } - } - } - } + @EventHandler + public void onBowHit(EntityDamageByEntityEvent e) { + if (e.getDamager() instanceof Projectile) { + if (e.getEntity() instanceof Player) { + Projectile arrow = ((Projectile) e.getDamager()); + if (arrow.getShooter() instanceof Player) { + Player damager = (Player) ((Projectile) e.getDamager()).getShooter(); + Player victim = (Player) e.getEntity(); + FPlayer fdamager = FPlayers.getInstance().getByPlayer(damager); + FPlayer fvictim = FPlayers.getInstance().getByPlayer(victim); + if (fvictim.getRelationTo(fdamager) == Relation.TRUCE) { + fdamager.msg(TL.PLAYER_PVP_CANTHURT, fvictim.describeTo(fdamager)); + e.setCancelled(true); + } + if (fvictim.getRelationTo(fdamager) == Relation.ENEMY) { + if (fvictim.isFlying()) { + fvictim.setFFlying(false, true); + } + } + } + } + } + } - // For disabling interactions with item frames in another faction's territory - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { - // only need to check for item frames - if (event.getRightClicked().getType() != EntityType.ITEM_FRAME) { - return; - } + // For disabling interactions with item frames in another faction's territory + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { + // only need to check for item frames + if (event.getRightClicked().getType() != EntityType.ITEM_FRAME) { + return; + } - Player player = event.getPlayer(); - Entity entity = event.getRightClicked(); + Player player = event.getPlayer(); + Entity entity = event.getRightClicked(); - if (!FactionsBlockListener.playerCanBuildDestroyBlock(player, entity.getLocation(), "use item frames", false)) { - event.setCancelled(true); - } - } + if (!FactionsBlockListener.playerCanBuildDestroyBlock(player, entity.getLocation(), "use item frames", false)) { + event.setCancelled(true); + } + } - // For disabling interactions with armor stands in another faction's territory - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { - Entity entity = event.getRightClicked(); + // For disabling interactions with armor stands in another faction's territory + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { + Entity entity = event.getRightClicked(); - // only need to check for armor stand and item frames - if (entity.getType() != EntityType.ARMOR_STAND) { - return; - } + // only need to check for armor stand and item frames + if (entity.getType() != EntityType.ARMOR_STAND) { + return; + } - if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), entity.getLocation(), "use armor stands", false)) { - event.setCancelled(true); - } - } + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), entity.getLocation(), "use armor stands", false)) { + event.setCancelled(true); + } + } - private boolean stopEndermanBlockManipulation(Location loc) { - if (loc == null) { - return false; - } - // quick check to see if all Enderman deny options are enabled; if so, no need to check location - if (Conf.wildernessDenyEndermanBlocks && - Conf.territoryDenyEndermanBlocks && - Conf.territoryDenyEndermanBlocksWhenOffline && - Conf.safeZoneDenyEndermanBlocks && - Conf.warZoneDenyEndermanBlocks) { - return true; - } + private boolean stopEndermanBlockManipulation(Location loc) { + if (loc == null) { + return false; + } + // quick check to see if all Enderman deny options are enabled; if so, no need to check location + if (Conf.wildernessDenyEndermanBlocks && + Conf.territoryDenyEndermanBlocks && + Conf.territoryDenyEndermanBlocksWhenOffline && + Conf.safeZoneDenyEndermanBlocks && + Conf.warZoneDenyEndermanBlocks) { + return true; + } - FLocation fLoc = new FLocation(loc); - Faction claimFaction = Board.getInstance().getFactionAt(fLoc); + FLocation fLoc = new FLocation(loc); + Faction claimFaction = Board.getInstance().getFactionAt(fLoc); - if (claimFaction.isWilderness()) { - return Conf.wildernessDenyEndermanBlocks; - } else if (claimFaction.isNormal()) { - return claimFaction.hasPlayersOnline() ? Conf.territoryDenyEndermanBlocks : Conf.territoryDenyEndermanBlocksWhenOffline; - } else if (claimFaction.isSafeZone()) { - return Conf.safeZoneDenyEndermanBlocks; - } else if (claimFaction.isWarZone()) { - return Conf.warZoneDenyEndermanBlocks; - } + if (claimFaction.isWilderness()) { + return Conf.wildernessDenyEndermanBlocks; + } else if (claimFaction.isNormal()) { + return claimFaction.hasPlayersOnline() ? Conf.territoryDenyEndermanBlocks : Conf.territoryDenyEndermanBlocksWhenOffline; + } else if (claimFaction.isSafeZone()) { + return Conf.safeZoneDenyEndermanBlocks; + } else if (claimFaction.isWarZone()) { + return Conf.warZoneDenyEndermanBlocks; + } - return false; - } + return false; + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java index 0639d02c..f9ca6adb 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsExploitListener.java @@ -14,52 +14,52 @@ import org.bukkit.event.player.PlayerTeleportEvent; public class FactionsExploitListener implements Listener { - public static boolean clippingThrough(Location target, Location from, double thickness) { - return ((from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness))); - } + public static boolean clippingThrough(Location target, Location from, double thickness) { + return ((from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness))); + } - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void obsidianGenerator(BlockFromToEvent event) { - if (!Conf.handleExploitObsidianGenerators) { - return; - } + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void obsidianGenerator(BlockFromToEvent event) { + if (!Conf.handleExploitObsidianGenerators) { + return; + } - // thanks to ObGenBlocker and WorldGuard for this method - Block block = event.getToBlock(); - int source = event.getBlock().getType().getId(); - int target = block.getType().getId(); - if ((target == 55 || target == 132) && (source == 0 || source == 10 || source == 11)) { - block.setType(Material.AIR); - } - } + // thanks to ObGenBlocker and WorldGuard for this method + Block block = event.getToBlock(); + int source = event.getBlock().getType().getId(); + int target = block.getType().getId(); + if ((target == 55 || target == 132) && (source == 0 || source == 10 || source == 11)) { + block.setType(Material.AIR); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void enderPearlTeleport(PlayerTeleportEvent event) { - if (!Conf.handleExploitEnderPearlClipping) { - return; - } - if (event.getCause() != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) { - return; - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void enderPearlTeleport(PlayerTeleportEvent event) { + if (!Conf.handleExploitEnderPearlClipping) { + return; + } + if (event.getCause() != PlayerTeleportEvent.TeleportCause.ENDER_PEARL) { + return; + } - // this exploit works when the target location is within 0.31 blocks or so of a door or glass block or similar... - Location target = event.getTo(); - Location from = event.getFrom(); + // this exploit works when the target location is within 0.31 blocks or so of a door or glass block or similar... + Location target = event.getTo(); + Location from = event.getFrom(); - // blocks who occupy less than 1 block width or length wise need to be handled differently - Material mat = event.getTo().getBlock().getType(); - if (((mat == SavageFactions.plugin.THIN_GLASS - || mat == SavageFactions.plugin.IRON_FENCE) && clippingThrough(target, from, 0.65)) - || ((mat == SavageFactions.plugin.FENCE || mat == SavageFactions.plugin.NETHER_FENCE) && clippingThrough(target, from, 0.45))) { - event.setTo(from); - return; - } + // blocks who occupy less than 1 block width or length wise need to be handled differently + Material mat = event.getTo().getBlock().getType(); + if (((mat == SavageFactions.plugin.THIN_GLASS + || mat == SavageFactions.plugin.IRON_FENCE) && clippingThrough(target, from, 0.65)) + || ((mat == SavageFactions.plugin.FENCE || mat == SavageFactions.plugin.NETHER_FENCE) && clippingThrough(target, from, 0.45))) { + event.setTo(from); + return; + } - // simple fix otherwise: ender pearl target locations are standardized to be in the center (X/Z) of the target block, not at the edges - target.setX(target.getBlockX() + 0.5); - target.setZ(target.getBlockZ() + 0.5); - event.setTo(target); + // simple fix otherwise: ender pearl target locations are standardized to be in the center (X/Z) of the target block, not at the edges + target.setX(target.getBlockX() + 0.5); + target.setZ(target.getBlockZ() + 0.5); + event.setTo(target); - } + } } diff --git a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java index 8ba1daa0..1b5b236c 100644 --- a/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/listeners/FactionsPlayerListener.java @@ -48,856 +48,856 @@ import java.util.logging.Level; public class FactionsPlayerListener implements Listener { - HashMap fallMap = new HashMap<>(); - - // Holds the next time a player can have a map shown. - private HashMap showTimes = new HashMap<>(); - // for handling people who repeatedly spam attempts to open a door (or similar) in another faction's territory - private Map interactSpammers = new HashMap<>(); - - public FactionsPlayerListener() { - for (Player player : SavageFactions.plugin.getServer().getOnlinePlayers()) { - initPlayer(player); - } - } - - public static Boolean isSystemFaction(Faction faction) { - return faction.isSafeZone() || - faction.isWarZone() || - faction.isWilderness(); - } - - public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) { - String name = player.getName(); - if (Conf.playersWhoBypassAllProtection.contains(name)) { - return true; - } - - - FPlayer me = FPlayers.getInstance().getByPlayer(player); - if (me.isAdminBypassing()) { - return true; - } - - FLocation loc = new FLocation(location); - Faction otherFaction = Board.getInstance().getFactionAt(loc); - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - - // Also cancel if player doesn't have ownership rights for this claim - if (Conf.ownedAreasEnabled && myFaction == otherFaction && !myFaction.playerHasOwnershipRights(me, loc)) { - if (!justCheck) { - me.msg("You can't use that in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); - } - return false; - } - - if (SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) { - return true; - } - - if (otherFaction.hasPlayersOnline()) { - if (!Conf.territoryDenyUseageMaterials.contains(material)) { - return true; // Item isn't one we're preventing for online factions. - } - } else { - if (!Conf.territoryDenyUseageMaterialsWhenOffline.contains(material)) { - return true; // Item isn't one we're preventing for offline factions. - } - } - - if (otherFaction.isWilderness()) { - if (!Conf.wildernessDenyUseage || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) { - return true; // This is not faction territory. Use whatever you like here. - } - - if (!justCheck) { - me.msg(TL.PLAYER_USE_WILDERNESS, TextUtil.getMaterialName(material)); - } - - return false; - } else if (otherFaction.isSafeZone()) { - if (!Conf.safeZoneDenyUseage || Permission.MANAGE_SAFE_ZONE.has(player)) { - return true; - } - - if (!justCheck) { - me.msg(TL.PLAYER_USE_SAFEZONE, TextUtil.getMaterialName(material)); - } - - return false; - } else if (otherFaction.isWarZone()) { - if (!Conf.warZoneDenyUseage || Permission.MANAGE_WAR_ZONE.has(player)) { - return true; - } - - if (!justCheck) { - me.msg(TL.PLAYER_USE_WARZONE, TextUtil.getMaterialName(material)); - } - - return false; - } - - // Cancel if we are not in our own territory - if (rel.confDenyUseage()) { - if (!justCheck) { - me.msg(TL.PLAYER_USE_TERRITORY, TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); - } - - return false; - } - - Access access = otherFaction.getAccess(me, PermissableAction.ITEM); - if (access != null && access != Access.UNDEFINED) { - // TODO: Update this once new access values are added other than just allow / deny. - if ((myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && myFaction.getOwnerListString(loc).contains(player.getName()))) { - return true; - } else if (myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && !myFaction.getOwnerListString(loc).contains(player.getName())) { - me.msg("You can't use items in this territory, it is owned by: " + myFaction.getOwnerListString(loc)); - return false; - } else if (access == Access.DENY) { - me.msg(TL.GENERIC_NOPERMISSION, PermissableAction.ITEM); - return false; - } - } - - return true; - } - - @SuppressWarnings("deprecation") - public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck) { - if (Conf.playersWhoBypassAllProtection.contains(player.getName())) - return true; - - FPlayer me = FPlayers.getInstance().getByPlayer(player); - if (me.isAdminBypassing()) - return true; - - Material material = block.getType(); - // Dupe fix. - FLocation loc = new FLocation(block); - Faction otherFaction = Board.getInstance().getFactionAt(loc); - Faction myFaction = me.getFaction(); - Relation rel = myFaction.getRelationTo(otherFaction); - - // no door/chest/whatever protection in wilderness, war zones, or safe zones - if (!otherFaction.isNormal()) - return true; - - if (SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) - return true; - - if (!rel.isMember() || !otherFaction.playerHasOwnershipRights(me, loc) && player.getItemInHand().getType() != null) { - - if (player.getItemInHand().getType().toString().toUpperCase().contains("DOOR")) - return false; - } - - PermissableAction action = null; - - if (SavageFactions.plugin.mc113) { - switch (block.getType()) { - case LEVER: - action = PermissableAction.LEVER; - break; - - case ACACIA_BUTTON: - case BIRCH_BUTTON: - case DARK_OAK_BUTTON: - case JUNGLE_BUTTON: - case OAK_BUTTON: - case SPRUCE_BUTTON: - case STONE_BUTTON: - action = PermissableAction.BUTTON; - break; - - case ACACIA_DOOR: - case BIRCH_DOOR: - case IRON_DOOR: - case JUNGLE_DOOR: - case OAK_DOOR: - case SPRUCE_DOOR: - case DARK_OAK_DOOR: - - case ACACIA_TRAPDOOR: - case BIRCH_TRAPDOOR: - case DARK_OAK_TRAPDOOR: - case IRON_TRAPDOOR: - case JUNGLE_TRAPDOOR: - case OAK_TRAPDOOR: - case SPRUCE_TRAPDOOR: - - case ACACIA_FENCE_GATE: - case BIRCH_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case OAK_FENCE_GATE: - case SPRUCE_FENCE_GATE: - action = PermissableAction.DOOR; - break; - - case CHEST: - case TRAPPED_CHEST: - case CHEST_MINECART: - - case SHULKER_BOX: - case BLACK_SHULKER_BOX: - case BLUE_SHULKER_BOX: - case BROWN_SHULKER_BOX: - case CYAN_SHULKER_BOX: - case GRAY_SHULKER_BOX: - case GREEN_SHULKER_BOX: - case LIGHT_BLUE_SHULKER_BOX: - case LIGHT_GRAY_SHULKER_BOX: - case LIME_SHULKER_BOX: - case MAGENTA_SHULKER_BOX: - case ORANGE_SHULKER_BOX: - case PINK_SHULKER_BOX: - case PURPLE_SHULKER_BOX: - case RED_SHULKER_BOX: - case WHITE_SHULKER_BOX: - case YELLOW_SHULKER_BOX: - - case FURNACE: - case DROPPER: - case DISPENSER: - case ENCHANTING_TABLE: - case BREWING_STAND: - case CAULDRON: - case HOPPER: - case BEACON: - case JUKEBOX: - - case ANVIL: - case CHIPPED_ANVIL: - case DAMAGED_ANVIL: - action = PermissableAction.CONTAINER; - break; - default: - // Check for doors that might have diff material name in old version. - if (block.getType().name().contains("DOOR")) { - action = PermissableAction.DOOR; - } - break; - } - } else { - if (block.getType().toString().toUpperCase().contains("BUTTON")) { - action = PermissableAction.BUTTON; - } - - switch (block.getType()) { - case LEVER: - action = PermissableAction.LEVER; - break; - case DARK_OAK_DOOR: - case ACACIA_DOOR: - case BIRCH_DOOR: - case IRON_DOOR: - case JUNGLE_DOOR: - case SPRUCE_DOOR: - case ACACIA_FENCE_GATE: - case BIRCH_FENCE_GATE: - case DARK_OAK_FENCE_GATE: - case JUNGLE_FENCE_GATE: - case SPRUCE_FENCE_GATE: - action = PermissableAction.DOOR; - break; - case CHEST: - case ENDER_CHEST: - case TRAPPED_CHEST: - case DISPENSER: - case ENCHANTING_TABLE: - case DROPPER: - case FURNACE: - case HOPPER: - case ANVIL: - case CHIPPED_ANVIL: - case DAMAGED_ANVIL: - case BREWING_STAND: - action = PermissableAction.CONTAINER; - break; - default: - // Check for doors that might have diff material name in old version. - if (block.getType().name().contains("DOOR")) - action = PermissableAction.DOOR; - break; - } - } - - // We only care about some material types. - if (otherFaction.hasPlayersOnline()) { - if (!Conf.territoryProtectedMaterials.contains(material)) - return true; - } else { - if (!Conf.territoryProtectedMaterialsWhenOffline.contains(material)) - return true; - } - - // Move up access check to check for exceptions - Access access = otherFaction.getAccess(me, action); - boolean doTerritoryEnemyProtectedCheck = true; - - if (action != null && (action.equals(PermissableAction.CONTAINER) || - action.equals(PermissableAction.DOOR))) { - if (access == Access.ALLOW) { - doTerritoryEnemyProtectedCheck = false; - } - } - - // Did not nest the boolean so that it stands out when Im looking - // through the code later. - if (doTerritoryEnemyProtectedCheck) { - // You may use any block unless it is another faction's territory... - if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials) || (rel.isTruce() && Conf.territoryTruceProtectMaterials)) { - if (!justCheck) { - me.msg(TL.PLAYER_USE_TERRITORY, (material == SavageFactions.plugin.SOIL ? "trample " : "use ") + TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); - } - return false; - } - } - - if (access != Access.ALLOW && me.getRole() != Role.LEADER) { - // TODO: Update this once new access values are added other than just allow / deny. - if ((myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && myFaction.getOwnerListString(loc).contains(player.getName()))) { - return true; - } else if (myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && !myFaction.getOwnerListString(loc).contains(player.getName())) { - me.msg("You can't " + action + " in this territory, it is owned by: " + myFaction.getOwnerListString(loc)); - return false; - } else if (access == Access.DENY) { - me.msg(TL.GENERIC_NOPERMISSION, action); - return false; - } - } - return true; - } - - public static boolean preventCommand(String fullCmd, Player player) { - if ((Conf.territoryNeutralDenyCommands.isEmpty() && Conf.territoryEnemyDenyCommands.isEmpty() && Conf.permanentFactionMemberDenyCommands.isEmpty() && Conf.warzoneDenyCommands.isEmpty())) { - return false; - } - - fullCmd = fullCmd.toLowerCase(); - - FPlayer me = FPlayers.getInstance().getByPlayer(player); - - String shortCmd; // command without the slash at the beginning - if (fullCmd.startsWith("/")) { - shortCmd = fullCmd.substring(1); - } else { - shortCmd = fullCmd; - fullCmd = "/" + fullCmd; - } - - if (me.hasFaction() && - !me.isAdminBypassing() && - !Conf.permanentFactionMemberDenyCommands.isEmpty() && - me.getFaction().isPermanent() && - isCommandInList(fullCmd, shortCmd, Conf.permanentFactionMemberDenyCommands.iterator())) { - me.msg(TL.PLAYER_COMMAND_PERMANENT, fullCmd); - return true; - } - - Faction at = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); - if (at.isWilderness() && !Conf.wildernessDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.wildernessDenyCommands.iterator())) { - me.msg(TL.PLAYER_COMMAND_WILDERNESS, fullCmd); - return true; - } - - Relation rel = at.getRelationTo(me); - if (at.isNormal() && rel.isAlly() && !Conf.territoryAllyDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryAllyDenyCommands.iterator())) { - me.msg(TL.PLAYER_COMMAND_ALLY, fullCmd); - return false; - } - - if (at.isNormal() && rel.isNeutral() && !Conf.territoryNeutralDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryNeutralDenyCommands.iterator())) { - me.msg(TL.PLAYER_COMMAND_NEUTRAL, fullCmd); - return true; - } - - if (at.isNormal() && rel.isEnemy() && !Conf.territoryEnemyDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryEnemyDenyCommands.iterator())) { - me.msg(TL.PLAYER_COMMAND_ENEMY, fullCmd); - return true; - } - - if (at.isWarZone() && !Conf.warzoneDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.warzoneDenyCommands.iterator())) { - me.msg(TL.PLAYER_COMMAND_WARZONE, fullCmd); - return true; - } - - return false; - } - - private static boolean isCommandInList(String fullCmd, String shortCmd, Iterator iter) { - String cmdCheck; - while (iter.hasNext()) { - cmdCheck = iter.next(); - if (cmdCheck == null) { - iter.remove(); - continue; - } - - cmdCheck = cmdCheck.toLowerCase(); - if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck)) { - return true; - } - } - return false; - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerJoin(PlayerJoinEvent event) { - initPlayer(event.getPlayer()); - } - - private void initPlayer(Player player) { - // Make sure that all online players do have a fplayer. - final FPlayer me = FPlayers.getInstance().getByPlayer(player); - ((MemoryFPlayer) me).setName(player.getName()); - - // Update the lastLoginTime for this fplayer - me.setLastLoginTime(System.currentTimeMillis()); - - // Store player's current FLocation and notify them where they are - me.setLastStoodAt(new FLocation(player.getLocation())); - - me.login(); // set kills / deaths - - // Check for Faction announcements. Let's delay this so they actually see it. - Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - if (me.isOnline()) { - me.getFaction().sendUnreadAnnouncements(me); - } - } - }, 33L); // Don't ask me why. - - if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-enabled", false)) { - FScoreboard.init(me); - FScoreboard.get(me).setDefaultSidebar(new FDefaultSidebar(), SavageFactions.plugin.getConfig().getInt("scoreboard.default-update-interval", 20)); - FScoreboard.get(me).setSidebarVisibility(me.showScoreboard()); - } - - Faction myFaction = me.getFaction(); - if (!myFaction.isWilderness()) { - for (FPlayer other : myFaction.getFPlayersWhereOnline(true)) { - if (other != me && other.isMonitoringJoins()) { - other.msg(TL.FACTION_LOGIN, me.getName()); - } - } - } - - - fallMap.put(me.getPlayer(), false); - Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - fallMap.remove(me.getPlayer()); - - } - }, 180L); - - - if (me.isSpyingChat() && !player.hasPermission(Permission.CHATSPY.node)) { - me.setSpyingChat(false); - SavageFactions.plugin.log(Level.INFO, "Found %s spying chat without permission on login. Disabled their chat spying.", player.getName()); - } - - if (me.isAdminBypassing() && !player.hasPermission(Permission.BYPASS.node)) { - me.setIsAdminBypassing(false); - SavageFactions.plugin.log(Level.INFO, "Found %s on admin Bypass without permission on login. Disabled it for them.", player.getName()); - } - - - // If they have the permission, don't let them autoleave. Bad inverted setter :\ - me.setAutoLeave(!player.hasPermission(Permission.AUTO_LEAVE_BYPASS.node)); - me.setTakeFallDamage(true); - } - - @EventHandler - public void onPlayerFall(EntityDamageEvent e) { - if (e.getEntity() instanceof Player) { - if (e.getCause() == EntityDamageEvent.DamageCause.FALL) { - Player player = (Player) e.getEntity(); - if (fallMap.containsKey(player)) { - e.setCancelled(true); - fallMap.remove(player); - } - } - } - } - - @EventHandler(priority = EventPriority.NORMAL) - public void onPlayerQuit(PlayerQuitEvent event) { - FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); - - // Make sure player's power is up to date when they log off. - me.getPower(); - // and update their last login time to point to when the logged off, for auto-remove routine - me.setLastLoginTime(System.currentTimeMillis()); - - me.logout(); // cache kills / deaths - - // if player is waiting for fstuck teleport but leaves, remove - if (SavageFactions.plugin.getStuckMap().containsKey(me.getPlayer().getUniqueId())) { - FPlayers.getInstance().getByPlayer(me.getPlayer()).msg(TL.COMMAND_STUCK_CANCELLED); - SavageFactions.plugin.getStuckMap().remove(me.getPlayer().getUniqueId()); - SavageFactions.plugin.getTimers().remove(me.getPlayer().getUniqueId()); - } - - Faction myFaction = me.getFaction(); - if (!myFaction.isWilderness()) { - myFaction.memberLoggedOff(); - } - - if (!myFaction.isWilderness()) { - for (FPlayer player : myFaction.getFPlayersWhereOnline(true)) { - if (player != me && player.isMonitoringJoins()) { - player.msg(TL.FACTION_LOGOUT, me.getName()); - } - } - } - - CmdSeeChunk.seeChunkMap.remove(event.getPlayer().getName()); - - FScoreboard.remove(me); - } - - public String parseAllPlaceholders(String string, Faction faction, Player player) { - string = TagUtil.parsePlaceholders(player, string); - - string = string.replace("{Faction}", faction.getTag()) - .replace("{online}", faction.getOnlinePlayers().size() + "") - .replace("{offline}", faction.getFPlayers().size() - faction.getOnlinePlayers().size() + "") - .replace("{chunks}", faction.getAllClaims().size() + "") - .replace("{power}", faction.getPower() + "") - .replace("{leader}", faction.getFPlayerAdmin() + ""); - - return string; - } - - public void enableFly(FPlayer me) { - if (SavageFactions.plugin.getConfig().getBoolean("ffly.AutoEnable")) { - - me.setFlying(true); - CmdFly.flyMap.put(me.getName(), true); - if (CmdFly.id == -1) { - if (SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enabled")) { - CmdFly.startParticles(); - } - } - if (CmdFly.flyid == -1) { - CmdFly.startFlyCheck(); - } - } - } - - //inspect - @EventHandler - public void onInspect(PlayerInteractEvent e) { - if (e.getAction().name().contains("BLOCK")) { - FPlayer fplayer = FPlayers.getInstance().getByPlayer(e.getPlayer()); - if (!fplayer.isInspectMode()) { - return; - } - e.setCancelled(true); - if (!fplayer.isAdminBypassing()) { - if (!fplayer.hasFaction()) { - fplayer.setInspectMode(false); - fplayer.msg(TL.COMMAND_INSPECT_DISABLED_NOFAC); - return; - } - if (fplayer.getFaction() != Board.getInstance().getFactionAt(new FLocation(e.getPlayer().getLocation()))) { - fplayer.msg(TL.COMMAND_INSPECT_NOTINCLAIM); - return; - } - } else { - fplayer.msg(TL.COMMAND_INSPECT_BYPASS); - } - List info = CoreProtect.getInstance().getAPI().blockLookup(e.getClickedBlock(), 0); - if (info.size() == 0) { - e.getPlayer().sendMessage(TL.COMMAND_INSPECT_NODATA.toString()); - return; - } - Player player = e.getPlayer(); - CoreProtectAPI coAPI = CoreProtect.getInstance().getAPI(); - player.sendMessage(TL.COMMAND_INSPECT_HEADER.toString().replace("{x}", e.getClickedBlock().getX() + "") - .replace("{y}", e.getClickedBlock().getY() + "") - .replace("{z}", e.getClickedBlock().getZ() + "")); - String rowFormat = TL.COMMAND_INSPECT_ROW.toString(); - for (int i = 0; i < info.size(); i++) { - CoreProtectAPI.ParseResult row = coAPI.parseResult(info.get(0)); - player.sendMessage(rowFormat - .replace("{time}", convertTime(row.getTime())) - .replace("{action}", row.getActionString()) - .replace("{player}", row.getPlayer()) - .replace("{block-type}", row.getType().toString().toLowerCase())); - } - } - } - - //For disabling enderpearl throws - @EventHandler - public void onPearl(PlayerInteractEvent e) { - Player player = e.getPlayer(); - if (player.getItemInHand().getType() == Material.ENDER_PEARL) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - if (fPlayer.isFlying()) { - if (Conf.noEnderpearlsInFly) { - fPlayer.msg(TL.COMMAND_FLY_NO_EPEARL); - e.setCancelled(true); - } - } - } - } - - //For Blocking Homes and Blocking Teleportation To Homes - @EventHandler - public void onPlayerHomeCheck(PlayerTeleportEvent event) throws Exception { - if (event.getPlayer().hasMetadata("NPC")){ - return; - } - if (event.getPlayer().hasPermission("factions.homes.bypass")) { - return; - } - if (Bukkit.getPluginManager().getPlugin("Essentials") == null) { - return; - } - boolean isHome = false; - for (String str : SavageFactions.plugin.ess.getUser(event.getPlayer()).getHomes()) { - Location home = SavageFactions.plugin.ess.getUser(event.getPlayer()).getHome(str); - if (home.getBlockX() == event.getTo().getBlockX() && home.getBlockY() == event.getTo().getBlockY() && home.getBlockZ() == event.getTo().getBlockZ()) { - isHome = true; - } - } - if (!isHome) { - return; - } - Location loc = event.getTo(); - FLocation floc = new FLocation(event.getTo()); - Faction fac = Board.getInstance().getFactionAt(floc); - Player player = event.getPlayer(); - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - User user = SavageFactions.plugin.ess.getUser(event.getPlayer()); - List homes = user.getHomes(); - if (fac.isWilderness() || FPlayers.getInstance().getByPlayer(event.getPlayer()).getFactionId().equals(fac.getId())) { - return; - } - //Warzone and SafeZone Home Initializers - if (fac.isWarZone() || fac.isSafeZone() && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-system-factions")) { - event.setCancelled(true); - fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); - if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-system-factions")) - for (String s : homes) { - if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { - user.delHome(s); - } - } - } - - if (fplayer.getFaction().getRelationTo(fac) == Relation.ENEMY && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-enemy-factions")) { - event.setCancelled(true); - fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); - if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-enemy-factions")) - for (String s : homes) { - if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { - user.delHome(s); - } - } - } - if (fplayer.getFaction().getRelationTo(fac) == Relation.NEUTRAL && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-neutral-factions")) { - event.setCancelled(true); - fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); - if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-neutral-factions")) - for (String s : homes) { - if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { - user.delHome(s); - } - } - } - if (fplayer.getFaction().getRelationTo(fac) == Relation.ALLY && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-ally-factions")) { - event.setCancelled(true); - fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); - if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-ally-factions")) - for (String s : homes) { - if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { - user.delHome(s); - } - } - } - if (fplayer.getFaction().getRelationTo(fac) == Relation.TRUCE && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-truce-factions")) { - event.setCancelled(true); - fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); - if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-truce-factions")) - for (String s : homes) { - if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { - user.delHome(s); - } - } - } - } - - - //Colors a String - public String color(String s) { - return ChatColor.translateAlternateColorCodes('&', s); - } - - - private String convertTime(int time) { - String result = String.valueOf(Math.round((System.currentTimeMillis() / 1000L - time) / 36.0D) / 100.0D); - return (result.length() == 3 ? result + "0" : result) + "/hrs ago"; - } - - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onPlayerMove(PlayerMoveEvent event) { - Player player = event.getPlayer(); - FPlayer me = FPlayers.getInstance().getByPlayer(player); - - // clear visualization - if (event.getFrom().getBlockX() != event.getTo().getBlockX() || event.getFrom().getBlockY() != event.getTo().getBlockY() || event.getFrom().getBlockZ() != event.getTo().getBlockZ()) { - VisualizeUtil.clear(event.getPlayer()); - if (me.isWarmingUp()) { - me.clearWarmup(); - me.msg(TL.WARMUPS_CANCELLED); - } - } - - // quick check to make sure player is moving between chunks; good performance boost - if (event.getFrom().getBlockX() >> 4 == event.getTo().getBlockX() >> 4 && event.getFrom().getBlockZ() >> 4 == event.getTo().getBlockZ() >> 4 && event.getFrom().getWorld() == event.getTo().getWorld()) { - return; - } - - - // Did we change coord? - FLocation from = me.getLastStoodAt(); - FLocation to = new FLocation(event.getTo()); - - if (from.equals(to)) { - return; - } - - // Yes we did change coord (: - - me.setLastStoodAt(to); - - // Did we change "host"(faction)? - Faction factionFrom = Board.getInstance().getFactionAt(from); - Faction factionTo = Board.getInstance().getFactionAt(to); - boolean changedFaction = (factionFrom != factionTo); - - - if (changedFaction) { - Bukkit.getServer().getPluginManager().callEvent(new FPlayerEnteredFactionEvent(factionTo, factionFrom, me)); - if (SavageFactions.plugin.getConfig().getBoolean("Title.Show-Title")) { - String title = SavageFactions.plugin.getConfig().getString("Title.Format.Title"); - title = title.replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); - title = parseAllPlaceholders(title, factionTo, player); - String subTitle = SavageFactions.plugin.getConfig().getString("Title.Format.Subtitle").replace("{Description}", factionTo.getDescription()).replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); - subTitle = parseAllPlaceholders(subTitle, factionTo, player); - if (!SavageFactions.plugin.mc17) { - if (!SavageFactions.plugin.mc18) { - me.getPlayer().sendTitle(SavageFactions.plugin.color(title), SavageFactions.plugin.color(subTitle), SavageFactions.plugin.getConfig().getInt("Title.Options.FadeInTime"), - SavageFactions.plugin.getConfig().getInt("Title.Options.ShowTime"), - SavageFactions.plugin.getConfig().getInt("Title.Options.FadeOutTime")); - } else { - me.getPlayer().sendTitle(SavageFactions.plugin.color(title), SavageFactions.plugin.color(subTitle)); - } - - - } - - } - - if (!SavageFactions.plugin.factionsFlight) { - return; - } - - - // enable fly :) - if (me.hasFaction() && !me.isFlying()) { - if (factionTo == me.getFaction()) { - enableFly(me); - } - // bypass checks - Relation relationTo = factionTo.getRelationTo(me); - if ((factionTo.isWilderness() && me.canflyinWilderness()) || - (factionTo.isWarZone() && me.canflyinWarzone()) || - (factionTo.isSafeZone() && me.canflyinSafezone()) || - (relationTo == Relation.ENEMY && me.canflyinEnemy()) || - (relationTo == Relation.ALLY && me.canflyinAlly()) || - (relationTo == Relation.TRUCE && me.canflyinTruce()) || - (relationTo == Relation.NEUTRAL && me.canflyinNeutral() && !isSystemFaction(factionTo))) { - enableFly(me); - } - - } - } - - - if (me.isMapAutoUpdating()) { - if (showTimes.containsKey(player.getUniqueId()) && (showTimes.get(player.getUniqueId()) > System.currentTimeMillis())) { - if (SavageFactions.plugin.getConfig().getBoolean("findfactionsexploit.log", false)) { - SavageFactions.plugin.log(Level.WARNING, "%s tried to show a faction map too soon and triggered exploit blocker.", player.getName()); - } - } else { - me.sendFancyMessage(Board.getInstance().getMap(me, to, player.getLocation().getYaw())); - showTimes.put(player.getUniqueId(), System.currentTimeMillis() + SavageFactions.plugin.getConfig().getLong("findfactionsexploit.cooldown", 2000)); - } - } else { - Faction myFaction = me.getFaction(); - String ownersTo = myFaction.getOwnerListString(to); - if (changedFaction) { - me.sendFactionHereMessage(factionFrom); - if (Conf.ownedAreasEnabled && Conf.ownedMessageOnBorder && myFaction == factionTo && !ownersTo.isEmpty()) { - me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); - } - } else if (Conf.ownedAreasEnabled && Conf.ownedMessageInsideTerritory && myFaction == factionTo && !myFaction.isWilderness()) { - String ownersFrom = myFaction.getOwnerListString(from); - if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo)) { - if (!ownersTo.isEmpty()) { - me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); - } else if (!TL.GENERIC_PUBLICLAND.toString().isEmpty()) { - me.sendMessage(TL.GENERIC_PUBLICLAND.toString()); - } - } - } - } - - if (me.getAutoClaimFor() != null) { - me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); - } else if (me.isAutoSafeClaimEnabled()) { - if (!Permission.MANAGE_SAFE_ZONE.has(player)) { - me.setIsAutoSafeClaimEnabled(false); - } else { - if (!Board.getInstance().getFactionAt(to).isSafeZone()) { - Board.getInstance().setFactionAt(Factions.getInstance().getSafeZone(), to); - me.msg(TL.PLAYER_SAFEAUTO); - } - } - } else if (me.isAutoWarClaimEnabled()) { - if (!Permission.MANAGE_WAR_ZONE.has(player)) { - me.setIsAutoWarClaimEnabled(false); - } else { - if (!Board.getInstance().getFactionAt(to).isWarZone()) { - Board.getInstance().setFactionAt(Factions.getInstance().getWarZone(), to); - me.msg(TL.PLAYER_WARAUTO); - } - } - } - } - - @EventHandler - public void onClose(InventoryCloseEvent e) { - FPlayer fme = FPlayers.getInstance().getById(e.getPlayer().getUniqueId().toString()); - if (fme.isInVault()) - fme.setInVault(false); - } - - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerInteract(PlayerInteractEvent event) { - /// Prevents the use of montster eggs in oned land. + HashMap fallMap = new HashMap<>(); + + // Holds the next time a player can have a map shown. + private HashMap showTimes = new HashMap<>(); + // for handling people who repeatedly spam attempts to open a door (or similar) in another faction's territory + private Map interactSpammers = new HashMap<>(); + + public FactionsPlayerListener() { + for (Player player : SavageFactions.plugin.getServer().getOnlinePlayers()) { + initPlayer(player); + } + } + + public static Boolean isSystemFaction(Faction faction) { + return faction.isSafeZone() || + faction.isWarZone() || + faction.isWilderness(); + } + + public static boolean playerCanUseItemHere(Player player, Location location, Material material, boolean justCheck) { + String name = player.getName(); + if (Conf.playersWhoBypassAllProtection.contains(name)) { + return true; + } + + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me.isAdminBypassing()) { + return true; + } + + FLocation loc = new FLocation(location); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + + // Also cancel if player doesn't have ownership rights for this claim + if (Conf.ownedAreasEnabled && myFaction == otherFaction && !myFaction.playerHasOwnershipRights(me, loc)) { + if (!justCheck) { + me.msg("You can't use that in this territory, it is owned by: " + otherFaction.getOwnerListString(loc)); + } + return false; + } + + if (SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) { + return true; + } + + if (otherFaction.hasPlayersOnline()) { + if (!Conf.territoryDenyUseageMaterials.contains(material)) { + return true; // Item isn't one we're preventing for online factions. + } + } else { + if (!Conf.territoryDenyUseageMaterialsWhenOffline.contains(material)) { + return true; // Item isn't one we're preventing for offline factions. + } + } + + if (otherFaction.isWilderness()) { + if (!Conf.wildernessDenyUseage || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) { + return true; // This is not faction territory. Use whatever you like here. + } + + if (!justCheck) { + me.msg(TL.PLAYER_USE_WILDERNESS, TextUtil.getMaterialName(material)); + } + + return false; + } else if (otherFaction.isSafeZone()) { + if (!Conf.safeZoneDenyUseage || Permission.MANAGE_SAFE_ZONE.has(player)) { + return true; + } + + if (!justCheck) { + me.msg(TL.PLAYER_USE_SAFEZONE, TextUtil.getMaterialName(material)); + } + + return false; + } else if (otherFaction.isWarZone()) { + if (!Conf.warZoneDenyUseage || Permission.MANAGE_WAR_ZONE.has(player)) { + return true; + } + + if (!justCheck) { + me.msg(TL.PLAYER_USE_WARZONE, TextUtil.getMaterialName(material)); + } + + return false; + } + + // Cancel if we are not in our own territory + if (rel.confDenyUseage()) { + if (!justCheck) { + me.msg(TL.PLAYER_USE_TERRITORY, TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); + } + + return false; + } + + Access access = otherFaction.getAccess(me, PermissableAction.ITEM); + if (access != null && access != Access.UNDEFINED) { + // TODO: Update this once new access values are added other than just allow / deny. + if ((myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && myFaction.getOwnerListString(loc).contains(player.getName()))) { + return true; + } else if (myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && !myFaction.getOwnerListString(loc).contains(player.getName())) { + me.msg("You can't use items in this territory, it is owned by: " + myFaction.getOwnerListString(loc)); + return false; + } else if (access == Access.DENY) { + me.msg(TL.GENERIC_NOPERMISSION, PermissableAction.ITEM); + return false; + } + } + + return true; + } + + @SuppressWarnings("deprecation") + public static boolean canPlayerUseBlock(Player player, Block block, boolean justCheck) { + if (Conf.playersWhoBypassAllProtection.contains(player.getName())) + return true; + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + if (me.isAdminBypassing()) + return true; + + Material material = block.getType(); + // Dupe fix. + FLocation loc = new FLocation(block); + Faction otherFaction = Board.getInstance().getFactionAt(loc); + Faction myFaction = me.getFaction(); + Relation rel = myFaction.getRelationTo(otherFaction); + + // no door/chest/whatever protection in wilderness, war zones, or safe zones + if (!otherFaction.isNormal()) + return true; + + if (SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() > otherFaction.getPowerRounded()) + return true; + + if (!rel.isMember() || !otherFaction.playerHasOwnershipRights(me, loc) && player.getItemInHand().getType() != null) { + + if (player.getItemInHand().getType().toString().toUpperCase().contains("DOOR")) + return false; + } + + PermissableAction action = null; + + if (SavageFactions.plugin.mc113) { + switch (block.getType()) { + case LEVER: + action = PermissableAction.LEVER; + break; + + case ACACIA_BUTTON: + case BIRCH_BUTTON: + case DARK_OAK_BUTTON: + case JUNGLE_BUTTON: + case OAK_BUTTON: + case SPRUCE_BUTTON: + case STONE_BUTTON: + action = PermissableAction.BUTTON; + break; + + case ACACIA_DOOR: + case BIRCH_DOOR: + case IRON_DOOR: + case JUNGLE_DOOR: + case OAK_DOOR: + case SPRUCE_DOOR: + case DARK_OAK_DOOR: + + case ACACIA_TRAPDOOR: + case BIRCH_TRAPDOOR: + case DARK_OAK_TRAPDOOR: + case IRON_TRAPDOOR: + case JUNGLE_TRAPDOOR: + case OAK_TRAPDOOR: + case SPRUCE_TRAPDOOR: + + case ACACIA_FENCE_GATE: + case BIRCH_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case OAK_FENCE_GATE: + case SPRUCE_FENCE_GATE: + action = PermissableAction.DOOR; + break; + + case CHEST: + case TRAPPED_CHEST: + case CHEST_MINECART: + + case SHULKER_BOX: + case BLACK_SHULKER_BOX: + case BLUE_SHULKER_BOX: + case BROWN_SHULKER_BOX: + case CYAN_SHULKER_BOX: + case GRAY_SHULKER_BOX: + case GREEN_SHULKER_BOX: + case LIGHT_BLUE_SHULKER_BOX: + case LIGHT_GRAY_SHULKER_BOX: + case LIME_SHULKER_BOX: + case MAGENTA_SHULKER_BOX: + case ORANGE_SHULKER_BOX: + case PINK_SHULKER_BOX: + case PURPLE_SHULKER_BOX: + case RED_SHULKER_BOX: + case WHITE_SHULKER_BOX: + case YELLOW_SHULKER_BOX: + + case FURNACE: + case DROPPER: + case DISPENSER: + case ENCHANTING_TABLE: + case BREWING_STAND: + case CAULDRON: + case HOPPER: + case BEACON: + case JUKEBOX: + + case ANVIL: + case CHIPPED_ANVIL: + case DAMAGED_ANVIL: + action = PermissableAction.CONTAINER; + break; + default: + // Check for doors that might have diff material name in old version. + if (block.getType().name().contains("DOOR")) { + action = PermissableAction.DOOR; + } + break; + } + } else { + if (block.getType().toString().toUpperCase().contains("BUTTON")) { + action = PermissableAction.BUTTON; + } + + switch (block.getType()) { + case LEVER: + action = PermissableAction.LEVER; + break; + case DARK_OAK_DOOR: + case ACACIA_DOOR: + case BIRCH_DOOR: + case IRON_DOOR: + case JUNGLE_DOOR: + case SPRUCE_DOOR: + case ACACIA_FENCE_GATE: + case BIRCH_FENCE_GATE: + case DARK_OAK_FENCE_GATE: + case JUNGLE_FENCE_GATE: + case SPRUCE_FENCE_GATE: + action = PermissableAction.DOOR; + break; + case CHEST: + case ENDER_CHEST: + case TRAPPED_CHEST: + case DISPENSER: + case ENCHANTING_TABLE: + case DROPPER: + case FURNACE: + case HOPPER: + case ANVIL: + case CHIPPED_ANVIL: + case DAMAGED_ANVIL: + case BREWING_STAND: + action = PermissableAction.CONTAINER; + break; + default: + // Check for doors that might have diff material name in old version. + if (block.getType().name().contains("DOOR")) + action = PermissableAction.DOOR; + break; + } + } + + // We only care about some material types. + if (otherFaction.hasPlayersOnline()) { + if (!Conf.territoryProtectedMaterials.contains(material)) + return true; + } else { + if (!Conf.territoryProtectedMaterialsWhenOffline.contains(material)) + return true; + } + + // Move up access check to check for exceptions + Access access = otherFaction.getAccess(me, action); + boolean doTerritoryEnemyProtectedCheck = true; + + if (action != null && (action.equals(PermissableAction.CONTAINER) || + action.equals(PermissableAction.DOOR))) { + if (access == Access.ALLOW) { + doTerritoryEnemyProtectedCheck = false; + } + } + + // Did not nest the boolean so that it stands out when Im looking + // through the code later. + if (doTerritoryEnemyProtectedCheck) { + // You may use any block unless it is another faction's territory... + if (rel.isNeutral() || (rel.isEnemy() && Conf.territoryEnemyProtectMaterials) || (rel.isAlly() && Conf.territoryAllyProtectMaterials) || (rel.isTruce() && Conf.territoryTruceProtectMaterials)) { + if (!justCheck) { + me.msg(TL.PLAYER_USE_TERRITORY, (material == SavageFactions.plugin.SOIL ? "trample " : "use ") + TextUtil.getMaterialName(material), otherFaction.getTag(myFaction)); + } + return false; + } + } + + if (access != Access.ALLOW && me.getRole() != Role.LEADER) { + // TODO: Update this once new access values are added other than just allow / deny. + if ((myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && myFaction.getOwnerListString(loc).contains(player.getName()))) { + return true; + } else if (myFaction.getOwnerListString(loc) != null && !myFaction.getOwnerListString(loc).isEmpty() && !myFaction.getOwnerListString(loc).contains(player.getName())) { + me.msg("You can't " + action + " in this territory, it is owned by: " + myFaction.getOwnerListString(loc)); + return false; + } else if (access == Access.DENY) { + me.msg(TL.GENERIC_NOPERMISSION, action); + return false; + } + } + return true; + } + + public static boolean preventCommand(String fullCmd, Player player) { + if ((Conf.territoryNeutralDenyCommands.isEmpty() && Conf.territoryEnemyDenyCommands.isEmpty() && Conf.permanentFactionMemberDenyCommands.isEmpty() && Conf.warzoneDenyCommands.isEmpty())) { + return false; + } + + fullCmd = fullCmd.toLowerCase(); + + FPlayer me = FPlayers.getInstance().getByPlayer(player); + + String shortCmd; // command without the slash at the beginning + if (fullCmd.startsWith("/")) { + shortCmd = fullCmd.substring(1); + } else { + shortCmd = fullCmd; + fullCmd = "/" + fullCmd; + } + + if (me.hasFaction() && + !me.isAdminBypassing() && + !Conf.permanentFactionMemberDenyCommands.isEmpty() && + me.getFaction().isPermanent() && + isCommandInList(fullCmd, shortCmd, Conf.permanentFactionMemberDenyCommands.iterator())) { + me.msg(TL.PLAYER_COMMAND_PERMANENT, fullCmd); + return true; + } + + Faction at = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); + if (at.isWilderness() && !Conf.wildernessDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.wildernessDenyCommands.iterator())) { + me.msg(TL.PLAYER_COMMAND_WILDERNESS, fullCmd); + return true; + } + + Relation rel = at.getRelationTo(me); + if (at.isNormal() && rel.isAlly() && !Conf.territoryAllyDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryAllyDenyCommands.iterator())) { + me.msg(TL.PLAYER_COMMAND_ALLY, fullCmd); + return false; + } + + if (at.isNormal() && rel.isNeutral() && !Conf.territoryNeutralDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryNeutralDenyCommands.iterator())) { + me.msg(TL.PLAYER_COMMAND_NEUTRAL, fullCmd); + return true; + } + + if (at.isNormal() && rel.isEnemy() && !Conf.territoryEnemyDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.territoryEnemyDenyCommands.iterator())) { + me.msg(TL.PLAYER_COMMAND_ENEMY, fullCmd); + return true; + } + + if (at.isWarZone() && !Conf.warzoneDenyCommands.isEmpty() && !me.isAdminBypassing() && isCommandInList(fullCmd, shortCmd, Conf.warzoneDenyCommands.iterator())) { + me.msg(TL.PLAYER_COMMAND_WARZONE, fullCmd); + return true; + } + + return false; + } + + private static boolean isCommandInList(String fullCmd, String shortCmd, Iterator iter) { + String cmdCheck; + while (iter.hasNext()) { + cmdCheck = iter.next(); + if (cmdCheck == null) { + iter.remove(); + continue; + } + + cmdCheck = cmdCheck.toLowerCase(); + if (fullCmd.startsWith(cmdCheck) || shortCmd.startsWith(cmdCheck)) { + return true; + } + } + return false; + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerJoin(PlayerJoinEvent event) { + initPlayer(event.getPlayer()); + } + + private void initPlayer(Player player) { + // Make sure that all online players do have a fplayer. + final FPlayer me = FPlayers.getInstance().getByPlayer(player); + ((MemoryFPlayer) me).setName(player.getName()); + + // Update the lastLoginTime for this fplayer + me.setLastLoginTime(System.currentTimeMillis()); + + // Store player's current FLocation and notify them where they are + me.setLastStoodAt(new FLocation(player.getLocation())); + + me.login(); // set kills / deaths + + // Check for Faction announcements. Let's delay this so they actually see it. + Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + if (me.isOnline()) { + me.getFaction().sendUnreadAnnouncements(me); + } + } + }, 33L); // Don't ask me why. + + if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-enabled", false)) { + FScoreboard.init(me); + FScoreboard.get(me).setDefaultSidebar(new FDefaultSidebar(), SavageFactions.plugin.getConfig().getInt("scoreboard.default-update-interval", 20)); + FScoreboard.get(me).setSidebarVisibility(me.showScoreboard()); + } + + Faction myFaction = me.getFaction(); + if (!myFaction.isWilderness()) { + for (FPlayer other : myFaction.getFPlayersWhereOnline(true)) { + if (other != me && other.isMonitoringJoins()) { + other.msg(TL.FACTION_LOGIN, me.getName()); + } + } + } + + + fallMap.put(me.getPlayer(), false); + Bukkit.getScheduler().scheduleSyncDelayedTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + fallMap.remove(me.getPlayer()); + + } + }, 180L); + + + if (me.isSpyingChat() && !player.hasPermission(Permission.CHATSPY.node)) { + me.setSpyingChat(false); + SavageFactions.plugin.log(Level.INFO, "Found %s spying chat without permission on login. Disabled their chat spying.", player.getName()); + } + + if (me.isAdminBypassing() && !player.hasPermission(Permission.BYPASS.node)) { + me.setIsAdminBypassing(false); + SavageFactions.plugin.log(Level.INFO, "Found %s on admin Bypass without permission on login. Disabled it for them.", player.getName()); + } + + + // If they have the permission, don't let them autoleave. Bad inverted setter :\ + me.setAutoLeave(!player.hasPermission(Permission.AUTO_LEAVE_BYPASS.node)); + me.setTakeFallDamage(true); + } + + @EventHandler + public void onPlayerFall(EntityDamageEvent e) { + if (e.getEntity() instanceof Player) { + if (e.getCause() == EntityDamageEvent.DamageCause.FALL) { + Player player = (Player) e.getEntity(); + if (fallMap.containsKey(player)) { + e.setCancelled(true); + fallMap.remove(player); + } + } + } + } + + @EventHandler(priority = EventPriority.NORMAL) + public void onPlayerQuit(PlayerQuitEvent event) { + FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); + + // Make sure player's power is up to date when they log off. + me.getPower(); + // and update their last login time to point to when the logged off, for auto-remove routine + me.setLastLoginTime(System.currentTimeMillis()); + + me.logout(); // cache kills / deaths + + // if player is waiting for fstuck teleport but leaves, remove + if (SavageFactions.plugin.getStuckMap().containsKey(me.getPlayer().getUniqueId())) { + FPlayers.getInstance().getByPlayer(me.getPlayer()).msg(TL.COMMAND_STUCK_CANCELLED); + SavageFactions.plugin.getStuckMap().remove(me.getPlayer().getUniqueId()); + SavageFactions.plugin.getTimers().remove(me.getPlayer().getUniqueId()); + } + + Faction myFaction = me.getFaction(); + if (!myFaction.isWilderness()) { + myFaction.memberLoggedOff(); + } + + if (!myFaction.isWilderness()) { + for (FPlayer player : myFaction.getFPlayersWhereOnline(true)) { + if (player != me && player.isMonitoringJoins()) { + player.msg(TL.FACTION_LOGOUT, me.getName()); + } + } + } + + CmdSeeChunk.seeChunkMap.remove(event.getPlayer().getName()); + + FScoreboard.remove(me); + } + + public String parseAllPlaceholders(String string, Faction faction, Player player) { + string = TagUtil.parsePlaceholders(player, string); + + string = string.replace("{Faction}", faction.getTag()) + .replace("{online}", faction.getOnlinePlayers().size() + "") + .replace("{offline}", faction.getFPlayers().size() - faction.getOnlinePlayers().size() + "") + .replace("{chunks}", faction.getAllClaims().size() + "") + .replace("{power}", faction.getPower() + "") + .replace("{leader}", faction.getFPlayerAdmin() + ""); + + return string; + } + + public void enableFly(FPlayer me) { + if (SavageFactions.plugin.getConfig().getBoolean("ffly.AutoEnable")) { + + me.setFlying(true); + CmdFly.flyMap.put(me.getName(), true); + if (CmdFly.id == -1) { + if (SavageFactions.plugin.getConfig().getBoolean("ffly.Particles.Enabled")) { + CmdFly.startParticles(); + } + } + if (CmdFly.flyid == -1) { + CmdFly.startFlyCheck(); + } + } + } + + //inspect + @EventHandler + public void onInspect(PlayerInteractEvent e) { + if (e.getAction().name().contains("BLOCK")) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(e.getPlayer()); + if (!fplayer.isInspectMode()) { + return; + } + e.setCancelled(true); + if (!fplayer.isAdminBypassing()) { + if (!fplayer.hasFaction()) { + fplayer.setInspectMode(false); + fplayer.msg(TL.COMMAND_INSPECT_DISABLED_NOFAC); + return; + } + if (fplayer.getFaction() != Board.getInstance().getFactionAt(new FLocation(e.getPlayer().getLocation()))) { + fplayer.msg(TL.COMMAND_INSPECT_NOTINCLAIM); + return; + } + } else { + fplayer.msg(TL.COMMAND_INSPECT_BYPASS); + } + List info = CoreProtect.getInstance().getAPI().blockLookup(e.getClickedBlock(), 0); + if (info.size() == 0) { + e.getPlayer().sendMessage(TL.COMMAND_INSPECT_NODATA.toString()); + return; + } + Player player = e.getPlayer(); + CoreProtectAPI coAPI = CoreProtect.getInstance().getAPI(); + player.sendMessage(TL.COMMAND_INSPECT_HEADER.toString().replace("{x}", e.getClickedBlock().getX() + "") + .replace("{y}", e.getClickedBlock().getY() + "") + .replace("{z}", e.getClickedBlock().getZ() + "")); + String rowFormat = TL.COMMAND_INSPECT_ROW.toString(); + for (int i = 0; i < info.size(); i++) { + CoreProtectAPI.ParseResult row = coAPI.parseResult(info.get(0)); + player.sendMessage(rowFormat + .replace("{time}", convertTime(row.getTime())) + .replace("{action}", row.getActionString()) + .replace("{player}", row.getPlayer()) + .replace("{block-type}", row.getType().toString().toLowerCase())); + } + } + } + + //For disabling enderpearl throws + @EventHandler + public void onPearl(PlayerInteractEvent e) { + Player player = e.getPlayer(); + if (player.getItemInHand().getType() == Material.ENDER_PEARL) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + if (fPlayer.isFlying()) { + if (Conf.noEnderpearlsInFly) { + fPlayer.msg(TL.COMMAND_FLY_NO_EPEARL); + e.setCancelled(true); + } + } + } + } + + //For Blocking Homes and Blocking Teleportation To Homes + @EventHandler + public void onPlayerHomeCheck(PlayerTeleportEvent event) throws Exception { + if (event.getPlayer().hasMetadata("NPC")) { + return; + } + if (event.getPlayer().hasPermission("factions.homes.bypass")) { + return; + } + if (Bukkit.getPluginManager().getPlugin("Essentials") == null) { + return; + } + boolean isHome = false; + for (String str : SavageFactions.plugin.ess.getUser(event.getPlayer()).getHomes()) { + Location home = SavageFactions.plugin.ess.getUser(event.getPlayer()).getHome(str); + if (home.getBlockX() == event.getTo().getBlockX() && home.getBlockY() == event.getTo().getBlockY() && home.getBlockZ() == event.getTo().getBlockZ()) { + isHome = true; + } + } + if (!isHome) { + return; + } + Location loc = event.getTo(); + FLocation floc = new FLocation(event.getTo()); + Faction fac = Board.getInstance().getFactionAt(floc); + Player player = event.getPlayer(); + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + User user = SavageFactions.plugin.ess.getUser(event.getPlayer()); + List homes = user.getHomes(); + if (fac.isWilderness() || FPlayers.getInstance().getByPlayer(event.getPlayer()).getFactionId().equals(fac.getId())) { + return; + } + //Warzone and SafeZone Home Initializers + if (fac.isWarZone() || fac.isSafeZone() && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-system-factions")) { + event.setCancelled(true); + fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); + if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-system-factions")) + for (String s : homes) { + if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { + user.delHome(s); + } + } + } + + if (fplayer.getFaction().getRelationTo(fac) == Relation.ENEMY && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-enemy-factions")) { + event.setCancelled(true); + fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); + if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-enemy-factions")) + for (String s : homes) { + if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { + user.delHome(s); + } + } + } + if (fplayer.getFaction().getRelationTo(fac) == Relation.NEUTRAL && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-neutral-factions")) { + event.setCancelled(true); + fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); + if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-neutral-factions")) + for (String s : homes) { + if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { + user.delHome(s); + } + } + } + if (fplayer.getFaction().getRelationTo(fac) == Relation.ALLY && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-ally-factions")) { + event.setCancelled(true); + fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); + if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-ally-factions")) + for (String s : homes) { + if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { + user.delHome(s); + } + } + } + if (fplayer.getFaction().getRelationTo(fac) == Relation.TRUCE && SavageFactions.plugin.getConfig().getBoolean("deny-homes-in-truce-factions")) { + event.setCancelled(true); + fplayer.msg(TL.COMMAND_HOME_BLOCKED, fac.getTag()); + if (SavageFactions.plugin.getConfig().getBoolean("remove-homes-in-truce-factions")) + for (String s : homes) { + if (user.getHome(s).getBlock().getLocation().getChunk().equals(loc.getChunk())) { + user.delHome(s); + } + } + } + } + + + //Colors a String + public String color(String s) { + return ChatColor.translateAlternateColorCodes('&', s); + } + + + private String convertTime(int time) { + String result = String.valueOf(Math.round((System.currentTimeMillis() / 1000L - time) / 36.0D) / 100.0D); + return (result.length() == 3 ? result + "0" : result) + "/hrs ago"; + } + + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerMove(PlayerMoveEvent event) { + Player player = event.getPlayer(); + FPlayer me = FPlayers.getInstance().getByPlayer(player); + + // clear visualization + if (event.getFrom().getBlockX() != event.getTo().getBlockX() || event.getFrom().getBlockY() != event.getTo().getBlockY() || event.getFrom().getBlockZ() != event.getTo().getBlockZ()) { + VisualizeUtil.clear(event.getPlayer()); + if (me.isWarmingUp()) { + me.clearWarmup(); + me.msg(TL.WARMUPS_CANCELLED); + } + } + + // quick check to make sure player is moving between chunks; good performance boost + if (event.getFrom().getBlockX() >> 4 == event.getTo().getBlockX() >> 4 && event.getFrom().getBlockZ() >> 4 == event.getTo().getBlockZ() >> 4 && event.getFrom().getWorld() == event.getTo().getWorld()) { + return; + } + + + // Did we change coord? + FLocation from = me.getLastStoodAt(); + FLocation to = new FLocation(event.getTo()); + + if (from.equals(to)) { + return; + } + + // Yes we did change coord (: + + me.setLastStoodAt(to); + + // Did we change "host"(faction)? + Faction factionFrom = Board.getInstance().getFactionAt(from); + Faction factionTo = Board.getInstance().getFactionAt(to); + boolean changedFaction = (factionFrom != factionTo); + + + if (changedFaction) { + Bukkit.getServer().getPluginManager().callEvent(new FPlayerEnteredFactionEvent(factionTo, factionFrom, me)); + if (SavageFactions.plugin.getConfig().getBoolean("Title.Show-Title")) { + String title = SavageFactions.plugin.getConfig().getString("Title.Format.Title"); + title = title.replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); + title = parseAllPlaceholders(title, factionTo, player); + String subTitle = SavageFactions.plugin.getConfig().getString("Title.Format.Subtitle").replace("{Description}", factionTo.getDescription()).replace("{Faction}", factionTo.getColorTo(me) + factionTo.getTag()); + subTitle = parseAllPlaceholders(subTitle, factionTo, player); + if (!SavageFactions.plugin.mc17) { + if (!SavageFactions.plugin.mc18) { + me.getPlayer().sendTitle(SavageFactions.plugin.color(title), SavageFactions.plugin.color(subTitle), SavageFactions.plugin.getConfig().getInt("Title.Options.FadeInTime"), + SavageFactions.plugin.getConfig().getInt("Title.Options.ShowTime"), + SavageFactions.plugin.getConfig().getInt("Title.Options.FadeOutTime")); + } else { + me.getPlayer().sendTitle(SavageFactions.plugin.color(title), SavageFactions.plugin.color(subTitle)); + } + + + } + + } + + if (!SavageFactions.plugin.factionsFlight) { + return; + } + + + // enable fly :) + if (me.hasFaction() && !me.isFlying()) { + if (factionTo == me.getFaction()) { + enableFly(me); + } + // bypass checks + Relation relationTo = factionTo.getRelationTo(me); + if ((factionTo.isWilderness() && me.canflyinWilderness()) || + (factionTo.isWarZone() && me.canflyinWarzone()) || + (factionTo.isSafeZone() && me.canflyinSafezone()) || + (relationTo == Relation.ENEMY && me.canflyinEnemy()) || + (relationTo == Relation.ALLY && me.canflyinAlly()) || + (relationTo == Relation.TRUCE && me.canflyinTruce()) || + (relationTo == Relation.NEUTRAL && me.canflyinNeutral() && !isSystemFaction(factionTo))) { + enableFly(me); + } + + } + } + + + if (me.isMapAutoUpdating()) { + if (showTimes.containsKey(player.getUniqueId()) && (showTimes.get(player.getUniqueId()) > System.currentTimeMillis())) { + if (SavageFactions.plugin.getConfig().getBoolean("findfactionsexploit.log", false)) { + SavageFactions.plugin.log(Level.WARNING, "%s tried to show a faction map too soon and triggered exploit blocker.", player.getName()); + } + } else { + me.sendFancyMessage(Board.getInstance().getMap(me, to, player.getLocation().getYaw())); + showTimes.put(player.getUniqueId(), System.currentTimeMillis() + SavageFactions.plugin.getConfig().getLong("findfactionsexploit.cooldown", 2000)); + } + } else { + Faction myFaction = me.getFaction(); + String ownersTo = myFaction.getOwnerListString(to); + if (changedFaction) { + me.sendFactionHereMessage(factionFrom); + if (Conf.ownedAreasEnabled && Conf.ownedMessageOnBorder && myFaction == factionTo && !ownersTo.isEmpty()) { + me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); + } + } else if (Conf.ownedAreasEnabled && Conf.ownedMessageInsideTerritory && myFaction == factionTo && !myFaction.isWilderness()) { + String ownersFrom = myFaction.getOwnerListString(from); + if (Conf.ownedMessageByChunk || !ownersFrom.equals(ownersTo)) { + if (!ownersTo.isEmpty()) { + me.sendMessage(TL.GENERIC_OWNERS.format(ownersTo)); + } else if (!TL.GENERIC_PUBLICLAND.toString().isEmpty()) { + me.sendMessage(TL.GENERIC_PUBLICLAND.toString()); + } + } + } + } + + if (me.getAutoClaimFor() != null) { + me.attemptClaim(me.getAutoClaimFor(), event.getTo(), true); + } else if (me.isAutoSafeClaimEnabled()) { + if (!Permission.MANAGE_SAFE_ZONE.has(player)) { + me.setIsAutoSafeClaimEnabled(false); + } else { + if (!Board.getInstance().getFactionAt(to).isSafeZone()) { + Board.getInstance().setFactionAt(Factions.getInstance().getSafeZone(), to); + me.msg(TL.PLAYER_SAFEAUTO); + } + } + } else if (me.isAutoWarClaimEnabled()) { + if (!Permission.MANAGE_WAR_ZONE.has(player)) { + me.setIsAutoWarClaimEnabled(false); + } else { + if (!Board.getInstance().getFactionAt(to).isWarZone()) { + Board.getInstance().setFactionAt(Factions.getInstance().getWarZone(), to); + me.msg(TL.PLAYER_WARAUTO); + } + } + } + } + + @EventHandler + public void onClose(InventoryCloseEvent e) { + FPlayer fme = FPlayers.getInstance().getById(e.getPlayer().getUniqueId().toString()); + if (fme.isInVault()) + fme.setInVault(false); + } + + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEvent event) { + /// Prevents the use of montster eggs in oned land. /*if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { if (event.hasItem() || event.hasBlock()) { ItemStack itemStack = event.getItem(); @@ -915,159 +915,159 @@ public class FactionsPlayerListener implements Listener { } } }*/ - // only need to check right-clicks and physical as of MC 1.4+; good performance boost - if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) - return; + // only need to check right-clicks and physical as of MC 1.4+; good performance boost + if (event.getAction() != Action.RIGHT_CLICK_BLOCK && event.getAction() != Action.PHYSICAL) + return; - Block block = event.getClickedBlock(); - Player player = event.getPlayer(); + Block block = event.getClickedBlock(); + Player player = event.getPlayer(); - if (block == null) - return; // clicked in air, apparently + if (block == null) + return; // clicked in air, apparently - if (!canPlayerUseBlock(player, block, false)) { - event.setCancelled(true); - if (Conf.handleExploitInteractionSpam) { - String name = player.getName(); - InteractAttemptSpam attempt = interactSpammers.get(name); - if (attempt == null) { - attempt = new InteractAttemptSpam(); - interactSpammers.put(name, attempt); - } + if (!canPlayerUseBlock(player, block, false)) { + event.setCancelled(true); + if (Conf.handleExploitInteractionSpam) { + String name = player.getName(); + InteractAttemptSpam attempt = interactSpammers.get(name); + if (attempt == null) { + attempt = new InteractAttemptSpam(); + interactSpammers.put(name, attempt); + } - int count = attempt.increment(); - if (count >= 10) { - FPlayer me = FPlayers.getInstance().getByPlayer(player); - me.msg(TL.PLAYER_OUCH); - player.damage(NumberConversions.floor((double) count / 10)); - } - } - return; - } + int count = attempt.increment(); + if (count >= 10) { + FPlayer me = FPlayers.getInstance().getByPlayer(player); + me.msg(TL.PLAYER_OUCH); + player.damage(NumberConversions.floor((double) count / 10)); + } + } + return; + } - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { - return; // only interested on right-clicks for below - } + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { + return; // only interested on right-clicks for below + } - if (!playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) { - event.setCancelled(true); - } - } + if (!playerCanUseItemHere(player, block.getLocation(), event.getMaterial(), false)) { + event.setCancelled(true); + } + } - @EventHandler - public void onPlayerBoneMeal(PlayerInteractEvent event) { - Block block = event.getClickedBlock(); + @EventHandler + public void onPlayerBoneMeal(PlayerInteractEvent event) { + Block block = event.getClickedBlock(); - if (event.getAction() == Action.RIGHT_CLICK_BLOCK && block.getType() == MultiversionMaterials.GRASS_BLOCK.parseMaterial() - && event.hasItem() && event.getItem().getType() == MultiversionMaterials.BONE_MEAL.parseMaterial()) { - if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), block.getLocation(), PermissableAction.BUILD.name(), true)) { - FPlayer me = FPlayers.getInstance().getById(event.getPlayer().getUniqueId().toString()); - Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); - Faction myFaction = me.getFaction(); + if (event.getAction() == Action.RIGHT_CLICK_BLOCK && block.getType() == MultiversionMaterials.GRASS_BLOCK.parseMaterial() + && event.hasItem() && event.getItem().getType() == MultiversionMaterials.BONE_MEAL.parseMaterial()) { + if (!FactionsBlockListener.playerCanBuildDestroyBlock(event.getPlayer(), block.getLocation(), PermissableAction.BUILD.name(), true)) { + FPlayer me = FPlayers.getInstance().getById(event.getPlayer().getUniqueId().toString()); + Faction otherFaction = Board.getInstance().getFactionAt(new FLocation(block.getLocation())); + Faction myFaction = me.getFaction(); - me.msg("You can't use bone meal in the territory of " + otherFaction.getTag(myFaction)); - event.setCancelled(true); - } - } - } + me.msg("You can't use bone meal in the territory of " + otherFaction.getTag(myFaction)); + event.setCancelled(true); + } + } + } - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerRespawn(PlayerRespawnEvent event) { - FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerRespawn(PlayerRespawnEvent event) { + FPlayer me = FPlayers.getInstance().getByPlayer(event.getPlayer()); - me.getPower(); // update power, so they won't have gained any while dead + me.getPower(); // update power, so they won't have gained any while dead - Location home = me.getFaction().getHome(); - if (Conf.homesEnabled && - Conf.homesTeleportToOnDeath && - home != null && - (Conf.homesRespawnFromNoPowerLossWorlds || !Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName()))) { - event.setRespawnLocation(home); - } - } + Location home = me.getFaction().getHome(); + if (Conf.homesEnabled && + Conf.homesTeleportToOnDeath && + home != null && + (Conf.homesRespawnFromNoPowerLossWorlds || !Conf.worldsNoPowerLoss.contains(event.getPlayer().getWorld().getName()))) { + event.setRespawnLocation(home); + } + } - // For some reason onPlayerInteract() sometimes misses bucket events depending on distance (something like 2-3 blocks away isn't detected), - // but these separate bucket events below always fire without fail - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { - Block block = event.getBlockClicked(); - Player player = event.getPlayer(); + // For some reason onPlayerInteract() sometimes misses bucket events depending on distance (something like 2-3 blocks away isn't detected), + // but these separate bucket events below always fire without fail + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event) { + Block block = event.getBlockClicked(); + Player player = event.getPlayer(); - if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { - event.setCancelled(true); - } - } + if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerBucketFill(PlayerBucketFillEvent event) { - Block block = event.getBlockClicked(); - Player player = event.getPlayer(); + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerBucketFill(PlayerBucketFillEvent event) { + Block block = event.getBlockClicked(); + Player player = event.getPlayer(); - if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { - event.setCancelled(true); - } - } + if (!playerCanUseItemHere(player, block.getLocation(), event.getBucket(), false)) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerInteractGUI(InventoryClickEvent event) { - if (event.getClickedInventory() == null) { - return; - } - if (event.getClickedInventory().getHolder() instanceof FactionGUI) { - event.setCancelled(true); - ((FactionGUI) event.getClickedInventory().getHolder()).onClick(event.getRawSlot(), event.getClick()); - } - } + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerInteractGUI(InventoryClickEvent event) { + if (event.getClickedInventory() == null) { + return; + } + if (event.getClickedInventory().getHolder() instanceof FactionGUI) { + event.setCancelled(true); + ((FactionGUI) event.getClickedInventory().getHolder()).onClick(event.getRawSlot(), event.getClick()); + } + } - @EventHandler(priority = EventPriority.HIGH) - public void onPlayerMoveGUI(InventoryDragEvent event) { - if (event.getInventory().getHolder() instanceof FactionGUI) { - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.HIGH) + public void onPlayerMoveGUI(InventoryDragEvent event) { + if (event.getInventory().getHolder() instanceof FactionGUI) { + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) - public void onPlayerKick(PlayerKickEvent event) { - FPlayer badGuy = FPlayers.getInstance().getByPlayer(event.getPlayer()); - if (badGuy == null) { - return; - } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) + public void onPlayerKick(PlayerKickEvent event) { + FPlayer badGuy = FPlayers.getInstance().getByPlayer(event.getPlayer()); + if (badGuy == null) { + return; + } - // if player was banned (not just kicked), get rid of their stored info - if (Conf.removePlayerDataWhenBanned && event.getReason().equals("Banned by admin.")) { - if (badGuy.getRole() == Role.LEADER) { - badGuy.getFaction().promoteNewLeader(); - } + // if player was banned (not just kicked), get rid of their stored info + if (Conf.removePlayerDataWhenBanned && event.getReason().equals("Banned by admin.")) { + if (badGuy.getRole() == Role.LEADER) { + badGuy.getFaction().promoteNewLeader(); + } - badGuy.leave(false); - badGuy.remove(); - } - } + badGuy.leave(false); + badGuy.remove(); + } + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - final public void onFactionJoin(FPlayerJoinEvent event) { - FTeamWrapper.applyUpdatesLater(event.getFaction()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + final public void onFactionJoin(FPlayerJoinEvent event) { + FTeamWrapper.applyUpdatesLater(event.getFaction()); + } - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onFactionLeave(FPlayerLeaveEvent event) { - FTeamWrapper.applyUpdatesLater(event.getFaction()); - } + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onFactionLeave(FPlayerLeaveEvent event) { + FTeamWrapper.applyUpdatesLater(event.getFaction()); + } - private static class InteractAttemptSpam { - private int attempts = 0; - private long lastAttempt = System.currentTimeMillis(); + private static class InteractAttemptSpam { + private int attempts = 0; + private long lastAttempt = System.currentTimeMillis(); - // returns the current attempt count - public int increment() { - long now = System.currentTimeMillis(); - if (now > lastAttempt + 2000) { - attempts = 1; - } else { - attempts++; - } - lastAttempt = now; - return attempts; - } - } + // returns the current attempt count + public int increment() { + long now = System.currentTimeMillis(); + if (now > lastAttempt + 2000) { + attempts = 1; + } else { + attempts++; + } + lastAttempt = now; + return attempts; + } + } } diff --git a/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java b/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java index d21d3898..03b6f565 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/BufferedObjective.java @@ -11,152 +11,152 @@ import java.lang.reflect.Method; import java.util.*; public class BufferedObjective { - private static final Method addEntryMethod; - private static final int MAX_LINE_LENGTH; + private static final Method addEntryMethod; + private static final int MAX_LINE_LENGTH; - static { - // Check for long line support. - // We require use of Spigot's `addEntry(String)` method on - // Teams, as adding OfflinePlayers to a team is far too slow. + static { + // Check for long line support. + // We require use of Spigot's `addEntry(String)` method on + // Teams, as adding OfflinePlayers to a team is far too slow. - Method addEntryMethodLookup = null; - try { - addEntryMethodLookup = Team.class.getMethod("addEntry", String.class); - } catch (NoSuchMethodException ignored) { - } + Method addEntryMethodLookup = null; + try { + addEntryMethodLookup = Team.class.getMethod("addEntry", String.class); + } catch (NoSuchMethodException ignored) { + } - addEntryMethod = addEntryMethodLookup; + addEntryMethod = addEntryMethodLookup; - if (addEntryMethod != null) { - MAX_LINE_LENGTH = 48; - } else { - MAX_LINE_LENGTH = 16; - } - } + if (addEntryMethod != null) { + MAX_LINE_LENGTH = 48; + } else { + MAX_LINE_LENGTH = 16; + } + } - private final Scoreboard scoreboard; - private final String baseName; - private final Map contents = new HashMap<>(); - private Objective current; - private List currentTeams = new ArrayList<>(); - private String title; - private DisplaySlot displaySlot; - private int objPtr; - private int teamPtr; - private boolean requiresUpdate = false; + private final Scoreboard scoreboard; + private final String baseName; + private final Map contents = new HashMap<>(); + private Objective current; + private List currentTeams = new ArrayList<>(); + private String title; + private DisplaySlot displaySlot; + private int objPtr; + private int teamPtr; + private boolean requiresUpdate = false; - public BufferedObjective(Scoreboard scoreboard) { - this.scoreboard = scoreboard; - this.baseName = createBaseName(); + public BufferedObjective(Scoreboard scoreboard) { + this.scoreboard = scoreboard; + this.baseName = createBaseName(); - current = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy"); - } + current = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy"); + } - private String createBaseName() { - Random random = new Random(); - StringBuilder builder = new StringBuilder(); - while (builder.length() < 14) { - builder.append(Integer.toHexString(random.nextInt())); - } - return builder.toString().substring(0, 14); - } + private String createBaseName() { + Random random = new Random(); + StringBuilder builder = new StringBuilder(); + while (builder.length() < 14) { + builder.append(Integer.toHexString(random.nextInt())); + } + return builder.toString().substring(0, 14); + } - public void setTitle(String title) { - if (this.title == null || !this.title.equals(title)) { - this.title = title; - requiresUpdate = true; - } - } + public void setTitle(String title) { + if (this.title == null || !this.title.equals(title)) { + this.title = title; + requiresUpdate = true; + } + } - public void setDisplaySlot(DisplaySlot slot) { - this.displaySlot = slot; - current.setDisplaySlot(slot); - } + public void setDisplaySlot(DisplaySlot slot) { + this.displaySlot = slot; + current.setDisplaySlot(slot); + } - public void setAllLines(List lines) { - if (lines.size() != contents.size()) { - contents.clear(); - } - for (int i = 0; i < lines.size(); i++) { - setLine(lines.size() - i, lines.get(i)); - } - } + public void setAllLines(List lines) { + if (lines.size() != contents.size()) { + contents.clear(); + } + for (int i = 0; i < lines.size(); i++) { + setLine(lines.size() - i, lines.get(i)); + } + } - public void setLine(int lineNumber, String content) { - if (content.length() > MAX_LINE_LENGTH) { - content = content.substring(0, MAX_LINE_LENGTH); - } - content = ChatColor.translateAlternateColorCodes('&', content); + public void setLine(int lineNumber, String content) { + if (content.length() > MAX_LINE_LENGTH) { + content = content.substring(0, MAX_LINE_LENGTH); + } + content = ChatColor.translateAlternateColorCodes('&', content); - if (contents.get(lineNumber) == null || !contents.get(lineNumber).equals(content)) { - contents.put(lineNumber, content); - requiresUpdate = true; - } - } + if (contents.get(lineNumber) == null || !contents.get(lineNumber).equals(content)) { + contents.put(lineNumber, content); + requiresUpdate = true; + } + } - // Hides the objective from the display slot until flip() is called - public void hide() { - if (displaySlot != null) { - scoreboard.clearSlot(displaySlot); - } - } + // Hides the objective from the display slot until flip() is called + public void hide() { + if (displaySlot != null) { + scoreboard.clearSlot(displaySlot); + } + } - public void flip() { - if (!requiresUpdate) { - return; - } - requiresUpdate = false; + public void flip() { + if (!requiresUpdate) { + return; + } + requiresUpdate = false; - Objective buffer = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy"); - buffer.setDisplayName(title); + Objective buffer = scoreboard.registerNewObjective(getNextObjectiveName(), "dummy"); + buffer.setDisplayName(title); - List bufferTeams = new ArrayList<>(); + List bufferTeams = new ArrayList<>(); - for (Map.Entry entry : contents.entrySet()) { - if (entry.getValue().length() > 16) { - Team team = scoreboard.registerNewTeam(getNextTeamName()); - bufferTeams.add(team); + for (Map.Entry entry : contents.entrySet()) { + if (entry.getValue().length() > 16) { + Team team = scoreboard.registerNewTeam(getNextTeamName()); + bufferTeams.add(team); - Iterator split = Splitter.fixedLength(16).split(entry.getValue()).iterator(); + Iterator split = Splitter.fixedLength(16).split(entry.getValue()).iterator(); - team.setPrefix(split.next()); - String name = split.next(); - if (split.hasNext()) { // We only guarantee two splits - team.setSuffix(split.next()); - } + team.setPrefix(split.next()); + String name = split.next(); + if (split.hasNext()) { // We only guarantee two splits + team.setSuffix(split.next()); + } - try { - addEntryMethod.invoke(team, name); - } catch (ReflectiveOperationException ignored) { - } - buffer.getScore(name).setScore(entry.getKey()); - } else { - buffer.getScore(entry.getValue()).setScore(entry.getKey()); - } - } + try { + addEntryMethod.invoke(team, name); + } catch (ReflectiveOperationException ignored) { + } + buffer.getScore(name).setScore(entry.getKey()); + } else { + buffer.getScore(entry.getValue()).setScore(entry.getKey()); + } + } - if (displaySlot != null) { - buffer.setDisplaySlot(displaySlot); - } + if (displaySlot != null) { + buffer.setDisplaySlot(displaySlot); + } - // Unregister _ALL_ the old things - current.unregister(); + // Unregister _ALL_ the old things + current.unregister(); - Iterator it = currentTeams.iterator(); - while (it.hasNext()) { - it.next().unregister(); - it.remove(); - } + Iterator it = currentTeams.iterator(); + while (it.hasNext()) { + it.next().unregister(); + it.remove(); + } - current = buffer; - currentTeams = bufferTeams; - } + current = buffer; + currentTeams = bufferTeams; + } - private String getNextObjectiveName() { - return baseName + "_" + ((objPtr++) % 2); - } + private String getNextObjectiveName() { + return baseName + "_" + ((objPtr++) % 2); + } - private String getNextTeamName() { - return baseName.substring(0, 10) + "_" + ((teamPtr++) % 999999); - } + private String getNextTeamName() { + return baseName.substring(0, 10) + "_" + ((teamPtr++) % 999999); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java b/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java index 91b2c1e4..61f667f4 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/FScoreboard.java @@ -13,137 +13,137 @@ import java.util.HashMap; import java.util.Map; public class FScoreboard { - private static final Map fscoreboards = new HashMap<>(); + private static final Map fscoreboards = new HashMap<>(); - private final Scoreboard scoreboard; - private final FPlayer fplayer; - private final BufferedObjective bufferedObjective; - private FSidebarProvider defaultProvider; - private FSidebarProvider temporaryProvider; - private boolean removed = false; + private final Scoreboard scoreboard; + private final FPlayer fplayer; + private final BufferedObjective bufferedObjective; + private FSidebarProvider defaultProvider; + private FSidebarProvider temporaryProvider; + private boolean removed = false; - private FScoreboard(FPlayer fplayer) { - this.fplayer = fplayer; + private FScoreboard(FPlayer fplayer) { + this.fplayer = fplayer; - if (isSupportedByServer()) { - this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); - this.bufferedObjective = new BufferedObjective(scoreboard); + if (isSupportedByServer()) { + this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); + this.bufferedObjective = new BufferedObjective(scoreboard); - fplayer.getPlayer().setScoreboard(scoreboard); - } else { - this.scoreboard = null; - this.bufferedObjective = null; - } - } + fplayer.getPlayer().setScoreboard(scoreboard); + } else { + this.scoreboard = null; + this.bufferedObjective = null; + } + } - // Glowstone doesn't support scoreboards. - // All references to this and related workarounds can be safely - // removed when scoreboards are supported. - public static boolean isSupportedByServer() { - return Bukkit.getScoreboardManager() != null; - } + // Glowstone doesn't support scoreboards. + // All references to this and related workarounds can be safely + // removed when scoreboards are supported. + public static boolean isSupportedByServer() { + return Bukkit.getScoreboardManager() != null; + } - public static void init(FPlayer fplayer) { - FScoreboard fboard = new FScoreboard(fplayer); - fscoreboards.put(fplayer, fboard); + public static void init(FPlayer fplayer) { + FScoreboard fboard = new FScoreboard(fplayer); + fscoreboards.put(fplayer, fboard); - if (fplayer.hasFaction()) { - FTeamWrapper.applyUpdates(fplayer.getFaction()); - } - FTeamWrapper.track(fboard); - } + if (fplayer.hasFaction()) { + FTeamWrapper.applyUpdates(fplayer.getFaction()); + } + FTeamWrapper.track(fboard); + } - public static void remove(FPlayer fplayer) { - FScoreboard fboard = fscoreboards.remove(fplayer); + public static void remove(FPlayer fplayer) { + FScoreboard fboard = fscoreboards.remove(fplayer); - if (fboard != null) { - fboard.removed = true; - FTeamWrapper.untrack(fboard); - } - } + if (fboard != null) { + fboard.removed = true; + FTeamWrapper.untrack(fboard); + } + } - public static FScoreboard get(FPlayer fplayer) { - return fscoreboards.get(fplayer); - } + public static FScoreboard get(FPlayer fplayer) { + return fscoreboards.get(fplayer); + } - public static FScoreboard get(Player player) { - return fscoreboards.get(FPlayers.getInstance().getByPlayer(player)); - } + public static FScoreboard get(Player player) { + return fscoreboards.get(FPlayers.getInstance().getByPlayer(player)); + } - protected FPlayer getFPlayer() { - return fplayer; - } + protected FPlayer getFPlayer() { + return fplayer; + } - protected Scoreboard getScoreboard() { - return scoreboard; - } + protected Scoreboard getScoreboard() { + return scoreboard; + } - public void setSidebarVisibility(boolean visible) { - if (!isSupportedByServer()) { - return; - } + public void setSidebarVisibility(boolean visible) { + if (!isSupportedByServer()) { + return; + } - bufferedObjective.setDisplaySlot(visible ? DisplaySlot.SIDEBAR : null); - } + bufferedObjective.setDisplaySlot(visible ? DisplaySlot.SIDEBAR : null); + } - public void setDefaultSidebar(final FSidebarProvider provider, int updateInterval) { - if (!isSupportedByServer()) { - return; - } + public void setDefaultSidebar(final FSidebarProvider provider, int updateInterval) { + if (!isSupportedByServer()) { + return; + } - defaultProvider = provider; - if (temporaryProvider == null) { - // We have no temporary provider; update the BufferedObjective! - updateObjective(); - } + defaultProvider = provider; + if (temporaryProvider == null) { + // We have no temporary provider; update the BufferedObjective! + updateObjective(); + } - new BukkitRunnable() { - @Override - public void run() { - if (removed || provider != defaultProvider) { - cancel(); - return; - } + new BukkitRunnable() { + @Override + public void run() { + if (removed || provider != defaultProvider) { + cancel(); + return; + } - if (temporaryProvider == null) { - updateObjective(); - } - } - }.runTaskTimer(SavageFactions.plugin, updateInterval, updateInterval); - } + if (temporaryProvider == null) { + updateObjective(); + } + } + }.runTaskTimer(SavageFactions.plugin, updateInterval, updateInterval); + } - public void setTemporarySidebar(final FSidebarProvider provider) { - if (!isSupportedByServer()) { - return; - } + public void setTemporarySidebar(final FSidebarProvider provider) { + if (!isSupportedByServer()) { + return; + } - temporaryProvider = provider; - updateObjective(); + temporaryProvider = provider; + updateObjective(); - new BukkitRunnable() { - @Override - public void run() { - if (removed) { - return; - } + new BukkitRunnable() { + @Override + public void run() { + if (removed) { + return; + } - if (temporaryProvider == provider) { - temporaryProvider = null; - updateObjective(); - } - } - }.runTaskLater(SavageFactions.plugin, SavageFactions.plugin.getConfig().getInt("scoreboard.expiration", 7) * 20); - } + if (temporaryProvider == provider) { + temporaryProvider = null; + updateObjective(); + } + } + }.runTaskLater(SavageFactions.plugin, SavageFactions.plugin.getConfig().getInt("scoreboard.expiration", 7) * 20); + } - private void updateObjective() { - FSidebarProvider provider = temporaryProvider != null ? temporaryProvider : defaultProvider; + private void updateObjective() { + FSidebarProvider provider = temporaryProvider != null ? temporaryProvider : defaultProvider; - if (provider == null) { - bufferedObjective.hide(); - } else { - bufferedObjective.setTitle(provider.getTitle(fplayer)); - bufferedObjective.setAllLines(provider.getLines(fplayer)); - bufferedObjective.flip(); - } - } + if (provider == null) { + bufferedObjective.hide(); + } else { + bufferedObjective.setTitle(provider.getTitle(fplayer)); + bufferedObjective.setAllLines(provider.getLines(fplayer)); + bufferedObjective.flip(); + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java b/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java index a40640f4..6ce4976c 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/FSidebarProvider.java @@ -10,32 +10,32 @@ import java.util.List; public abstract class FSidebarProvider { - public abstract String getTitle(FPlayer fplayer); + public abstract String getTitle(FPlayer fplayer); - public abstract List getLines(FPlayer fplayer); + public abstract List getLines(FPlayer fplayer); - public String replaceTags(FPlayer fPlayer, String s) { - s = TagUtil.parsePlaceholders(fPlayer.getPlayer(), s); + public String replaceTags(FPlayer fPlayer, String s) { + s = TagUtil.parsePlaceholders(fPlayer.getPlayer(), s); - return qualityAssure(TagUtil.parsePlain(fPlayer, s)); - } + return qualityAssure(TagUtil.parsePlain(fPlayer, s)); + } - public String replaceTags(Faction faction, FPlayer fPlayer, String s) { - // Run through Placeholder API first - s = TagUtil.parsePlaceholders(fPlayer.getPlayer(), s); + public String replaceTags(Faction faction, FPlayer fPlayer, String s) { + // Run through Placeholder API first + s = TagUtil.parsePlaceholders(fPlayer.getPlayer(), s); - return qualityAssure(TagUtil.parsePlain(faction, fPlayer, s)); - } + return qualityAssure(TagUtil.parsePlain(faction, fPlayer, s)); + } - private String qualityAssure(String line) { - if (line.contains("{notFrozen}") || line.contains("{notPermanent}")) { - return "n/a"; // we dont support support these error variables in scoreboards - } - if (line.contains("{ig}")) { - // since you can't really fit a whole "Faction Home: world, x, y, z" on one line - // we assume it's broken up into two lines, so returning our tl will suffice. - return TL.COMMAND_SHOW_NOHOME.toString(); - } - return SavageFactions.plugin.txt.parse(line); // finally add color :) - } + private String qualityAssure(String line) { + if (line.contains("{notFrozen}") || line.contains("{notPermanent}")) { + return "n/a"; // we dont support support these error variables in scoreboards + } + if (line.contains("{ig}")) { + // since you can't really fit a whole "Faction Home: world, x, y, z" on one line + // we assume it's broken up into two lines, so returning our tl will suffice. + return TL.COMMAND_SHOW_NOHOME.toString(); + } + return SavageFactions.plugin.txt.parse(line); // finally add color :) + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java b/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java index f2f442d2..88ee2663 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/FTeamWrapper.java @@ -12,215 +12,215 @@ import org.bukkit.scoreboard.Team; import java.util.*; public class FTeamWrapper { - private static final Map wrappers = new HashMap<>(); - private static final List tracking = new ArrayList<>(); - private static final Set updating = new HashSet<>(); - private static int factionTeamPtr; - private final Map teams = new HashMap<>(); - private final String teamName; - private final Faction faction; - private final Set members = new HashSet<>(); + private static final Map wrappers = new HashMap<>(); + private static final List tracking = new ArrayList<>(); + private static final Set updating = new HashSet<>(); + private static int factionTeamPtr; + private final Map teams = new HashMap<>(); + private final String teamName; + private final Faction faction; + private final Set members = new HashSet<>(); - private FTeamWrapper(Faction faction) { - this.teamName = "faction_" + (factionTeamPtr++); - this.faction = faction; + private FTeamWrapper(Faction faction) { + this.teamName = "faction_" + (factionTeamPtr++); + this.faction = faction; - for (FScoreboard fboard : tracking) { - add(fboard); - } - } + for (FScoreboard fboard : tracking) { + add(fboard); + } + } - public static void applyUpdatesLater(final Faction faction) { - if (!FScoreboard.isSupportedByServer()) { - return; - } + public static void applyUpdatesLater(final Faction faction) { + if (!FScoreboard.isSupportedByServer()) { + return; + } - if (faction.isWilderness()) { - return; - } + if (faction.isWilderness()) { + return; + } - if (!SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false) || SavageFactions.plugin.getConfig().getBoolean("See-Invisible-Faction-Members")) { - return; - } + if (!SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false) || SavageFactions.plugin.getConfig().getBoolean("See-Invisible-Faction-Members")) { + return; + } - if (updating.add(faction)) { - Bukkit.getScheduler().runTask(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - updating.remove(faction); - applyUpdates(faction); - } - }); - } - } + if (updating.add(faction)) { + Bukkit.getScheduler().runTask(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + updating.remove(faction); + applyUpdates(faction); + } + }); + } + } - public static void applyUpdates(Faction faction) { - if (!FScoreboard.isSupportedByServer()) { - return; - } + public static void applyUpdates(Faction faction) { + if (!FScoreboard.isSupportedByServer()) { + return; + } - if (faction.isWilderness()) { - return; - } + if (faction.isWilderness()) { + return; + } - if (!SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false) || SavageFactions.plugin.getConfig().getBoolean("See-Invisible-Faction-Members")) { - return; - } + if (!SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false) || SavageFactions.plugin.getConfig().getBoolean("See-Invisible-Faction-Members")) { + return; + } - if (updating.contains(faction)) { - // Faction will be updated soon. - return; - } + if (updating.contains(faction)) { + // Faction will be updated soon. + return; + } - FTeamWrapper wrapper = wrappers.get(faction); - Set factionMembers = faction.getFPlayers(); + FTeamWrapper wrapper = wrappers.get(faction); + Set factionMembers = faction.getFPlayers(); - if (wrapper != null && Factions.getInstance().getFactionById(faction.getId()) == null) { - // Faction was disbanded - wrapper.unregister(); - wrappers.remove(faction); - return; - } + if (wrapper != null && Factions.getInstance().getFactionById(faction.getId()) == null) { + // Faction was disbanded + wrapper.unregister(); + wrappers.remove(faction); + return; + } - if (wrapper == null) { - wrapper = new FTeamWrapper(faction); - wrappers.put(faction, wrapper); - } + if (wrapper == null) { + wrapper = new FTeamWrapper(faction); + wrappers.put(faction, wrapper); + } - for (OfflinePlayer player : wrapper.getPlayers()) { - if (!player.isOnline() || !factionMembers.contains(FPlayers.getInstance().getByOfflinePlayer(player))) { - // Player is offline or no longer in faction - wrapper.removePlayer(player); - } - } + for (OfflinePlayer player : wrapper.getPlayers()) { + if (!player.isOnline() || !factionMembers.contains(FPlayers.getInstance().getByOfflinePlayer(player))) { + // Player is offline or no longer in faction + wrapper.removePlayer(player); + } + } - for (FPlayer fmember : factionMembers) { - if (!fmember.isOnline()) { - continue; - } + for (FPlayer fmember : factionMembers) { + if (!fmember.isOnline()) { + continue; + } - // Scoreboard might not have player; add him/her - wrapper.addPlayer(fmember.getPlayer()); - } + // Scoreboard might not have player; add him/her + wrapper.addPlayer(fmember.getPlayer()); + } - wrapper.updatePrefixes(); - } + wrapper.updatePrefixes(); + } - public static void updatePrefixes(Faction faction) { - if (!FScoreboard.isSupportedByServer()) { - return; - } + public static void updatePrefixes(Faction faction) { + if (!FScoreboard.isSupportedByServer()) { + return; + } - if (!wrappers.containsKey(faction)) { - applyUpdates(faction); - } else { - wrappers.get(faction).updatePrefixes(); - } - } + if (!wrappers.containsKey(faction)) { + applyUpdates(faction); + } else { + wrappers.get(faction).updatePrefixes(); + } + } - protected static void track(FScoreboard fboard) { - if (!FScoreboard.isSupportedByServer()) { - return; - } - tracking.add(fboard); - for (FTeamWrapper wrapper : wrappers.values()) { - wrapper.add(fboard); - } - } + protected static void track(FScoreboard fboard) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + tracking.add(fboard); + for (FTeamWrapper wrapper : wrappers.values()) { + wrapper.add(fboard); + } + } - protected static void untrack(FScoreboard fboard) { - if (!FScoreboard.isSupportedByServer()) { - return; - } - tracking.remove(fboard); - for (FTeamWrapper wrapper : wrappers.values()) { - wrapper.remove(fboard); - } - } + protected static void untrack(FScoreboard fboard) { + if (!FScoreboard.isSupportedByServer()) { + return; + } + tracking.remove(fboard); + for (FTeamWrapper wrapper : wrappers.values()) { + wrapper.remove(fboard); + } + } - private void add(FScoreboard fboard) { - Scoreboard board = fboard.getScoreboard(); - Team team = board.registerNewTeam(teamName); - teams.put(fboard, team); + private void add(FScoreboard fboard) { + Scoreboard board = fboard.getScoreboard(); + Team team = board.registerNewTeam(teamName); + teams.put(fboard, team); - for (OfflinePlayer player : getPlayers()) { - team.addPlayer(player); - } + for (OfflinePlayer player : getPlayers()) { + team.addPlayer(player); + } - updatePrefix(fboard); - } + updatePrefix(fboard); + } - private void remove(FScoreboard fboard) { - teams.remove(fboard).unregister(); - } + private void remove(FScoreboard fboard) { + teams.remove(fboard).unregister(); + } - private void updatePrefixes() { - if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false)) { - for (FScoreboard fboard : teams.keySet()) { - updatePrefix(fboard); - } - } - } + private void updatePrefixes() { + if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false)) { + for (FScoreboard fboard : teams.keySet()) { + updatePrefix(fboard); + } + } + } - private void updatePrefix(FScoreboard fboard) { - if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false)) { - FPlayer fplayer = fboard.getFPlayer(); - Team team = teams.get(fboard); - boolean focused = false; + private void updatePrefix(FScoreboard fboard) { + if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-prefixes", false)) { + FPlayer fplayer = fboard.getFPlayer(); + Team team = teams.get(fboard); + boolean focused = false; - if (SavageFactions.plugin.getConfig().getBoolean("See-Invisible-Faction-Members", false)) { - team.setCanSeeFriendlyInvisibles(true); - } + if (SavageFactions.plugin.getConfig().getBoolean("See-Invisible-Faction-Members", false)) { + team.setCanSeeFriendlyInvisibles(true); + } - if ((SavageFactions.plugin.getConfig().getBoolean("ffocus.Enabled")) && (fplayer.getFaction() != null) && (fplayer.getFaction().getFocused() != null)) { - for (FPlayer fp : faction.getFPlayersWhereOnline(true)) { - if (fplayer.getFaction().getFocused().equalsIgnoreCase(fp.getName())) { - team.setPrefix(ChatColor.translateAlternateColorCodes('&', SavageFactions.plugin.getConfig().getString("ffocus.Prefix", "&7»&b"))); - focused = true; - } - } - } - if (!focused) { - String prefix = TL.DEFAULT_PREFIX.toString(); + if ((SavageFactions.plugin.getConfig().getBoolean("ffocus.Enabled")) && (fplayer.getFaction() != null) && (fplayer.getFaction().getFocused() != null)) { + for (FPlayer fp : faction.getFPlayersWhereOnline(true)) { + if (fplayer.getFaction().getFocused().equalsIgnoreCase(fp.getName())) { + team.setPrefix(ChatColor.translateAlternateColorCodes('&', SavageFactions.plugin.getConfig().getString("ffocus.Prefix", "&7»&b"))); + focused = true; + } + } + } + if (!focused) { + String prefix = TL.DEFAULT_PREFIX.toString(); - prefix = PlaceholderAPI.setPlaceholders(fplayer.getPlayer(), prefix); - prefix = PlaceholderAPI.setBracketPlaceholders(fplayer.getPlayer(), prefix); - prefix = prefix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString()); - prefix = prefix.replace("{faction}", - faction.getTag().substring(0, Math.min("{faction}".length() + 16 - prefix.length(), faction.getTag().length()))); - if ((team.getPrefix() == null) || (!team.getPrefix().equals(prefix))) { - team.setPrefix(prefix); - } - } - } - } + prefix = PlaceholderAPI.setPlaceholders(fplayer.getPlayer(), prefix); + prefix = PlaceholderAPI.setBracketPlaceholders(fplayer.getPlayer(), prefix); + prefix = prefix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString()); + prefix = prefix.replace("{faction}", + faction.getTag().substring(0, Math.min("{faction}".length() + 16 - prefix.length(), faction.getTag().length()))); + if ((team.getPrefix() == null) || (!team.getPrefix().equals(prefix))) { + team.setPrefix(prefix); + } + } + } + } - private void addPlayer(OfflinePlayer player) { - if (members.add(player)) { - for (Team team : teams.values()) { - team.addPlayer(player); - } - } - } + private void addPlayer(OfflinePlayer player) { + if (members.add(player)) { + for (Team team : teams.values()) { + team.addPlayer(player); + } + } + } - private void removePlayer(OfflinePlayer player) { - if (members.remove(player)) { - for (Team team : teams.values()) { - team.removePlayer(player); - } - } - } + private void removePlayer(OfflinePlayer player) { + if (members.remove(player)) { + for (Team team : teams.values()) { + team.removePlayer(player); + } + } + } - private Set getPlayers() { - return new HashSet<>(this.members); - } + private Set getPlayers() { + return new HashSet<>(this.members); + } - private void unregister() { - for (Team team : teams.values()) { - team.unregister(); - } - teams.clear(); - } + private void unregister() { + for (Team team : teams.values()) { + team.unregister(); + } + teams.clear(); + } } diff --git a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java index 5bdf32fa..64c68708 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FDefaultSidebar.java @@ -10,32 +10,32 @@ import java.util.ListIterator; public class FDefaultSidebar extends FSidebarProvider { - @Override - public String getTitle(FPlayer fplayer) { - return replaceTags(fplayer, SavageFactions.plugin.getConfig().getString("scoreboard.default-title", "{name}")); - } + @Override + public String getTitle(FPlayer fplayer) { + return replaceTags(fplayer, SavageFactions.plugin.getConfig().getString("scoreboard.default-title", "{name}")); + } - @Override - public List getLines(FPlayer fplayer) { - if (fplayer.hasFaction()) { - return getOutput(fplayer, "scoreboard.default"); - } else if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.factionless-enabled", false)) { - return getOutput(fplayer, "scoreboard.factionless"); - } - return getOutput(fplayer, "scoreboard.default"); // no faction, factionless-board disabled - } + @Override + public List getLines(FPlayer fplayer) { + if (fplayer.hasFaction()) { + return getOutput(fplayer, "scoreboard.default"); + } else if (SavageFactions.plugin.getConfig().getBoolean("scoreboard.factionless-enabled", false)) { + return getOutput(fplayer, "scoreboard.factionless"); + } + return getOutput(fplayer, "scoreboard.default"); // no faction, factionless-board disabled + } - public List getOutput(FPlayer fplayer, String list) { - List lines = SavageFactions.plugin.getConfig().getStringList(list); + public List getOutput(FPlayer fplayer, String list) { + List lines = SavageFactions.plugin.getConfig().getStringList(list); - if (lines == null || lines.isEmpty()) { - return new ArrayList<>(); - } + if (lines == null || lines.isEmpty()) { + return new ArrayList<>(); + } - ListIterator it = lines.listIterator(); - while (it.hasNext()) { - it.set(replaceTags(fplayer, it.next())); - } - return lines; - } + ListIterator it = lines.listIterator(); + while (it.hasNext()) { + it.set(replaceTags(fplayer, it.next())); + } + return lines; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java index 93759678..4820387c 100644 --- a/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java +++ b/src/main/java/com/massivecraft/factions/scoreboards/sidebar/FInfoSidebar.java @@ -9,25 +9,25 @@ import java.util.List; import java.util.ListIterator; public class FInfoSidebar extends FSidebarProvider { - private final Faction faction; + private final Faction faction; - public FInfoSidebar(Faction faction) { - this.faction = faction; - } + public FInfoSidebar(Faction faction) { + this.faction = faction; + } - @Override - public String getTitle(FPlayer fplayer) { - return faction.getRelationTo(fplayer).getColor() + faction.getTag(); - } + @Override + public String getTitle(FPlayer fplayer) { + return faction.getRelationTo(fplayer).getColor() + faction.getTag(); + } - @Override - public List getLines(FPlayer fplayer) { - List lines = SavageFactions.plugin.getConfig().getStringList("scoreboard.finfo"); + @Override + public List getLines(FPlayer fplayer) { + List lines = SavageFactions.plugin.getConfig().getStringList("scoreboard.finfo"); - ListIterator it = lines.listIterator(); - while (it.hasNext()) { - it.set(replaceTags(faction, fplayer, it.next())); - } - return lines; - } + ListIterator it = lines.listIterator(); + while (it.hasNext()) { + it.set(replaceTags(faction, fplayer, it.next())); + } + return lines; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java index 037a9c03..4c33f291 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerFactionExpression.java @@ -18,80 +18,80 @@ import org.bukkit.event.Event; public class PlayerFactionExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerFactionExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction of %player%", "[the] %player%['s] faction"); - } + static { + Skript.registerExpression(PlayerFactionExpression.class, String.class, ExpressionType.SIMPLE, "[the] faction of %player%", "[the] %player%['s] faction"); + } - Expression playerExpression; + Expression playerExpression; - @Override - public Class getReturnType() { - return String.class; - } + @Override + public Class getReturnType() { + return String.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { + playerExpression = (Expression) exprs[0]; + return true; + } - @Override - public String toString(Event event, boolean debug) { - return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); + } - @Override - protected String[] get(Event event) { - Player player = playerExpression.getSingle(event); + @Override + protected String[] get(Event event) { + Player player = playerExpression.getSingle(event); - if (player != null) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - return new String[]{fPlayer.getFaction().getTag()}; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + return new String[]{fPlayer.getFaction().getTag()}; + } - return null; + return null; - } + } - @Override - public Class[] acceptChange(final Changer.ChangeMode mode) { - if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { - return CollectionUtils.array(String.class); - } - return null; - } + @Override + public Class[] acceptChange(final Changer.ChangeMode mode) { + if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { + return CollectionUtils.array(String.class); + } + return null; + } - @Override - public void change(Event event, Object[] delta, Changer.ChangeMode mode) { - Player player = playerExpression.getSingle(event); - if (player == null) { - return; - } + @Override + public void change(Event event, Object[] delta, Changer.ChangeMode mode) { + Player player = playerExpression.getSingle(event); + if (player == null) { + return; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - switch (mode) { - case DELETE: - case RESET: - fPlayer.setFaction(Factions.getInstance().getWilderness()); - break; - case SET: - Faction faction = Factions.getInstance().getByTag((String) delta[0]); - if (faction == null) { - faction = Factions.getInstance().getWilderness(); - } - fPlayer.setFaction(faction); - break; - default: - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case DELETE: + case RESET: + fPlayer.setFaction(Factions.getInstance().getWilderness()); + break; + case SET: + Faction faction = Factions.getInstance().getByTag((String) delta[0]); + if (faction == null) { + faction = Factions.getInstance().getWilderness(); + } + fPlayer.setFaction(faction); + break; + default: + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java index 928da2e5..f4d2c4c2 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerPowerExpression.java @@ -16,80 +16,80 @@ import org.bukkit.event.Event; public class PlayerPowerExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerPowerExpression.class, Number.class, ExpressionType.SIMPLE, "[the] power of %player%", "[the] %player%['s] power"); - } + static { + Skript.registerExpression(PlayerPowerExpression.class, Number.class, ExpressionType.SIMPLE, "[the] power of %player%", "[the] %player%['s] power"); + } - Expression playerExpression; + Expression playerExpression; - @Override - public Class getReturnType() { - return Double.class; - } + @Override + public Class getReturnType() { + return Double.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { + playerExpression = (Expression) exprs[0]; + return true; + } - @Override - public String toString(Event event, boolean debug) { - return "Player Power with expression player" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Power with expression player" + playerExpression.toString(event, debug); + } - @Override - protected Double[] get(Event event) { - Player player = playerExpression.getSingle(event); + @Override + protected Double[] get(Event event) { + Player player = playerExpression.getSingle(event); - if (player != null) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - return new Double[]{fPlayer.getFaction().getPower()}; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + return new Double[]{fPlayer.getFaction().getPower()}; + } - return null; + return null; - } + } - @Override - public Class[] acceptChange(final Changer.ChangeMode mode) { - if (mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE) { - return CollectionUtils.array(Number.class); - } - return null; - } + @Override + public Class[] acceptChange(final Changer.ChangeMode mode) { + if (mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.ADD || mode == Changer.ChangeMode.REMOVE) { + return CollectionUtils.array(Number.class); + } + return null; + } - @Override - public void change(Event event, Object[] delta, Changer.ChangeMode mode) { - Player player = playerExpression.getSingle(event); - if (player == null) { - return; - } + @Override + public void change(Event event, Object[] delta, Changer.ChangeMode mode) { + Player player = playerExpression.getSingle(event); + if (player == null) { + return; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - switch (mode) { - case ADD: - fPlayer.alterPower(Double.valueOf((Long) delta[0])); - break; - case REMOVE: - fPlayer.alterPower(Double.valueOf((Long) delta[0]) * -1); - break; - case RESET: - fPlayer.alterPower(fPlayer.getPowerMax() * -1); - break; - default: - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case ADD: + fPlayer.alterPower(Double.valueOf((Long) delta[0])); + break; + case REMOVE: + fPlayer.alterPower(Double.valueOf((Long) delta[0]) * -1); + break; + case RESET: + fPlayer.alterPower(fPlayer.getPowerMax() * -1); + break; + default: + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java index 13d96ade..238c6134 100644 --- a/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java +++ b/src/main/java/com/massivecraft/factions/skript/expressions/player/PlayerRoleExpression.java @@ -16,77 +16,77 @@ import org.bukkit.event.Event; public class PlayerRoleExpression extends SimpleExpression { - static { - Skript.registerExpression(PlayerRoleExpression.class, String.class, ExpressionType.SIMPLE, "[the] role of %player%", "[the] %player%['s] role"); - } + static { + Skript.registerExpression(PlayerRoleExpression.class, String.class, ExpressionType.SIMPLE, "[the] role of %player%", "[the] %player%['s] role"); + } - Expression playerExpression; + Expression playerExpression; - @Override - public Class getReturnType() { - return String.class; - } + @Override + public Class getReturnType() { + return String.class; + } - @Override - public boolean isSingle() { - return true; - } + @Override + public boolean isSingle() { + return true; + } - @SuppressWarnings("unchecked") - @Override - public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { - playerExpression = (Expression) exprs[0]; - return true; - } + @SuppressWarnings("unchecked") + @Override + public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, SkriptParser.ParseResult parser) { + playerExpression = (Expression) exprs[0]; + return true; + } - @Override - public String toString(Event event, boolean debug) { - return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); - } + @Override + public String toString(Event event, boolean debug) { + return "Player Faction Name Expression with expression player" + playerExpression.toString(event, debug); + } - @Override - protected String[] get(Event event) { - Player player = playerExpression.getSingle(event); + @Override + protected String[] get(Event event) { + Player player = playerExpression.getSingle(event); - if (player != null) { - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - return new String[]{fPlayer.getRole().toString()}; - } + if (player != null) { + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + return new String[]{fPlayer.getRole().toString()}; + } - return null; + return null; - } + } - @Override - public Class[] acceptChange(final Changer.ChangeMode mode) { - if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { - return CollectionUtils.array(String.class); - } - return null; - } + @Override + public Class[] acceptChange(final Changer.ChangeMode mode) { + if (mode == Changer.ChangeMode.DELETE || mode == Changer.ChangeMode.RESET || mode == Changer.ChangeMode.SET) { + return CollectionUtils.array(String.class); + } + return null; + } - @Override - public void change(Event event, Object[] delta, Changer.ChangeMode mode) { - Player player = playerExpression.getSingle(event); - if (player == null) { - return; - } + @Override + public void change(Event event, Object[] delta, Changer.ChangeMode mode) { + Player player = playerExpression.getSingle(event); + if (player == null) { + return; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - switch (mode) { - case DELETE: - case RESET: - fPlayer.setRole(Role.RECRUIT); - break; - case SET: - fPlayer.setRole(Role.fromString(((String) delta[0]).toLowerCase())); - break; - default: - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + switch (mode) { + case DELETE: + case RESET: + fPlayer.setRole(Role.RECRUIT); + break; + case SET: + fPlayer.setRole(Role.fromString(((String) delta[0]).toLowerCase())); + break; + default: + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/struct/BanInfo.java b/src/main/java/com/massivecraft/factions/struct/BanInfo.java index 365d7a31..8aacfe24 100644 --- a/src/main/java/com/massivecraft/factions/struct/BanInfo.java +++ b/src/main/java/com/massivecraft/factions/struct/BanInfo.java @@ -2,41 +2,41 @@ package com.massivecraft.factions.struct; public class BanInfo { - // FPlayer IDs - private final String banner; - private final String banned; - private final long time; + // FPlayer IDs + private final String banner; + private final String banned; + private final long time; - public BanInfo(String banner, String banned, long time) { - this.banner = banner; - this.banned = banned; - this.time = time; - } + public BanInfo(String banner, String banned, long time) { + this.banner = banner; + this.banned = banned; + this.time = time; + } - /** - * Get the FPlayer ID of the player who issued the ban. - * - * @return FPlayer ID. - */ - public String getBanner() { - return this.banner; - } + /** + * Get the FPlayer ID of the player who issued the ban. + * + * @return FPlayer ID. + */ + public String getBanner() { + return this.banner; + } - /** - * Get the FPlayer ID of the player who got banned. - * - * @return FPlayer ID. - */ - public String getBanned() { - return banned; - } + /** + * Get the FPlayer ID of the player who got banned. + * + * @return FPlayer ID. + */ + public String getBanned() { + return banned; + } - /** - * Get the server time when the ban was issued. - * - * @return system timestamp. - */ - public long getTime() { - return time; - } + /** + * Get the server time when the ban was issued. + * + * @return system timestamp. + */ + public long getTime() { + return time; + } } diff --git a/src/main/java/com/massivecraft/factions/struct/ChatMode.java b/src/main/java/com/massivecraft/factions/struct/ChatMode.java index 34536416..42471a1e 100644 --- a/src/main/java/com/massivecraft/factions/struct/ChatMode.java +++ b/src/main/java/com/massivecraft/factions/struct/ChatMode.java @@ -3,40 +3,40 @@ package com.massivecraft.factions.struct; import com.massivecraft.factions.zcore.util.TL; public enum ChatMode { - MOD(4, TL.CHAT_MOD), - FACTION(3, TL.CHAT_FACTION), - ALLIANCE(2, TL.CHAT_ALLIANCE), - TRUCE(1, TL.CHAT_TRUCE), - PUBLIC(0, TL.CHAT_PUBLIC); + MOD(4, TL.CHAT_MOD), + FACTION(3, TL.CHAT_FACTION), + ALLIANCE(2, TL.CHAT_ALLIANCE), + TRUCE(1, TL.CHAT_TRUCE), + PUBLIC(0, TL.CHAT_PUBLIC); - public final int value; - public final TL nicename; + public final int value; + public final TL nicename; - ChatMode(final int value, final TL nicename) { - this.value = value; - this.nicename = nicename; - } + ChatMode(final int value, final TL nicename) { + this.value = value; + this.nicename = nicename; + } - public boolean isAtLeast(ChatMode role) { - return this.value >= role.value; - } + public boolean isAtLeast(ChatMode role) { + return this.value >= role.value; + } - public boolean isAtMost(ChatMode role) { - return this.value <= role.value; - } + public boolean isAtMost(ChatMode role) { + return this.value <= role.value; + } - @Override - public String toString() { - return this.nicename.toString(); - } + @Override + public String toString() { + return this.nicename.toString(); + } - public ChatMode getNext() { - if (this == PUBLIC) { - return ALLIANCE; - } - if (this == ALLIANCE) { - return FACTION; - } - return PUBLIC; - } + public ChatMode getNext() { + if (this == PUBLIC) { + return ALLIANCE; + } + if (this == ALLIANCE) { + return FACTION; + } + return PUBLIC; + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Permission.java b/src/main/java/com/massivecraft/factions/struct/Permission.java index 3184485d..c174df31 100644 --- a/src/main/java/com/massivecraft/factions/struct/Permission.java +++ b/src/main/java/com/massivecraft/factions/struct/Permission.java @@ -1,125 +1,125 @@ -package com.massivecraft.factions.struct; - -import com.massivecraft.factions.SavageFactions; -import org.bukkit.command.CommandSender; - -public enum Permission { - MANAGE_SAFE_ZONE("managesafezone"), - MANAGE_WAR_ZONE("managewarzone"), - OWNERSHIP_BYPASS("ownershipbypass"), - ADMIN("admin"), - ADMIN_ANY("admin.any"), - AHOME("ahome"), - ANNOUNCE("announce"), - AUTOCLAIM("autoclaim"), - AUTO_LEAVE_BYPASS("autoleavebypass"), - BAN("ban"), - BYPASS("bypass"), - CHAT("chat"), - CHATSPY("chatspy"), - CLAIM("claim"), - CLAIMAT("claimat"), - CLAIM_LINE("claim.line"), - CLAIM_RADIUS("claim.radius"), - CONFIG("config"), - CONVERT("convert"), - CREATE("create"), - DEFAULTRANK("defaultrank"), - DEINVITE("deinvite"), - DESCRIPTION("description"), - DISBAND("disband"), - DISBAND_ANY("disband.any"), - FLY("fly"), - FOCUS("focus"), - HELP("help"), - HOME("home"), - INVITE("invite"), - JOIN("join"), - JOIN_ANY("join.any"), - JOIN_OTHERS("join.others"), - KICK("kick"), - KICK_ANY("kick.any"), - LEAVE("leave"), - LIST("list"), - LOCK("lock"), - MAP("map"), - MAPHEIGHT("mapheight"), - MOD("mod"), - COLEADER("coleader"), - MOD_ANY("mod.any"), - COLEADER_ANY("coleader.any"), - MODIFY_POWER("modifypower"), - MONEY_BALANCE("money.balance"), - MONEY_BALANCE_ANY("money.balance.any"), - MONEY_DEPOSIT("money.deposit"), - MONEY_WITHDRAW("money.withdraw"), - MONEY_WITHDRAW_ANY("money.withdraw.any"), - MONEY_F2F("money.f2f"), - MONEY_F2P("money.f2p"), - MONEY_P2F("money.p2f"), - MONITOR_LOGINS("monitorlogins"), - NO_BOOM("noboom"), - OPEN("open"), - OWNER("owner"), - OWNERLIST("ownerlist"), - SET_PEACEFUL("setpeaceful"), - SET_PERMANENT("setpermanent"), - SET_PERMANENTPOWER("setpermanentpower"), - SHOW_INVITES("showinvites"), - PAYPALSET("setpaypal"), - PERMISSIONS("permissions"), - POWERBOOST("powerboost"), - POWER("power"), - POWER_ANY("power.any"), - PROMOTE("promote"), - RELATION("relation"), - RELOAD("reload"), - SAVE("save"), - SETHOME("sethome"), - SETHOME_ANY("sethome.any"), - SHOW("show"), - STATUS("status"), - STEALTH("stealth"), - STUCK("stuck"), - TAG("tag"), - TNT("tnt"), - TITLE("title"), - TITLE_COLOR("title.color"), - TOGGLE_ALLIANCE_CHAT("togglealliancechat"), - UNCLAIM("unclaim"), - UNCLAIM_ALL("unclaimall"), - VERSION("version"), - SCOREBOARD("scoreboard"), - SEECHUNK("seechunk"), - SETWARP("setwarp"), - TOP("top"), - VAULT("vault"), - GETVAULT("getvault"), - SETMAXVAULTS("setmaxvaults"), - RULES("rules"), - CHECKPOINT("checkpoint"), - UPGRADES("upgrades"), - BANNER("banner"), - TPBANNER("tpbanner"), - KILLHOLOS("killholos"), - INSPECT("inspect"), - TNTFILL("tntfill"), - COORD("coords"), - SHOWCLAIMS("showclaims"), - WARP("warp"), - CHEST("Chest"); - - public final String node; - - Permission(final String node) { - this.node = "factions." + node; - } - - public boolean has(CommandSender sender, boolean informSenderIfNot) { - return SavageFactions.plugin.perm.has(sender, this.node, informSenderIfNot); - } - - public boolean has(CommandSender sender) { - return has(sender, false); - } -} +package com.massivecraft.factions.struct; + +import com.massivecraft.factions.SavageFactions; +import org.bukkit.command.CommandSender; + +public enum Permission { + MANAGE_SAFE_ZONE("managesafezone"), + MANAGE_WAR_ZONE("managewarzone"), + OWNERSHIP_BYPASS("ownershipbypass"), + ADMIN("admin"), + ADMIN_ANY("admin.any"), + AHOME("ahome"), + ANNOUNCE("announce"), + AUTOCLAIM("autoclaim"), + AUTO_LEAVE_BYPASS("autoleavebypass"), + BAN("ban"), + BYPASS("bypass"), + CHAT("chat"), + CHATSPY("chatspy"), + CLAIM("claim"), + CLAIMAT("claimat"), + CLAIM_LINE("claim.line"), + CLAIM_RADIUS("claim.radius"), + CONFIG("config"), + CONVERT("convert"), + CREATE("create"), + DEFAULTRANK("defaultrank"), + DEINVITE("deinvite"), + DESCRIPTION("description"), + DISBAND("disband"), + DISBAND_ANY("disband.any"), + FLY("fly"), + FOCUS("focus"), + HELP("help"), + HOME("home"), + INVITE("invite"), + JOIN("join"), + JOIN_ANY("join.any"), + JOIN_OTHERS("join.others"), + KICK("kick"), + KICK_ANY("kick.any"), + LEAVE("leave"), + LIST("list"), + LOCK("lock"), + MAP("map"), + MAPHEIGHT("mapheight"), + MOD("mod"), + COLEADER("coleader"), + MOD_ANY("mod.any"), + COLEADER_ANY("coleader.any"), + MODIFY_POWER("modifypower"), + MONEY_BALANCE("money.balance"), + MONEY_BALANCE_ANY("money.balance.any"), + MONEY_DEPOSIT("money.deposit"), + MONEY_WITHDRAW("money.withdraw"), + MONEY_WITHDRAW_ANY("money.withdraw.any"), + MONEY_F2F("money.f2f"), + MONEY_F2P("money.f2p"), + MONEY_P2F("money.p2f"), + MONITOR_LOGINS("monitorlogins"), + NO_BOOM("noboom"), + OPEN("open"), + OWNER("owner"), + OWNERLIST("ownerlist"), + SET_PEACEFUL("setpeaceful"), + SET_PERMANENT("setpermanent"), + SET_PERMANENTPOWER("setpermanentpower"), + SHOW_INVITES("showinvites"), + PAYPALSET("setpaypal"), + PERMISSIONS("permissions"), + POWERBOOST("powerboost"), + POWER("power"), + POWER_ANY("power.any"), + PROMOTE("promote"), + RELATION("relation"), + RELOAD("reload"), + SAVE("save"), + SETHOME("sethome"), + SETHOME_ANY("sethome.any"), + SHOW("show"), + STATUS("status"), + STEALTH("stealth"), + STUCK("stuck"), + TAG("tag"), + TNT("tnt"), + TITLE("title"), + TITLE_COLOR("title.color"), + TOGGLE_ALLIANCE_CHAT("togglealliancechat"), + UNCLAIM("unclaim"), + UNCLAIM_ALL("unclaimall"), + VERSION("version"), + SCOREBOARD("scoreboard"), + SEECHUNK("seechunk"), + SETWARP("setwarp"), + TOP("top"), + VAULT("vault"), + GETVAULT("getvault"), + SETMAXVAULTS("setmaxvaults"), + RULES("rules"), + CHECKPOINT("checkpoint"), + UPGRADES("upgrades"), + BANNER("banner"), + TPBANNER("tpbanner"), + KILLHOLOS("killholos"), + INSPECT("inspect"), + TNTFILL("tntfill"), + COORD("coords"), + SHOWCLAIMS("showclaims"), + WARP("warp"), + CHEST("Chest"); + + public final String node; + + Permission(final String node) { + this.node = "factions." + node; + } + + public boolean has(CommandSender sender, boolean informSenderIfNot) { + return SavageFactions.plugin.perm.has(sender, this.node, informSenderIfNot); + } + + public boolean has(CommandSender sender) { + return has(sender, false); + } +} diff --git a/src/main/java/com/massivecraft/factions/struct/Relation.java b/src/main/java/com/massivecraft/factions/struct/Relation.java index 2072352b..66d6039f 100644 --- a/src/main/java/com/massivecraft/factions/struct/Relation.java +++ b/src/main/java/com/massivecraft/factions/struct/Relation.java @@ -15,221 +15,221 @@ import java.util.List; public enum Relation implements Permissable { - MEMBER(4, TL.RELATION_MEMBER_SINGULAR.toString()), - ALLY(3, TL.RELATION_ALLY_SINGULAR.toString()), - TRUCE(2, TL.RELATION_TRUCE_SINGULAR.toString()), - NEUTRAL(1, TL.RELATION_NEUTRAL_SINGULAR.toString()), - ENEMY(0, TL.RELATION_ENEMY_SINGULAR.toString()); + MEMBER(4, TL.RELATION_MEMBER_SINGULAR.toString()), + ALLY(3, TL.RELATION_ALLY_SINGULAR.toString()), + TRUCE(2, TL.RELATION_TRUCE_SINGULAR.toString()), + NEUTRAL(1, TL.RELATION_NEUTRAL_SINGULAR.toString()), + ENEMY(0, TL.RELATION_ENEMY_SINGULAR.toString()); - public final int value; - public final String nicename; + public final int value; + public final String nicename; - Relation(final int value, final String nicename) { - this.value = value; - this.nicename = nicename; - } + Relation(final int value, final String nicename) { + this.value = value; + this.nicename = nicename; + } - public static Relation fromString(String s) { - // Because Java 6 doesn't allow String switches :( - if (s.equalsIgnoreCase(MEMBER.nicename)) { - return MEMBER; - } else if (s.equalsIgnoreCase(ALLY.nicename)) { - return ALLY; - } else if (s.equalsIgnoreCase(TRUCE.nicename)) { - return TRUCE; - } else if (s.equalsIgnoreCase(ENEMY.nicename)) { - return ENEMY; - } else { - return NEUTRAL; // If they somehow mess things up, go back to default behavior. - } - } + public static Relation fromString(String s) { + // Because Java 6 doesn't allow String switches :( + if (s.equalsIgnoreCase(MEMBER.nicename)) { + return MEMBER; + } else if (s.equalsIgnoreCase(ALLY.nicename)) { + return ALLY; + } else if (s.equalsIgnoreCase(TRUCE.nicename)) { + return TRUCE; + } else if (s.equalsIgnoreCase(ENEMY.nicename)) { + return ENEMY; + } else { + return NEUTRAL; // If they somehow mess things up, go back to default behavior. + } + } - @Override - public String toString() { - return this.nicename; - } + @Override + public String toString() { + return this.nicename; + } - public String getTranslation() { - try { - return TL.valueOf("RELATION_" + name() + "_SINGULAR").toString(); - } catch (IllegalArgumentException e) { - return toString(); - } - } + public String getTranslation() { + try { + return TL.valueOf("RELATION_" + name() + "_SINGULAR").toString(); + } catch (IllegalArgumentException e) { + return toString(); + } + } - public String getPluralTranslation() { - for (TL t : TL.values()) { - if (t.name().equalsIgnoreCase("RELATION_" + name() + "_PLURAL")) { - return t.toString(); - } - } - return toString(); - } + public String getPluralTranslation() { + for (TL t : TL.values()) { + if (t.name().equalsIgnoreCase("RELATION_" + name() + "_PLURAL")) { + return t.toString(); + } + } + return toString(); + } - public boolean isMember() { - return this == MEMBER; - } + public boolean isMember() { + return this == MEMBER; + } - public boolean isAlly() { - return this == ALLY; - } + public boolean isAlly() { + return this == ALLY; + } - public boolean isTruce() { - return this == TRUCE; - } + public boolean isTruce() { + return this == TRUCE; + } - public boolean isNeutral() { - return this == NEUTRAL; - } + public boolean isNeutral() { + return this == NEUTRAL; + } - public boolean isEnemy() { - return this == ENEMY; - } + public boolean isEnemy() { + return this == ENEMY; + } - public boolean isAtLeast(Relation relation) { - return this.value >= relation.value; - } + public boolean isAtLeast(Relation relation) { + return this.value >= relation.value; + } - public boolean isAtMost(Relation relation) { - return this.value <= relation.value; - } + public boolean isAtMost(Relation relation) { + return this.value <= relation.value; + } - public ChatColor getColor() { + public ChatColor getColor() { - switch (this) { - case MEMBER: - return Conf.colorMember; - case ALLY: - return Conf.colorAlly; - case NEUTRAL: - return Conf.colorNeutral; - case TRUCE: - return Conf.colorTruce; - default: - return Conf.colorEnemy; - } - } + switch (this) { + case MEMBER: + return Conf.colorMember; + case ALLY: + return Conf.colorAlly; + case NEUTRAL: + return Conf.colorNeutral; + case TRUCE: + return Conf.colorTruce; + default: + return Conf.colorEnemy; + } + } - // return appropriate Conf setting for DenyBuild based on this relation and their online status - public boolean confDenyBuild(boolean online) { - if (isMember()) { - return false; - } + // return appropriate Conf setting for DenyBuild based on this relation and their online status + public boolean confDenyBuild(boolean online) { + if (isMember()) { + return false; + } - if (online) { - if (isEnemy()) { - return Conf.territoryEnemyDenyBuild; - } else if (isAlly()) { - return Conf.territoryAllyDenyBuild; - } else if (isTruce()) { - return Conf.territoryTruceDenyBuild; - } else { - return Conf.territoryDenyBuild; - } - } else { - if (isEnemy()) { - return Conf.territoryEnemyDenyBuildWhenOffline; - } else if (isAlly()) { - return Conf.territoryAllyDenyBuildWhenOffline; - } else if (isTruce()) { - return Conf.territoryTruceDenyBuildWhenOffline; - } else { - return Conf.territoryDenyBuildWhenOffline; - } - } - } + if (online) { + if (isEnemy()) { + return Conf.territoryEnemyDenyBuild; + } else if (isAlly()) { + return Conf.territoryAllyDenyBuild; + } else if (isTruce()) { + return Conf.territoryTruceDenyBuild; + } else { + return Conf.territoryDenyBuild; + } + } else { + if (isEnemy()) { + return Conf.territoryEnemyDenyBuildWhenOffline; + } else if (isAlly()) { + return Conf.territoryAllyDenyBuildWhenOffline; + } else if (isTruce()) { + return Conf.territoryTruceDenyBuildWhenOffline; + } else { + return Conf.territoryDenyBuildWhenOffline; + } + } + } - // return appropriate Conf setting for PainBuild based on this relation and their online status - public boolean confPainBuild(boolean online) { - if (isMember()) { - return false; - } + // return appropriate Conf setting for PainBuild based on this relation and their online status + public boolean confPainBuild(boolean online) { + if (isMember()) { + return false; + } - if (online) { - if (isEnemy()) { - return Conf.territoryEnemyPainBuild; - } else if (isAlly()) { - return Conf.territoryAllyPainBuild; - } else if (isTruce()) { - return Conf.territoryTrucePainBuild; - } else { - return Conf.territoryPainBuild; - } - } else { - if (isEnemy()) { - return Conf.territoryEnemyPainBuildWhenOffline; - } else if (isAlly()) { - return Conf.territoryAllyPainBuildWhenOffline; - } else if (isTruce()) { - return Conf.territoryTrucePainBuildWhenOffline; - } else { - return Conf.territoryPainBuildWhenOffline; - } - } - } + if (online) { + if (isEnemy()) { + return Conf.territoryEnemyPainBuild; + } else if (isAlly()) { + return Conf.territoryAllyPainBuild; + } else if (isTruce()) { + return Conf.territoryTrucePainBuild; + } else { + return Conf.territoryPainBuild; + } + } else { + if (isEnemy()) { + return Conf.territoryEnemyPainBuildWhenOffline; + } else if (isAlly()) { + return Conf.territoryAllyPainBuildWhenOffline; + } else if (isTruce()) { + return Conf.territoryTrucePainBuildWhenOffline; + } else { + return Conf.territoryPainBuildWhenOffline; + } + } + } - // return appropriate Conf setting for DenyUseage based on this relation - public boolean confDenyUseage() { - if (isMember()) { - return false; - } else if (isEnemy()) { - return Conf.territoryEnemyDenyUseage; - } else if (isAlly()) { - return Conf.territoryAllyDenyUseage; - } else if (isTruce()) { - return Conf.territoryTruceDenyUseage; - } else { - return Conf.territoryDenyUseage; - } - } + // return appropriate Conf setting for DenyUseage based on this relation + public boolean confDenyUseage() { + if (isMember()) { + return false; + } else if (isEnemy()) { + return Conf.territoryEnemyDenyUseage; + } else if (isAlly()) { + return Conf.territoryAllyDenyUseage; + } else if (isTruce()) { + return Conf.territoryTruceDenyUseage; + } else { + return Conf.territoryDenyUseage; + } + } - public double getRelationCost() { - if (isEnemy()) { - return Conf.econCostEnemy; - } else if (isAlly()) { - return Conf.econCostAlly; - } else if (isTruce()) { - return Conf.econCostTruce; - } else { - return Conf.econCostNeutral; - } - } + public double getRelationCost() { + if (isEnemy()) { + return Conf.econCostEnemy; + } else if (isAlly()) { + return Conf.econCostAlly; + } else if (isTruce()) { + return Conf.econCostTruce; + } else { + return Conf.econCostNeutral; + } + } - // Utility method to build items for F Perm GUI - @Override - public ItemStack buildItem() { - final ConfigurationSection RELATION_CONFIG = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.relation"); + // Utility method to build items for F Perm GUI + @Override + public ItemStack buildItem() { + final ConfigurationSection RELATION_CONFIG = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.relation"); - String displayName = replacePlaceholders(RELATION_CONFIG.getString("placeholder-item.name", "")); - List lore = new ArrayList<>(); + String displayName = replacePlaceholders(RELATION_CONFIG.getString("placeholder-item.name", "")); + List lore = new ArrayList<>(); - Material material = Material.matchMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase())); - if (material == null) { - return null; - } + Material material = Material.matchMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase())); + if (material == null) { + return null; + } - ItemStack item = new ItemStack(material); - ItemMeta itemMeta = item.getItemMeta(); + ItemStack item = new ItemStack(material); + ItemMeta itemMeta = item.getItemMeta(); - for (String loreLine : RELATION_CONFIG.getStringList("placeholder-item.lore")) { - lore.add(replacePlaceholders(loreLine)); - } + for (String loreLine : RELATION_CONFIG.getStringList("placeholder-item.lore")) { + lore.add(replacePlaceholders(loreLine)); + } - itemMeta.setDisplayName(displayName); - itemMeta.setLore(lore); - item.setItemMeta(itemMeta); + itemMeta.setDisplayName(displayName); + itemMeta.setLore(lore); + item.setItemMeta(itemMeta); - return item; - } + return item; + } - public String replacePlaceholders(String string) { - string = ChatColor.translateAlternateColorCodes('&', string); + public String replacePlaceholders(String string) { + string = ChatColor.translateAlternateColorCodes('&', string); - String permissableName = nicename.substring(0, 1).toUpperCase() + nicename.substring(1); + String permissableName = nicename.substring(0, 1).toUpperCase() + nicename.substring(1); - string = string.replace("{relation-color}", getColor().toString()); - string = string.replace("{relation}", permissableName); + string = string.replace("{relation-color}", getColor().toString()); + string = string.replace("{relation}", permissableName); - return string; - } + return string; + } } diff --git a/src/main/java/com/massivecraft/factions/struct/Role.java b/src/main/java/com/massivecraft/factions/struct/Role.java index 92a94629..226e912e 100644 --- a/src/main/java/com/massivecraft/factions/struct/Role.java +++ b/src/main/java/com/massivecraft/factions/struct/Role.java @@ -15,140 +15,140 @@ import java.util.ArrayList; import java.util.List; public enum Role implements Permissable { - LEADER(4, TL.ROLE_LEADER), - COLEADER(3, TL.ROLE_COLEADER), - MODERATOR(2, TL.ROLE_MODERATOR), - NORMAL(1, TL.ROLE_NORMAL), - RECRUIT(0, TL.ROLE_RECRUIT); + LEADER(4, TL.ROLE_LEADER), + COLEADER(3, TL.ROLE_COLEADER), + MODERATOR(2, TL.ROLE_MODERATOR), + NORMAL(1, TL.ROLE_NORMAL), + RECRUIT(0, TL.ROLE_RECRUIT); - public final int value; - public final String nicename; - public final TL translation; + public final int value; + public final String nicename; + public final TL translation; - Role(final int value, final TL translation) { - this.value = value; - this.nicename = translation.toString(); - this.translation = translation; - } + Role(final int value, final TL translation) { + this.value = value; + this.nicename = translation.toString(); + this.translation = translation; + } - public static Role getRelative(Role role, int relative) { - return Role.getByValue(role.value + relative); - } + public static Role getRelative(Role role, int relative) { + return Role.getByValue(role.value + relative); + } - public static Role getByValue(int value) { - switch (value) { - case 0: - return RECRUIT; - case 1: - return NORMAL; - case 2: - return MODERATOR; - case 3: - return COLEADER; - case 4: - return LEADER; - } + public static Role getByValue(int value) { + switch (value) { + case 0: + return RECRUIT; + case 1: + return NORMAL; + case 2: + return MODERATOR; + case 3: + return COLEADER; + case 4: + return LEADER; + } - return null; - } + return null; + } - public static Role fromString(String check) { - switch (check.toLowerCase()) { - case "leader": - case "admin": - return LEADER; - case "coleader": - return COLEADER; - case "mod": - case "moderator": - return MODERATOR; - case "normal": - case "member": - return NORMAL; - case "recruit": - case "rec": - return RECRUIT; - } + public static Role fromString(String check) { + switch (check.toLowerCase()) { + case "leader": + case "admin": + return LEADER; + case "coleader": + return COLEADER; + case "mod": + case "moderator": + return MODERATOR; + case "normal": + case "member": + return NORMAL; + case "recruit": + case "rec": + return RECRUIT; + } - return null; - } + return null; + } - public boolean isAtLeast(Role role) { - return this.value >= role.value; - } + public boolean isAtLeast(Role role) { + return this.value >= role.value; + } - public boolean isAtMost(Role role) { - return this.value <= role.value; - } + public boolean isAtMost(Role role) { + return this.value <= role.value; + } - @Override - public String toString() { - return this.nicename; - } + @Override + public String toString() { + return this.nicename; + } - public TL getTranslation() { - return translation; - } + public TL getTranslation() { + return translation; + } - public String getPrefix() { + public String getPrefix() { - switch (this) { - case LEADER: - return Conf.prefixLeader; - case COLEADER: - return Conf.prefixCoLeader; - case MODERATOR: - return Conf.prefixMod; - case NORMAL: - return Conf.prefixNormal; - case RECRUIT: - return Conf.prefixRecruit; - } + switch (this) { + case LEADER: + return Conf.prefixLeader; + case COLEADER: + return Conf.prefixCoLeader; + case MODERATOR: + return Conf.prefixMod; + case NORMAL: + return Conf.prefixNormal; + case RECRUIT: + return Conf.prefixRecruit; + } - return ""; - } + return ""; + } - // Utility method to build items for F Perm GUI - @Override - public ItemStack buildItem() { - final ConfigurationSection RELATION_CONFIG = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.relation"); + // Utility method to build items for F Perm GUI + @Override + public ItemStack buildItem() { + final ConfigurationSection RELATION_CONFIG = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.relation"); - String displayName = replacePlaceholders(RELATION_CONFIG.getString("placeholder-item.name", "")); - List lore = new ArrayList<>(); + String displayName = replacePlaceholders(RELATION_CONFIG.getString("placeholder-item.name", "")); + List lore = new ArrayList<>(); - Material material = Material.matchMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase(), "STAINED_CLAY")); - if (material == null) { - return null; - } + Material material = Material.matchMaterial(RELATION_CONFIG.getString("materials." + name().toLowerCase(), "STAINED_CLAY")); + if (material == null) { + return null; + } - ItemStack item = new ItemStack(material); - ItemMeta itemMeta = item.getItemMeta(); + ItemStack item = new ItemStack(material); + ItemMeta itemMeta = item.getItemMeta(); - for (String loreLine : RELATION_CONFIG.getStringList("placeholder-item.lore")) { - lore.add(replacePlaceholders(loreLine)); - } + for (String loreLine : RELATION_CONFIG.getStringList("placeholder-item.lore")) { + lore.add(replacePlaceholders(loreLine)); + } - itemMeta.setDisplayName(displayName); - itemMeta.setLore(lore); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - } + itemMeta.setDisplayName(displayName); + itemMeta.setLore(lore); + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + } - item.setItemMeta(itemMeta); + item.setItemMeta(itemMeta); - return item; - } + return item; + } - public String replacePlaceholders(String string) { - string = ChatColor.translateAlternateColorCodes('&', string); + public String replacePlaceholders(String string) { + string = ChatColor.translateAlternateColorCodes('&', string); - String permissableName = nicename.substring(0, 1).toUpperCase() + nicename.substring(1); + String permissableName = nicename.substring(0, 1).toUpperCase() + nicename.substring(1); - string = string.replace("{relation-color}", ChatColor.GREEN.toString()); - string = string.replace("{relation}", permissableName); + string = string.replace("{relation-color}", ChatColor.GREEN.toString()); + string = string.replace("{relation}", permissableName); - return string; - } + return string; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java index a4149c94..f2096851 100644 --- a/src/main/java/com/massivecraft/factions/util/AsciiCompass.java +++ b/src/main/java/com/massivecraft/factions/util/AsciiCompass.java @@ -7,104 +7,104 @@ import java.util.ArrayList; public class AsciiCompass { - public static Point getCompassPointForDirection(double inDegrees) { - double degrees = (inDegrees - 180) % 360; - if (degrees < 0) { - degrees += 360; - } + public static Point getCompassPointForDirection(double inDegrees) { + double degrees = (inDegrees - 180) % 360; + if (degrees < 0) { + degrees += 360; + } - if (0 <= degrees && degrees < 22.5) { - return Point.N; - } else if (22.5 <= degrees && degrees < 67.5) { - return Point.NE; - } else if (67.5 <= degrees && degrees < 112.5) { - return Point.E; - } else if (112.5 <= degrees && degrees < 157.5) { - return Point.SE; - } else if (157.5 <= degrees && degrees < 202.5) { - return Point.S; - } else if (202.5 <= degrees && degrees < 247.5) { - return Point.SW; - } else if (247.5 <= degrees && degrees < 292.5) { - return Point.W; - } else if (292.5 <= degrees && degrees < 337.5) { - return Point.NW; - } else if (337.5 <= degrees && degrees < 360.0) { - return Point.N; - } else { - return null; - } - } + if (0 <= degrees && degrees < 22.5) { + return Point.N; + } else if (22.5 <= degrees && degrees < 67.5) { + return Point.NE; + } else if (67.5 <= degrees && degrees < 112.5) { + return Point.E; + } else if (112.5 <= degrees && degrees < 157.5) { + return Point.SE; + } else if (157.5 <= degrees && degrees < 202.5) { + return Point.S; + } else if (202.5 <= degrees && degrees < 247.5) { + return Point.SW; + } else if (247.5 <= degrees && degrees < 292.5) { + return Point.W; + } else if (292.5 <= degrees && degrees < 337.5) { + return Point.NW; + } else if (337.5 <= degrees && degrees < 360.0) { + return Point.N; + } else { + return null; + } + } - public static ArrayList getAsciiCompass(Point point, ChatColor colorActive, String colorDefault) { - ArrayList ret = new ArrayList<>(); - String row; + public static ArrayList getAsciiCompass(Point point, ChatColor colorActive, String colorDefault) { + ArrayList ret = new ArrayList<>(); + String row; - row = ""; - row += Point.NW.toString(Point.NW == point, colorActive, colorDefault); - row += Point.N.toString(Point.N == point, colorActive, colorDefault); - row += Point.NE.toString(Point.NE == point, colorActive, colorDefault); - ret.add(row); + row = ""; + row += Point.NW.toString(Point.NW == point, colorActive, colorDefault); + row += Point.N.toString(Point.N == point, colorActive, colorDefault); + row += Point.NE.toString(Point.NE == point, colorActive, colorDefault); + ret.add(row); - row = ""; - row += Point.W.toString(Point.W == point, colorActive, colorDefault); - row += colorDefault + "+"; - row += Point.E.toString(Point.E == point, colorActive, colorDefault); - ret.add(row); + row = ""; + row += Point.W.toString(Point.W == point, colorActive, colorDefault); + row += colorDefault + "+"; + row += Point.E.toString(Point.E == point, colorActive, colorDefault); + ret.add(row); - row = ""; - row += Point.SW.toString(Point.SW == point, colorActive, colorDefault); - row += Point.S.toString(Point.S == point, colorActive, colorDefault); - row += Point.SE.toString(Point.SE == point, colorActive, colorDefault); - ret.add(row); + row = ""; + row += Point.SW.toString(Point.SW == point, colorActive, colorDefault); + row += Point.S.toString(Point.S == point, colorActive, colorDefault); + row += Point.SE.toString(Point.SE == point, colorActive, colorDefault); + ret.add(row); - return ret; - } + return ret; + } - public static ArrayList getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) { - return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault); - } + public static ArrayList getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) { + return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault); + } - public enum Point { + public enum Point { - N('N'), - NE('/'), - E('E'), - SE('\\'), - S('S'), - SW('/'), - W('W'), - NW('\\'); + N('N'), + NE('/'), + E('E'), + SE('\\'), + S('S'), + SW('/'), + W('W'), + NW('\\'); - public final char asciiChar; + public final char asciiChar; - Point(final char asciiChar) { - this.asciiChar = asciiChar; - } + Point(final char asciiChar) { + this.asciiChar = asciiChar; + } - @Override - public String toString() { - return String.valueOf(this.asciiChar); - } + @Override + public String toString() { + return String.valueOf(this.asciiChar); + } - public String getTranslation() { - if (this == N) { - return TL.COMPASS_SHORT_NORTH.toString(); - } - if (this == E) { - return TL.COMPASS_SHORT_EAST.toString(); - } - if (this == S) { - return TL.COMPASS_SHORT_SOUTH.toString(); - } - if (this == W) { - return TL.COMPASS_SHORT_WEST.toString(); - } - return toString(); - } + public String getTranslation() { + if (this == N) { + return TL.COMPASS_SHORT_NORTH.toString(); + } + if (this == E) { + return TL.COMPASS_SHORT_EAST.toString(); + } + if (this == S) { + return TL.COMPASS_SHORT_SOUTH.toString(); + } + if (this == W) { + return TL.COMPASS_SHORT_WEST.toString(); + } + return toString(); + } - public String toString(boolean isActive, ChatColor colorActive, String colorDefault) { - return (isActive ? colorActive : colorDefault) + getTranslation(); - } - } + public String toString(boolean isActive, ChatColor colorActive, String colorDefault) { + return (isActive ? colorActive : colorDefault) + getTranslation(); + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java b/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java index 0cc7fd62..aae7392a 100644 --- a/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java +++ b/src/main/java/com/massivecraft/factions/util/AutoLeaveProcessTask.java @@ -10,84 +10,84 @@ import java.util.logging.Level; public class AutoLeaveProcessTask extends BukkitRunnable { - private transient boolean readyToGo = false; - private transient boolean finished = false; - private transient ListIterator iterator; - private transient double toleranceMillis; + private transient boolean readyToGo = false; + private transient boolean finished = false; + private transient ListIterator iterator; + private transient double toleranceMillis; - public AutoLeaveProcessTask() { - ArrayList fplayers = (ArrayList) FPlayers.getInstance().getAllFPlayers(); - this.iterator = fplayers.listIterator(); - this.toleranceMillis = Conf.autoLeaveAfterDaysOfInactivity * 24 * 60 * 60 * 1000; - this.readyToGo = true; - this.finished = false; - } + public AutoLeaveProcessTask() { + ArrayList fplayers = (ArrayList) FPlayers.getInstance().getAllFPlayers(); + this.iterator = fplayers.listIterator(); + this.toleranceMillis = Conf.autoLeaveAfterDaysOfInactivity * 24 * 60 * 60 * 1000; + this.readyToGo = true; + this.finished = false; + } - public void run() { - if (Conf.autoLeaveAfterDaysOfInactivity <= 0.0 || Conf.autoLeaveRoutineMaxMillisecondsPerTick <= 0.0) { - this.stop(); - return; - } + public void run() { + if (Conf.autoLeaveAfterDaysOfInactivity <= 0.0 || Conf.autoLeaveRoutineMaxMillisecondsPerTick <= 0.0) { + this.stop(); + return; + } - if (!readyToGo) { - return; - } - // this is set so it only does one iteration at a time, no matter how frequently the timer fires - readyToGo = false; - // and this is tracked to keep one iteration from dragging on too long and possibly choking the system if there are a very large number of players to go through - long loopStartTime = System.currentTimeMillis(); + if (!readyToGo) { + return; + } + // this is set so it only does one iteration at a time, no matter how frequently the timer fires + readyToGo = false; + // and this is tracked to keep one iteration from dragging on too long and possibly choking the system if there are a very large number of players to go through + long loopStartTime = System.currentTimeMillis(); - while (iterator.hasNext()) { - long now = System.currentTimeMillis(); + while (iterator.hasNext()) { + long now = System.currentTimeMillis(); - // if this iteration has been running for maximum time, stop to take a breather until next tick - if (now > loopStartTime + Conf.autoLeaveRoutineMaxMillisecondsPerTick) { - readyToGo = true; - return; - } + // if this iteration has been running for maximum time, stop to take a breather until next tick + if (now > loopStartTime + Conf.autoLeaveRoutineMaxMillisecondsPerTick) { + readyToGo = true; + return; + } - FPlayer fplayer = iterator.next(); + FPlayer fplayer = iterator.next(); - // Check if they should be exempt from this. - if (!fplayer.willAutoLeave()) { - SavageFactions.plugin.debug(Level.INFO, fplayer.getName() + " was going to be auto-removed but was set not to."); - continue; - } + // Check if they should be exempt from this. + if (!fplayer.willAutoLeave()) { + SavageFactions.plugin.debug(Level.INFO, fplayer.getName() + " was going to be auto-removed but was set not to."); + continue; + } - if (fplayer.isOffline() && now - fplayer.getLastLoginTime() > toleranceMillis) { - if (Conf.logFactionLeave || Conf.logFactionKick) { - SavageFactions.plugin.log("Player " + fplayer.getName() + " was auto-removed due to inactivity."); - } + if (fplayer.isOffline() && now - fplayer.getLastLoginTime() > toleranceMillis) { + if (Conf.logFactionLeave || Conf.logFactionKick) { + SavageFactions.plugin.log("Player " + fplayer.getName() + " was auto-removed due to inactivity."); + } - // if player is faction admin, sort out the faction since he's going away - if (fplayer.getRole() == Role.LEADER) { - Faction faction = fplayer.getFaction(); - if (faction != null) { - fplayer.getFaction().promoteNewLeader(true); - } - } + // if player is faction admin, sort out the faction since he's going away + if (fplayer.getRole() == Role.LEADER) { + Faction faction = fplayer.getFaction(); + if (faction != null) { + fplayer.getFaction().promoteNewLeader(true); + } + } - fplayer.leave(false); - iterator.remove(); // go ahead and remove this list's link to the FPlayer object - if (Conf.autoLeaveDeleteFPlayerData) { - fplayer.remove(); - } - } - } + fplayer.leave(false); + iterator.remove(); // go ahead and remove this list's link to the FPlayer object + if (Conf.autoLeaveDeleteFPlayerData) { + fplayer.remove(); + } + } + } - // looks like we've finished - this.stop(); - } + // looks like we've finished + this.stop(); + } - // we're done, shut down - public void stop() { - readyToGo = false; - finished = true; + // we're done, shut down + public void stop() { + readyToGo = false; + finished = true; - this.cancel(); - } + this.cancel(); + } - public boolean isFinished() { - return finished; - } + public boolean isFinished() { + return finished; + } } diff --git a/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java b/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java index a13ca1d3..4ffd75b6 100644 --- a/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java +++ b/src/main/java/com/massivecraft/factions/util/AutoLeaveTask.java @@ -5,24 +5,24 @@ import com.massivecraft.factions.SavageFactions; public class AutoLeaveTask implements Runnable { - private static AutoLeaveProcessTask task; - double rate; + private static AutoLeaveProcessTask task; + double rate; - public AutoLeaveTask() { - this.rate = Conf.autoLeaveRoutineRunsEveryXMinutes; - } + public AutoLeaveTask() { + this.rate = Conf.autoLeaveRoutineRunsEveryXMinutes; + } - public synchronized void run() { - if (task != null && !task.isFinished()) { - return; - } + public synchronized void run() { + if (task != null && !task.isFinished()) { + return; + } - task = new AutoLeaveProcessTask(); - task.runTaskTimer(SavageFactions.plugin, 1, 1); + task = new AutoLeaveProcessTask(); + task.runTaskTimer(SavageFactions.plugin, 1, 1); - // maybe setting has been changed? if so, restart this task at new rate - if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) { - SavageFactions.plugin.startAutoLeaveTask(true); - } - } + // maybe setting has been changed? if so, restart this task at new rate + if (this.rate != Conf.autoLeaveRoutineRunsEveryXMinutes) { + SavageFactions.plugin.startAutoLeaveTask(true); + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java index f83b7328..ce552584 100644 --- a/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java +++ b/src/main/java/com/massivecraft/factions/util/ClipPlaceholderAPIManager.java @@ -15,151 +15,151 @@ import java.util.UUID; public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements Relational { - // Identifier for this expansion - @Override - public String getIdentifier() { - return "factionsuuid"; - } + // Identifier for this expansion + @Override + public String getIdentifier() { + return "factionsuuid"; + } - @Override - public String getAuthor() { - return "drtshock"; - } + @Override + public String getAuthor() { + return "drtshock"; + } - // Since we are registering this expansion from the dependency, this can be null - @Override - public String getPlugin() { - return null; - } + // Since we are registering this expansion from the dependency, this can be null + @Override + public String getPlugin() { + return null; + } - // Return the plugin version since this expansion is bundled with the dependency - @Override - public String getVersion() { - return SavageFactions.plugin.getDescription().getVersion(); - } + // Return the plugin version since this expansion is bundled with the dependency + @Override + public String getVersion() { + return SavageFactions.plugin.getDescription().getVersion(); + } - // Relational placeholders - @Override - public String onPlaceholderRequest(Player p1, Player p2, String placeholder) { - if (p1 == null || p2 == null || placeholder == null) { - return ""; - } + // Relational placeholders + @Override + public String onPlaceholderRequest(Player p1, Player p2, String placeholder) { + if (p1 == null || p2 == null || placeholder == null) { + return ""; + } - FPlayer fp1 = FPlayers.getInstance().getByPlayer(p1); - FPlayer fp2 = FPlayers.getInstance().getByPlayer(p2); - if (fp1 == null || fp2 == null) { - return ""; - } + FPlayer fp1 = FPlayers.getInstance().getByPlayer(p1); + FPlayer fp2 = FPlayers.getInstance().getByPlayer(p2); + if (fp1 == null || fp2 == null) { + return ""; + } - switch (placeholder) { - case "relation": - String relationName = fp1.getRelationTo(fp2).nicename; - return relationName != null ? relationName : ""; - case "relation_color": - ChatColor color = fp1.getColorTo(fp2); - return color != null ? color.toString() : ""; - } + switch (placeholder) { + case "relation": + String relationName = fp1.getRelationTo(fp2).nicename; + return relationName != null ? relationName : ""; + case "relation_color": + ChatColor color = fp1.getColorTo(fp2); + return color != null ? color.toString() : ""; + } - return null; - } + return null; + } - @Override - public String onPlaceholderRequest(Player player, String placeholder) { - if (player == null || placeholder == null) { - return ""; - } + @Override + public String onPlaceholderRequest(Player player, String placeholder) { + if (player == null || placeholder == null) { + return ""; + } - FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); - Faction faction = fPlayer.getFaction(); - switch (placeholder) { - // First list player stuff - case "player_name": - return fPlayer.getName(); - case "player_lastseen": - String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fPlayer.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; - return fPlayer.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fPlayer.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); - case "player_group": - return SavageFactions.plugin.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fPlayer.getId()))); - case "player_balance": - return Econ.isSetup() ? Econ.getFriendlyBalance(fPlayer) : TL.ECON_OFF.format("balance"); - case "player_power": - return String.valueOf(fPlayer.getPowerRounded()); - case "player_maxpower": - return String.valueOf(fPlayer.getPowerMaxRounded()); - case "player_kills": - return String.valueOf(fPlayer.getKills()); - case "player_deaths": - return String.valueOf(fPlayer.getDeaths()); - case "player_role_prefix": - return String.valueOf(fPlayer.getRolePrefix()); - case "player_role": - return fPlayer.hasFaction() ? fPlayer.getRole().getPrefix() : ""; - // Then Faction stuff - case "faction_name": - return fPlayer.hasFaction() ? faction.getTag() : ""; - case "faction_power": - return String.valueOf(faction.getPowerRounded()); - case "faction_powermax": - return String.valueOf(faction.getPowerMaxRounded()); - case "faction_description": - return faction.getDescription(); - case "faction_claims": - return String.valueOf(faction.getAllClaims().size()); - case "faction_founded": - return TL.sdf.format(faction.getFoundedDate()); - case "faction_joining": - return (faction.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); - case "faction_peaceful": - return faction.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; - case "faction_powerboost": - double powerBoost = faction.getPowerBoost(); - return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); - case "faction_leader": - FPlayer fAdmin = faction.getFPlayerAdmin(); - return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); - case "faction_warps": - return String.valueOf(faction.getWarps().size()); - case "faction_raidable": - boolean raid = SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && faction.getLandRounded() >= faction.getPowerRounded(); - return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); - case "faction_home_world": - return faction.hasHome() ? faction.getHome().getWorld().getName() : ""; - case "faction_home_x": - return faction.hasHome() ? String.valueOf(faction.getHome().getBlockX()) : ""; - case "faction_home_y": - return faction.hasHome() ? String.valueOf(faction.getHome().getBlockY()) : ""; - case "faction_home_z": - return faction.hasHome() ? String.valueOf(faction.getHome().getBlockZ()) : ""; - case "facion_land_value": - return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(faction.getLandRounded())) : TL.ECON_OFF.format("value"); - 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.moneyString(Econ.getBalance(faction.getAccountId())) : TL.ECON_OFF.format("balance"); - case "faction_allies": - return String.valueOf(faction.getRelationCount(Relation.ALLY)); - case "faction_enemies": - return String.valueOf(faction.getRelationCount(Relation.ENEMY)); - case "faction_truces": - return String.valueOf(faction.getRelationCount(Relation.TRUCE)); - case "faction_online": - return String.valueOf(faction.getOnlinePlayers().size()); - case "faction_offline": - return String.valueOf(faction.getFPlayers().size() - faction.getOnlinePlayers().size()); - case "faction_size": - return String.valueOf(faction.getFPlayers().size()); - case "faction_kills": - return String.valueOf(faction.getKills()); - case "faction_deaths": - return String.valueOf(faction.getDeaths()); - case "faction_maxvaults": - return String.valueOf(faction.getMaxVaults()); - case "faction_name_at_location": - Faction factionAtLocation = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); - return factionAtLocation != null ? factionAtLocation.getTag() : Factions.getInstance().getWilderness().getTag(); - } + FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); + Faction faction = fPlayer.getFaction(); + switch (placeholder) { + // First list player stuff + case "player_name": + return fPlayer.getName(); + case "player_lastseen": + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - fPlayer.getLastLoginTime(), true, true) + TL.COMMAND_STATUS_AGOSUFFIX; + return fPlayer.isOnline() ? ChatColor.GREEN + TL.COMMAND_STATUS_ONLINE.toString() : (System.currentTimeMillis() - fPlayer.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + case "player_group": + return SavageFactions.plugin.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fPlayer.getId()))); + case "player_balance": + return Econ.isSetup() ? Econ.getFriendlyBalance(fPlayer) : TL.ECON_OFF.format("balance"); + case "player_power": + return String.valueOf(fPlayer.getPowerRounded()); + case "player_maxpower": + return String.valueOf(fPlayer.getPowerMaxRounded()); + case "player_kills": + return String.valueOf(fPlayer.getKills()); + case "player_deaths": + return String.valueOf(fPlayer.getDeaths()); + case "player_role_prefix": + return String.valueOf(fPlayer.getRolePrefix()); + case "player_role": + return fPlayer.hasFaction() ? fPlayer.getRole().getPrefix() : ""; + // Then Faction stuff + case "faction_name": + return fPlayer.hasFaction() ? faction.getTag() : ""; + case "faction_power": + return String.valueOf(faction.getPowerRounded()); + case "faction_powermax": + return String.valueOf(faction.getPowerMaxRounded()); + case "faction_description": + return faction.getDescription(); + case "faction_claims": + return String.valueOf(faction.getAllClaims().size()); + case "faction_founded": + return TL.sdf.format(faction.getFoundedDate()); + case "faction_joining": + return (faction.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); + case "faction_peaceful": + return faction.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; + case "faction_powerboost": + double powerBoost = faction.getPowerBoost(); + return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); + case "faction_leader": + FPlayer fAdmin = faction.getFPlayerAdmin(); + return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); + case "faction_warps": + return String.valueOf(faction.getWarps().size()); + case "faction_raidable": + boolean raid = SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && faction.getLandRounded() >= faction.getPowerRounded(); + return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); + case "faction_home_world": + return faction.hasHome() ? faction.getHome().getWorld().getName() : ""; + case "faction_home_x": + return faction.hasHome() ? String.valueOf(faction.getHome().getBlockX()) : ""; + case "faction_home_y": + return faction.hasHome() ? String.valueOf(faction.getHome().getBlockY()) : ""; + case "faction_home_z": + return faction.hasHome() ? String.valueOf(faction.getHome().getBlockZ()) : ""; + case "facion_land_value": + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(faction.getLandRounded())) : TL.ECON_OFF.format("value"); + 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.moneyString(Econ.getBalance(faction.getAccountId())) : TL.ECON_OFF.format("balance"); + case "faction_allies": + return String.valueOf(faction.getRelationCount(Relation.ALLY)); + case "faction_enemies": + return String.valueOf(faction.getRelationCount(Relation.ENEMY)); + case "faction_truces": + return String.valueOf(faction.getRelationCount(Relation.TRUCE)); + case "faction_online": + return String.valueOf(faction.getOnlinePlayers().size()); + case "faction_offline": + return String.valueOf(faction.getFPlayers().size() - faction.getOnlinePlayers().size()); + case "faction_size": + return String.valueOf(faction.getFPlayers().size()); + case "faction_kills": + return String.valueOf(faction.getKills()); + case "faction_deaths": + return String.valueOf(faction.getDeaths()); + case "faction_maxvaults": + return String.valueOf(faction.getMaxVaults()); + case "faction_name_at_location": + Faction factionAtLocation = Board.getInstance().getFactionAt(new FLocation(player.getLocation())); + return factionAtLocation != null ? factionAtLocation.getTag() : Factions.getInstance().getWilderness().getTag(); + } - return null; - } + return null; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java index f5b2b975..2f0ed3e9 100644 --- a/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/EnumTypeAdapter.java @@ -15,52 +15,52 @@ import java.util.Map; public final class EnumTypeAdapter> extends TypeAdapter { - public static final TypeAdapterFactory ENUM_FACTORY = newEnumTypeHierarchyFactory(); - private final Map nameToConstant = new HashMap<>(); - private final Map constantToName = new HashMap<>(); + public static final TypeAdapterFactory ENUM_FACTORY = newEnumTypeHierarchyFactory(); + private final Map nameToConstant = new HashMap<>(); + private final Map constantToName = new HashMap<>(); - public EnumTypeAdapter(Class classOfT) { - try { - for (T constant : classOfT.getEnumConstants()) { - String name = constant.name(); - SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class); - if (annotation != null) { - name = annotation.value(); - } - nameToConstant.put(name, constant); - constantToName.put(constant, name); - } - } catch (NoSuchFieldException e) { - // ignore since it could be a modified enum - } - } + public EnumTypeAdapter(Class classOfT) { + try { + for (T constant : classOfT.getEnumConstants()) { + String name = constant.name(); + SerializedName annotation = classOfT.getField(name).getAnnotation(SerializedName.class); + if (annotation != null) { + name = annotation.value(); + } + nameToConstant.put(name, constant); + constantToName.put(constant, name); + } + } catch (NoSuchFieldException e) { + // ignore since it could be a modified enum + } + } - public static TypeAdapterFactory newEnumTypeHierarchyFactory() { - return new TypeAdapterFactory() { - @SuppressWarnings({"rawtypes", "unchecked"}) - public TypeAdapter create(Gson gson, TypeToken typeToken) { - Class rawType = typeToken.getRawType(); - if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { - return null; - } - if (!rawType.isEnum()) { - rawType = rawType.getSuperclass(); // handle anonymous subclasses - } - return (TypeAdapter) new EnumTypeAdapter(rawType); - } - }; - } + public static TypeAdapterFactory newEnumTypeHierarchyFactory() { + return new TypeAdapterFactory() { + @SuppressWarnings({"rawtypes", "unchecked"}) + public TypeAdapter create(Gson gson, TypeToken typeToken) { + Class rawType = typeToken.getRawType(); + if (!Enum.class.isAssignableFrom(rawType) || rawType == Enum.class) { + return null; + } + if (!rawType.isEnum()) { + rawType = rawType.getSuperclass(); // handle anonymous subclasses + } + return (TypeAdapter) new EnumTypeAdapter(rawType); + } + }; + } - public T read(JsonReader in) throws IOException { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } - return nameToConstant.get(in.nextString()); - } + public T read(JsonReader in) throws IOException { + if (in.peek() == JsonToken.NULL) { + in.nextNull(); + return null; + } + return nameToConstant.get(in.nextString()); + } - public void write(JsonWriter out, T value) throws IOException { - out.value(value == null ? null : constantToName.get(value)); - } + public void write(JsonWriter out, T value) throws IOException { + out.value(value == null ? null : constantToName.get(value)); + } } diff --git a/src/main/java/com/massivecraft/factions/util/FactionGUI.java b/src/main/java/com/massivecraft/factions/util/FactionGUI.java index d4b181bf..37d02903 100644 --- a/src/main/java/com/massivecraft/factions/util/FactionGUI.java +++ b/src/main/java/com/massivecraft/factions/util/FactionGUI.java @@ -4,8 +4,8 @@ import org.bukkit.event.inventory.ClickType; public interface FactionGUI { - void onClick(int slot, ClickType action); + void onClick(int slot, ClickType action); - void build(); + void build(); } diff --git a/src/main/java/com/massivecraft/factions/util/InventoryTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/InventoryTypeAdapter.java index 0b941b1d..518d2b3c 100644 --- a/src/main/java/com/massivecraft/factions/util/InventoryTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/InventoryTypeAdapter.java @@ -8,20 +8,20 @@ import java.lang.reflect.Type; public class InventoryTypeAdapter implements JsonSerializer, JsonDeserializer { - @Override - public JsonElement serialize(Inventory inventory, Type type, JsonSerializationContext jsonSerializationContext) { + @Override + public JsonElement serialize(Inventory inventory, Type type, JsonSerializationContext jsonSerializationContext) { - JsonObject object = new JsonObject(); - object.add("contents", new JsonPrimitive(InventoryUtil.toBase64(inventory))); - return object; - } + JsonObject object = new JsonObject(); + object.add("contents", new JsonPrimitive(InventoryUtil.toBase64(inventory))); + return object; + } - @Override - public Inventory deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { - JsonObject object = jsonElement.getAsJsonObject(); - return InventoryUtil.fromBase64(object.get("contents").getAsString()); - } + @Override + public Inventory deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { + JsonObject object = jsonElement.getAsJsonObject(); + return InventoryUtil.fromBase64(object.get("contents").getAsString()); + } } diff --git a/src/main/java/com/massivecraft/factions/util/InventoryUtil.java b/src/main/java/com/massivecraft/factions/util/InventoryUtil.java index 98f31df6..a64ad690 100644 --- a/src/main/java/com/massivecraft/factions/util/InventoryUtil.java +++ b/src/main/java/com/massivecraft/factions/util/InventoryUtil.java @@ -14,78 +14,78 @@ import java.io.IOException; public class InventoryUtil { - public static String InventoryToString(ItemStack[] items) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - dataOutput.writeInt(items.length); - for (ItemStack item : items) { - dataOutput.writeObject(item); - } - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } + public static String InventoryToString(ItemStack[] items) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + dataOutput.writeInt(items.length); + for (ItemStack item : items) { + dataOutput.writeObject(item); + } + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } - public static ItemStack[] StringToInventory(String data) throws IOException { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - ItemStack[] items = new ItemStack[dataInput.readInt()]; - for (int i = 0; i < items.length; i++) { - items[i] = (ItemStack) dataInput.readObject(); - } - dataInput.close(); - return items; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } + public static ItemStack[] StringToInventory(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack[] items = new ItemStack[dataInput.readInt()]; + for (int i = 0; i < items.length; i++) { + items[i] = (ItemStack) dataInput.readObject(); + } + dataInput.close(); + return items; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } - public static String toBase64(Inventory inventory) { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + public static String toBase64(Inventory inventory) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - // Write the size of the inventory - dataOutput.writeInt(inventory.getSize()); + // Write the size of the inventory + dataOutput.writeInt(inventory.getSize()); - // Save every element in the list - for (int i = 0; i < inventory.getSize(); i++) { - dataOutput.writeObject(inventory.getItem(i)); - } + // Save every element in the list + for (int i = 0; i < inventory.getSize(); i++) { + dataOutput.writeObject(inventory.getItem(i)); + } - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Cannot into itemstacksz!", e); - } - } + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Cannot into itemstacksz!", e); + } + } - public static String toBase64(ItemStack[] is, int size) { - Inventory inventory = Bukkit.createInventory(null, size); - inventory.setContents(is); - return toBase64(inventory); - } + public static String toBase64(ItemStack[] is, int size) { + Inventory inventory = Bukkit.createInventory(null, size); + inventory.setContents(is); + return toBase64(inventory); + } - public static Inventory fromBase64(String data) { - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); + public static Inventory fromBase64(String data) { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); - // Read the serialized inventory - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, (ItemStack) dataInput.readObject()); - } - dataInput.close(); - return inventory; - } catch (Exception e) { - } - return null; - } + // Read the serialized inventory + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, (ItemStack) dataInput.readObject()); + } + dataInput.close(); + return inventory; + } catch (Exception e) { + } + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/util/LazyLocation.java b/src/main/java/com/massivecraft/factions/util/LazyLocation.java index a141bbc7..1682d8d3 100644 --- a/src/main/java/com/massivecraft/factions/util/LazyLocation.java +++ b/src/main/java/com/massivecraft/factions/util/LazyLocation.java @@ -12,90 +12,90 @@ import java.io.Serializable; */ public class LazyLocation implements Serializable { - private static final long serialVersionUID = -6049901271320963314L; - private transient Location location = null; - private String worldName; - private double x; - private double y; - private double z; - private float pitch; - private float yaw; + private static final long serialVersionUID = -6049901271320963314L; + private transient Location location = null; + private String worldName; + private double x; + private double y; + private double z; + private float pitch; + private float yaw; - public LazyLocation(Location loc) { - setLocation(loc); - } + public LazyLocation(Location loc) { + setLocation(loc); + } - public LazyLocation(final String worldName, final double x, final double y, final double z) { - this(worldName, x, y, z, 0, 0); - } + public LazyLocation(final String worldName, final double x, final double y, final double z) { + this(worldName, x, y, z, 0, 0); + } - public LazyLocation(final String worldName, final double x, final double y, final double z, final float yaw, final float pitch) { - this.worldName = worldName; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - } + public LazyLocation(final String worldName, final double x, final double y, final double z, final float yaw, final float pitch) { + this.worldName = worldName; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } - // This returns the actual Location - public final Location getLocation() { - // make sure Location is initialized before returning it - initLocation(); - return location; - } + // This returns the actual Location + public final Location getLocation() { + // make sure Location is initialized before returning it + initLocation(); + return location; + } - // change the Location - public final void setLocation(Location loc) { - this.location = loc; - this.worldName = loc.getWorld().getName(); - this.x = loc.getX(); - this.y = loc.getY(); - this.z = loc.getZ(); - this.yaw = loc.getYaw(); - this.pitch = loc.getPitch(); - } + // change the Location + public final void setLocation(Location loc) { + this.location = loc; + this.worldName = loc.getWorld().getName(); + this.x = loc.getX(); + this.y = loc.getY(); + this.z = loc.getZ(); + this.yaw = loc.getYaw(); + this.pitch = loc.getPitch(); + } - // This initializes the Location - private void initLocation() { - // if location is already initialized, simply return - if (location != null) { - return; - } + // This initializes the Location + private void initLocation() { + // if location is already initialized, simply return + if (location != null) { + return; + } - // get World; hopefully it's initialized at this point - World world = Bukkit.getWorld(worldName); - if (world == null) { - return; - } + // get World; hopefully it's initialized at this point + World world = Bukkit.getWorld(worldName); + if (world == null) { + return; + } - // store the Location for future calls, and pass it on - location = new Location(world, x, y, z, yaw, pitch); - } + // store the Location for future calls, and pass it on + location = new Location(world, x, y, z, yaw, pitch); + } - public final String getWorldName() { - return worldName; - } + public final String getWorldName() { + return worldName; + } - public final double getX() { - return x; - } + public final double getX() { + return x; + } - public final double getY() { - return y; - } + public final double getY() { + return y; + } - public final double getZ() { - return z; - } + public final double getZ() { + return z; + } - public final double getPitch() { - return pitch; - } + public final double getPitch() { + return pitch; + } - public final double getYaw() { - return yaw; - } + public final double getYaw() { + return yaw; + } } diff --git a/src/main/java/com/massivecraft/factions/util/LocationTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/LocationTypeAdapter.java index 6c5880a7..99905a00 100644 --- a/src/main/java/com/massivecraft/factions/util/LocationTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/LocationTypeAdapter.java @@ -10,41 +10,41 @@ import java.util.logging.Level; public class LocationTypeAdapter implements JsonSerializer, JsonDeserializer { - @Override - public JsonElement serialize(Location location, Type type, JsonSerializationContext jsonSerializationContext) { - JsonObject object = new JsonObject(); - try { - object.add("x", new JsonPrimitive(location.getX())); - object.add("y", new JsonPrimitive(location.getY())); - object.add("z", new JsonPrimitive(location.getZ())); - object.add("world", new JsonPrimitive(location.getWorld().toString())); - return object; - } catch (Exception ex) { - ex.printStackTrace(); - SavageFactions.plugin.log(Level.WARNING, "Error encountered while serializing a Location."); - return object; - } - } + @Override + public JsonElement serialize(Location location, Type type, JsonSerializationContext jsonSerializationContext) { + JsonObject object = new JsonObject(); + try { + object.add("x", new JsonPrimitive(location.getX())); + object.add("y", new JsonPrimitive(location.getY())); + object.add("z", new JsonPrimitive(location.getZ())); + object.add("world", new JsonPrimitive(location.getWorld().toString())); + return object; + } catch (Exception ex) { + ex.printStackTrace(); + SavageFactions.plugin.log(Level.WARNING, "Error encountered while serializing a Location."); + return object; + } + } - @Override - public Location deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { - JsonObject object = jsonElement.getAsJsonObject(); - try { + @Override + public Location deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { + JsonObject object = jsonElement.getAsJsonObject(); + try { - return new Location(Bukkit.getWorld(object.get("world").getAsString()), - object.get("x").getAsDouble(), - object.get("y").getAsDouble(), - object.get("z").getAsDouble()); - } catch (Exception ex) { - ex.printStackTrace(); - SavageFactions.plugin.log(Level.WARNING, "Error encountered while" + - " deserializing a Location."); - return null; - } + return new Location(Bukkit.getWorld(object.get("world").getAsString()), + object.get("x").getAsDouble(), + object.get("y").getAsDouble(), + object.get("z").getAsDouble()); + } catch (Exception ex) { + ex.printStackTrace(); + SavageFactions.plugin.log(Level.WARNING, "Error encountered while" + + " deserializing a Location."); + return null; + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java index e1d6b60b..a95843d3 100644 --- a/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MapFLocToStringSetTypeAdapter.java @@ -16,89 +16,89 @@ import java.util.logging.Level; public class MapFLocToStringSetTypeAdapter implements JsonDeserializer>>, JsonSerializer>> { - @Override - public Map> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - try { - JsonObject obj = json.getAsJsonObject(); - if (obj == null) { - return null; - } + @Override + public Map> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { + return null; + } - Map> locationMap = new ConcurrentHashMap<>(); - Set nameSet; - Iterator iter; - String worldName; - String[] coords; - int x, z; + Map> locationMap = new ConcurrentHashMap<>(); + Set nameSet; + Iterator iter; + String worldName; + String[] coords; + int x, z; - for (Entry entry : obj.entrySet()) { - worldName = entry.getKey(); - for (Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { - coords = entry2.getKey().trim().split("[,\\s]+"); - x = Integer.parseInt(coords[0]); - z = Integer.parseInt(coords[1]); + for (Entry entry : obj.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); - nameSet = new HashSet<>(); - iter = entry2.getValue().getAsJsonArray().iterator(); - while (iter.hasNext()) { - nameSet.add(iter.next().getAsString()); - } + nameSet = new HashSet<>(); + iter = entry2.getValue().getAsJsonArray().iterator(); + while (iter.hasNext()) { + nameSet.add(iter.next().getAsString()); + } - locationMap.put(new FLocation(worldName, x, z), nameSet); - } - } + locationMap.put(new FLocation(worldName, x, z), nameSet); + } + } - return locationMap; + return locationMap; - } catch (Exception ex) { - ex.printStackTrace(); - SavageFactions.plugin.log(Level.WARNING, "Error encountered while deserializing a Map of FLocations to String Sets."); - return null; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + SavageFactions.plugin.log(Level.WARNING, "Error encountered while deserializing a Map of FLocations to String Sets."); + return null; + } + } - @Override - public JsonElement serialize(Map> src, Type typeOfSrc, JsonSerializationContext context) { - JsonObject obj = new JsonObject(); + @Override + public JsonElement serialize(Map> src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); - try { - if (src != null) { - FLocation loc; - String locWorld; - Set nameSet; - Iterator iter; - JsonArray nameArray; - JsonPrimitive nameElement; + try { + if (src != null) { + FLocation loc; + String locWorld; + Set nameSet; + Iterator iter; + JsonArray nameArray; + JsonPrimitive nameElement; - for (Entry> entry : src.entrySet()) { - loc = entry.getKey(); - locWorld = loc.getWorldName(); - nameSet = entry.getValue(); + for (Entry> entry : src.entrySet()) { + loc = entry.getKey(); + locWorld = loc.getWorldName(); + nameSet = entry.getValue(); - if (nameSet == null || nameSet.isEmpty()) { - continue; - } + if (nameSet == null || nameSet.isEmpty()) { + continue; + } - nameArray = new JsonArray(); - iter = nameSet.iterator(); - while (iter.hasNext()) { - nameElement = new JsonPrimitive(iter.next()); - nameArray.add(nameElement); - } + nameArray = new JsonArray(); + iter = nameSet.iterator(); + while (iter.hasNext()) { + nameElement = new JsonPrimitive(iter.next()); + nameArray.add(nameElement); + } - if (!obj.has(locWorld)) { - obj.add(locWorld, new JsonObject()); - } + if (!obj.has(locWorld)) { + obj.add(locWorld, new JsonObject()); + } - obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); - } - } - return obj; + obj.get(locWorld).getAsJsonObject().add(loc.getCoordString(), nameArray); + } + } + return obj; - } catch (Exception ex) { - ex.printStackTrace(); - SavageFactions.plugin.log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets."); - return obj; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + SavageFactions.plugin.log(Level.WARNING, "Error encountered while serializing a Map of FLocations to String Sets."); + return obj; + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/MiscUtil.java b/src/main/java/com/massivecraft/factions/util/MiscUtil.java index 07ff1b49..76536007 100644 --- a/src/main/java/com/massivecraft/factions/util/MiscUtil.java +++ b/src/main/java/com/massivecraft/factions/util/MiscUtil.java @@ -18,113 +18,113 @@ import java.util.logging.Level; public class MiscUtil { - /// TODO create tag whitelist!! - public static HashSet substanceChars = - new HashSet<>(Arrays.asList("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""))); + /// TODO create tag whitelist!! + public static HashSet substanceChars = + new HashSet<>(Arrays.asList("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""))); - public static EntityType creatureTypeFromEntity(Entity entity) { - if (!(entity instanceof Creature)) { - return null; - } + public static EntityType creatureTypeFromEntity(Entity entity) { + if (!(entity instanceof Creature)) { + return null; + } - String name = entity.getClass().getSimpleName(); - name = name.substring(5); // Remove "Craft" + String name = entity.getClass().getSimpleName(); + name = name.substring(5); // Remove "Craft" - return EntityType.fromName(name); - } + return EntityType.fromName(name); + } - // Inclusive range - public static long[] range(long start, long end) { - long[] values = new long[(int) Math.abs(end - start) + 1]; + // Inclusive range + public static long[] range(long start, long end) { + long[] values = new long[(int) Math.abs(end - start) + 1]; - if (end < start) { - long oldstart = start; - start = end; - end = oldstart; - } + if (end < start) { + long oldstart = start; + start = end; + end = oldstart; + } - for (long i = start; i <= end; i++) { - values[(int) (i - start)] = i; - } + for (long i = start; i <= end; i++) { + values[(int) (i - start)] = i; + } - return values; - } + return values; + } - public static String getComparisonString(String str) { - StringBuilder ret = new StringBuilder(); + public static String getComparisonString(String str) { + StringBuilder ret = new StringBuilder(); - str = ChatColor.stripColor(str); - str = str.toLowerCase(); + str = ChatColor.stripColor(str); + str = str.toLowerCase(); - for (char c : str.toCharArray()) { - if (substanceChars.contains(String.valueOf(c))) { - ret.append(c); - } - } - return ret.toString().toLowerCase(); - } + for (char c : str.toCharArray()) { + if (substanceChars.contains(String.valueOf(c))) { + ret.append(c); + } + } + return ret.toString().toLowerCase(); + } - public static ArrayList validateTag(String str) { - ArrayList errors = new ArrayList<>(); + public static ArrayList validateTag(String str) { + ArrayList errors = new ArrayList<>(); - if (getComparisonString(str).length() < Conf.factionTagLengthMin) { - errors.add(SavageFactions.plugin.txt.parse(TL.GENERIC_FACTIONTAG_TOOSHORT.toString(), Conf.factionTagLengthMin)); - } + if (getComparisonString(str).length() < Conf.factionTagLengthMin) { + errors.add(SavageFactions.plugin.txt.parse(TL.GENERIC_FACTIONTAG_TOOSHORT.toString(), Conf.factionTagLengthMin)); + } - if (str.length() > Conf.factionTagLengthMax) { - errors.add(SavageFactions.plugin.txt.parse(TL.GENERIC_FACTIONTAG_TOOLONG.toString(), Conf.factionTagLengthMax)); - } + if (str.length() > Conf.factionTagLengthMax) { + errors.add(SavageFactions.plugin.txt.parse(TL.GENERIC_FACTIONTAG_TOOLONG.toString(), Conf.factionTagLengthMax)); + } - for (char c : str.toCharArray()) { - if (!substanceChars.contains(String.valueOf(c))) { - errors.add(SavageFactions.plugin.txt.parse(TL.GENERIC_FACTIONTAG_ALPHANUMERIC.toString(), c)); - } - } + for (char c : str.toCharArray()) { + if (!substanceChars.contains(String.valueOf(c))) { + errors.add(SavageFactions.plugin.txt.parse(TL.GENERIC_FACTIONTAG_ALPHANUMERIC.toString(), c)); + } + } - return errors; - } + return errors; + } - public static Iterable rankOrder(Iterable players) { - List admins = new ArrayList<>(); - List coleaders = new ArrayList<>(); - List moderators = new ArrayList<>(); - List normal = new ArrayList<>(); - List recruit = new ArrayList<>(); + public static Iterable rankOrder(Iterable players) { + List admins = new ArrayList<>(); + List coleaders = new ArrayList<>(); + List moderators = new ArrayList<>(); + List normal = new ArrayList<>(); + List recruit = new ArrayList<>(); - for (FPlayer player : players) { + for (FPlayer player : players) { - // Fix for some data being broken when we added the recruit rank. - if (player.getRole() == null) { - player.setRole(Role.NORMAL); - SavageFactions.plugin.log(Level.WARNING, String.format("Player %s had null role. Setting them to normal. This isn't good D:", player.getName())); - } + // Fix for some data being broken when we added the recruit rank. + if (player.getRole() == null) { + player.setRole(Role.NORMAL); + SavageFactions.plugin.log(Level.WARNING, String.format("Player %s had null role. Setting them to normal. This isn't good D:", player.getName())); + } - switch (player.getRole()) { - case LEADER: - admins.add(player); - break; - case COLEADER: - admins.add(player); - break; - case MODERATOR: - moderators.add(player); - break; - case NORMAL: - normal.add(player); - break; - case RECRUIT: - recruit.add(player); - break; - } - } + switch (player.getRole()) { + case LEADER: + admins.add(player); + break; + case COLEADER: + admins.add(player); + break; + case MODERATOR: + moderators.add(player); + break; + case NORMAL: + normal.add(player); + break; + case RECRUIT: + recruit.add(player); + break; + } + } - List ret = new ArrayList<>(); - ret.addAll(admins); - ret.addAll(coleaders); - ret.addAll(moderators); - ret.addAll(normal); - ret.addAll(recruit); - return ret; - } + List ret = new ArrayList<>(); + ret.addAll(admins); + ret.addAll(coleaders); + ret.addAll(moderators); + ret.addAll(normal); + ret.addAll(recruit); + return ret; + } } diff --git a/src/main/java/com/massivecraft/factions/util/MultiversionMaterials.java b/src/main/java/com/massivecraft/factions/util/MultiversionMaterials.java index df243e72..6ded7b7d 100644 --- a/src/main/java/com/massivecraft/factions/util/MultiversionMaterials.java +++ b/src/main/java/com/massivecraft/factions/util/MultiversionMaterials.java @@ -7,968 +7,968 @@ import java.util.HashMap; public enum MultiversionMaterials { - ACACIA_BOAT("BOAT_ACACIA", 0), - ACACIA_BUTTON("WOOD_BUTTON", 0), - ACACIA_DOOR("ACACIA_DOOR", 0), - ACACIA_FENCE("ACACIA_FENCE", 0), - ACACIA_FENCE_GATE("ACACIA_FENCE_GATE", 0), - ACACIA_LEAVES("LEAVES_2", 0), - ACACIA_LOG("LOG_2", 0), - ACACIA_PLANKS("WOOD", 4), - ACACIA_PRESSURE_PLATE("WOOD_PLATE", 0), - ACACIA_SAPLING("SAPLING", 4), - ACACIA_SLAB("WOOD_STEP", 4), - ACACIA_STAIRS("ACACIA_STAIRS", 4), - ACACIA_TRAPDOOR("TRAP_DOOR", 0), - ACACIA_WOOD("LOG_2", 0), - ACTIVATOR_RAIL("ACTIVATOR_RAIL", 0), - AIR("AIR", 0), - ALLIUM("STONE", 0), - ANDESITE("STONE", 5), - ANVIL("ANVIL", 0), - APPLE("APPLE", 0), - ARMOR_STAND("ARMOR_STAND", 0), - ARROW("ARROW", 0), - ATTACHED_MELON_STEM("MELON_STEM", 7), - ATTACHED_PUMPKIN_STEM("PUMPKIN_STEM", 7), - AZURE_BLUET("RED_ROSE", 3), - BAKED_POTATO("BAKED_POTATO", 0), - BARRIER("BARRIER", 0), - BAT_SPAWN_EGG("MONSTER_EGG", 0), - BEACON("BEACON", 0), - BEDROCK("BEDROCK", 0), - BEEF("RAW_BEEF", 0), - BEETROOT("BEETROOT", 0), - BEETROOTS("BEETROOT", 0), - BEETROOT_SEEDS("BEETROOT_SEEDS", 0), - BEETROOT_SOUP("BEETROOT_SOUP", 0), - BIRCH_BOAT("BOAT_BIRCH", 0), - BIRCH_BUTTON("WOOD_BUTTON", 0), - BIRCH_DOOR("BIRCH_DOOR", 0), - BIRCH_FENCE("BIRCH_FENCE", 0), - BIRCH_FENCE_GATE("BIRCH_FENCE_GATE", 0), - BIRCH_LEAVES("LEAVES", 2), - BIRCH_LOG("LOG", 2), - BIRCH_PLANKS("WOOD", 2), - BIRCH_PRESSURE_PLATE("WOOD_PLATE", 0), - BIRCH_SAPLING("SAPLING", 2), - BIRCH_SLAB("WOOD_STEP", 2), - BIRCH_STAIRS("BIRCH_WOOD_STAIRS", 0), - BIRCH_TRAPDOOR("TRAP_DOOR", 0), - BIRCH_WOOD("LOG", 2), - BLACK_BANNER("BANNER", 0), - BLACK_BED("BED", 15), - BLACK_CARPET("CARPET", 15), - BLACK_CONCRETE("CONCRETE", 15), - BLACK_CONCRETE_POWDER("CONCRETE_POWDER", 15), - BLACK_GLAZED_TERRACOTTA("BLACK_GLAZED_TERRACOTTA", 0), - BLACK_SHULKER_BOX("BLACK_SHULKER_BOX", 0), - BLACK_STAINED_GLASS("STAINED_GLASS", 15), - BLACK_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 15), - BLACK_TERRACOTTA("STAINED_CLAY", 15), - BLACK_WALL_BANNER("WALL_BANNER", 0), - BLACK_WOOL("WOOL", 15), - BLAZE_POWDER("BLAZE_POWDER", 0), - BLAZE_ROD("BLAZE_ROD", 0), - BLAZE_SPAWN_EGG("MONSTER_EGG", 0), - BLUE_BANNER("BANNER", 11), - BLUE_BED("BED", 4), - BLUE_CARPET("CARPET", 11), - BLUE_CONCRETE("CONCRETE", 11), - BLUE_CONCRETE_POWDER("CONCRETE_POWDER", 11), - BLUE_GLAZED_TERRACOTTA("BLUE_GLAZED_TERRACOTTA", 0), - BLUE_ICE("PACKED_ICE", 0), - BLUE_ORCHID("RED_ROSE", 1), - BLUE_SHULKER_BOX("BLUE_SHULKER_BOX", 0), - BLUE_STAINED_GLASS("STAINED_GLASS", 11), - BLUE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 11), - BLUE_TERRACOTTA("STAINED_CLAY", 11), - BLUE_WALL_BANNER("WALL_BANNER", 11), - BLUE_WOOL("WOOL", 11), - BONE("BONE", 0), - BONE_BLOCK("BONE_BLOCK", 0), - BONE_MEAL("INK_SACK", 15), - BOOK("BOOK", 0), - BOOKSHELF("BOOKSHELF", 0), - BOW("BOW", 0), - BOWL("BOWL", 0), - BRAIN_CORAL("STONE", 0), - BRAIN_CORAL_BLOCK("STONE", 0), - BRAIN_CORAL_FAN("STONE", 0), - BREAD("BREAD", 0), - BREWING_STAND("BREWING_STAND", 0), - BRICK("CLAY_BRICK", 0), - BRICKS("BRICK", 0), - BRICK_SLAB("STEP", 4), - BRICK_STAIRS("BRICK_STAIRS", 0), - BROWN_BANNER("BANNER", 3), - BROWN_BED("BED", 12), - BROWN_CARPET("CARPET", 12), - BROWN_CONCRETE("CONCRETE", 12), - BROWN_CONCRETE_POWDER("CONCRETE_POWDER", 12), - BROWN_GLAZED_TERRACOTTA("BROWN_GLAZED_TERRACOTTA", 0), - BROWN_MUSHROOM("BROWN_MUSHROOM", 0), - BROWN_MUSHROOM_BLOCK("BROWN_MUSHROOM", 0), //UNSURE - BROWN_SHULKER_BOX("BROWN_SHULKER_BOX", 0), - BROWN_STAINED_GLASS("STAINED_GLASS", 12), - BROWN_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 12), - BROWN_TERRACOTTA("STAINED_CLAY", 12), - BROWN_WALL_BANNER("WALL_BANNER", 3), - BROWN_WOOL("WOOL", 12), - BUBBLE_COLUMN("STONE", 0), - BUBBLE_CORAL("STONE", 0), - BUBBLE_CORAL_BLOCK("STONE", 0), - BUBBLE_CORAL_FAN("STONE", 0), - BUCKET("BUCKET", 0), - CACTUS("CACTUS", 0), - CACTUS_GREEN("INK_SACK", 2), - CAKE("CAKE", 0), - CARROT("CARROT_ITEM", 0), - CARROTS("CARROT", 0), - CARROT_ON_A_STICK("CARROT_STICK", 0), - CARVED_PUMPKIN("PUMPKIN", 0), - CAULDRON("CAULDRON", 0), - CAVE_AIR("AIR", 0), - CAVE_SPIDER_SPAWN_EGG("MONSTER_EGG", 0), - CHAINMAIL_BOOTS("CHAINMAIL_BOOTS", 0), - CHAINMAIL_CHESTPLATE("CHAINMAIL_CHESTPLATE", 0), - CHAINMAIL_HELMET("CHAINMAIL_HELMET", 0), - CHAINMAIL_LEGGINGS("CHAINMAIL_LEGGINGS", 0), - CHAIN_COMMAND_BLOCK("COMMAND_CHAIN", 0), - CHARCOAL("COAL", 1), - CHEST("CHEST", 0), - CHEST_MINECART("STORAGE_MINECART", 0), - CHICKEN("RAW_CHICKEN", 0), - CHICKEN_SPAWN_EGG("MONSTER_EGG", 0), - CHIPPED_ANVIL("ANVIL", 1), - CHISELED_QUARTZ_BLOCK("QUARTZ_BLOCK", 1), - CHISELED_RED_SANDSTONE("RED_SANDSTONE", 1), - CHISELED_SANDSTONE("SANDSTONE", 1), - CHISELED_STONE_BRICKS("SMOOTH_BRICK", 3), - CHORUS_FLOWER("CHORUS_FLOWER", 0), - CHORUS_FRUIT("CHORUS_FRUIT", 0), - CHORUS_PLANT("CHORUS_PLANT", 0), - CLAY("CLAY", 0), - CLAY_BALL("CLAY_BALL", 0), - CLOCK("WATCH", 0), - COAL("COAL", 0), - COAL_BLOCK("COAL_BLOCK", 0), - COAL_ORE("COAL_ORE", 0), - COARSE_DIRT("DIRT", 1), - COBBLESTONE("COBBLESTONE", 0), - COBBLESTONE_SLAB("STEP", 3), - COBBLESTONE_STAIRS("COBBLESTONE_STAIRS", 0), - COBBLESTONE_WALL("COBBLE_WALL", 0), - COBWEB("WEB", 0), - COCOA("COCOA", 0), - COCOA_BEANS("INK_SACK", 3), - COD("RAW_FISH", 0), - COD_BUCKET("BUCKET", 0), - COD_SPAWN_EGG("MONSTER_EGG", 0), - COMMAND_BLOCK("COMMAND", 0), - COMMAND_BLOCK_MINECART("COMMAND_MINECART", 0), - COMPARATOR("REDSTONE_COMPARATOR", 0), - COMPASS("COMPASS", 0), - CONDUIT("STONE", 0), - COOKED_BEEF("COOKED_BEEF", 0), - COOKED_CHICKEN("COOKED_CHICKEN", 0), - COOKED_COD("COOKED_FISH", 0), - COOKED_MUTTON("COOKED_MUTTON", 0), - COOKED_PORKCHOP("GRILLED_PORK", 0), - COOKED_RABBIT("COOKED_RABBIT", 0), - COOKED_SALMON("COOKED_FISH", 1), - COOKIE("COOKIE", 0), - COW_SPAWN_EGG("MONSTER_EGG", 0), - CRACKED_STONE_BRICKS("SMOOTH_BRICK", 2), - CRAFTING_TABLE("WORKBENCH", 0), - CREEPER_HEAD("SKULL", 0), - CREEPER_SPAWN_EGG("MONSTER_EGG", 0), - CREEPER_WALL_HEAD("SKULL", 0), - CUT_RED_SANDSTONE("STONE", 0), - CUT_SANDSTONE("STONE", 0), - CYAN_BANNER("BANNER", 6), - CYAN_BED("BED", 9), - CYAN_CARPET("CARPET", 9), - CYAN_CONCRETE("CONCRETE", 9), - CYAN_CONCRETE_POWDER("CONCRETE_POWDER", 9), - CYAN_DYE("INK_SACK", 6), - CYAN_GLAZED_TERRACOTTA("CYAN_GLAZED_TERRACOTTA", 0), - CYAN_SHULKER_BOX("CYAN_SHULKER_BOX", 0), - CYAN_STAINED_GLASS("STAINED_GLASS", 9), - CYAN_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 9), - CYAN_TERRACOTTA("STAINED_CLAY", 9), - CYAN_WALL_BANNER("WALL_BANNER", 0), - CYAN_WOOL("WOOL", 9), - DAMAGED_ANVIL("ANVIL", 2), - DANDELION("YELLOW_FLOWER", 0), - DANDELION_YELLOW("INK_SACK", 11), - DARK_OAK_BOAT("BOAT_DARK_OAK", 0), - DARK_OAK_BUTTON("WOOD_BUTTON", 0), - DARK_OAK_DOOR("DARK_OAK_DOOR", 0), - DARK_OAK_FENCE("DARK_OAK_FENCE", 0), - DARK_OAK_FENCE_GATE("DARK_OAK_FENCE_GATE", 0), - DARK_OAK_LEAVES("LEAVES_2", 1), - DARK_OAK_LOG("LOG_2", 1), - DARK_OAK_PLANKS("WOOD", 5), - DARK_OAK_PRESSURE_PLATE("WOOD_PLATE", 0), - DARK_OAK_SAPLING("SAPLING", 5), - DARK_OAK_SLAB("WOOD_STEP", 0), - DARK_OAK_STAIRS("DARK_OAK_STAIRS", 0), - DARK_OAK_TRAPDOOR("TRAP_DOOR", 0), - DARK_OAK_WOOD("LOG_2", 1), - DARK_PRISMARINE("PRISMARINE", 2), - DARK_PRISMARINE_SLAB("STONE", 0), - DARK_PRISMARINE_STAIRS("STONE", 0), - DAYLIGHT_DETECTOR("DAYLIGHT_DETECTOR", 0), - DEAD_BRAIN_CORAL_BLOCK("STONE", 0), - DEAD_BUBBLE_CORAL_BLOCK("STONE", 0), - DEAD_BUSH("DEAD_BUSH", 0), - DEAD_FIRE_CORAL_BLOCK("STONE", 0), - DEAD_HORN_CORAL_BLOCK("STONE", 0), - DEAD_TUBE_CORAL_BLOCK("STONE", 0), - DEBUG_STICK("STICK", 0), - DETECTOR_RAIL("DETECTOR_RAIL", 0), - DIAMOND("DIAMOND", 0), - DIAMOND_AXE("DIAMOND_AXE", 0), - DIAMOND_BLOCK("DIAMOND_BLOCK", 0), - DIAMOND_BOOTS("DIAMOND_BOOTS", 0), - DIAMOND_CHESTPLATE("DIAMOND_CHESTPLATE", 0), - DIAMOND_HELMET("DIAMOND_HELMET", 0), - DIAMOND_HOE("DIAMOND_HOE", 0), - DIAMOND_HORSE_ARMOR("DIAMOND_BARDING", 0), - DIAMOND_LEGGINGS("DIAMOND_LEGGINGS", 0), - DIAMOND_ORE("DIAMOND_ORE", 0), - DIAMOND_PICKAXE("DIAMOND_PICKAXE", 0), - DIAMOND_SHOVEL("DIAMOND_SPADE", 0), - DIAMOND_SWORD("DIAMOND_SWORD", 0), - DIORITE("STONE", 3), - DIRT("DIRT", 0), - DISPENSER("DISPENSER", 0), - DOLPHIN_SPAWN_EGG("MONSTER_EGG", 0), - DONKEY_SPAWN_EGG("MONSTER_EGG", 0), - DRAGON_BREATH("DRAGONS_BREATH", 0), - DRAGON_EGG("DRAGON_EGG", 0), - DRAGON_HEAD("SKULL", 5), - DRAGON_WALL_HEAD("SKULL", 0), - DRIED_KELP("STONE", 0), - DRIED_KELP_BLOCK("STONE", 0), - DROPPER("DROPPER", 0), - DROWNED_SPAWN_EGG("MONSTER_EGG", 0), - EGG("EGG", 0), - ELDER_GUARDIAN_SPAWN_EGG("MONSTER_EGG", 0), - ELYTRA("ELYTRA", 0), - EMERALD("EMERALD", 0), - EMERALD_BLOCK("EMERALD_BLOCK", 0), - EMERALD_ORE("EMERALD_ORE", 0), - ENCHANTED_BOOK("ENCHANTED_BOOK", 0), - ENCHANTED_GOLDEN_APPLE("GOLDEN_APPLE", 1), - ENCHANTING_TABLE("ENCHANTING_TABLE", 0), - ENDERMAN_SPAWN_EGG("MONSTER_EGG", 0), - ENDERMITE_SPAWN_EGG("MONSTER_EGG", 0), - ENDER_CHEST("ENDER_CHEST", 0), - ENDER_EYE("EYE_OF_ENDER", 0), - ENDER_PEARL("ENDER_PEARL", 0), - END_CRYSTAL("END_CRYSTAL", 0), - END_GATEWAY("END_GATEWAY", 0), - END_PORTAL("ENDER_PORTAL", 0), - END_PORTAL_FRAME("ENDER_PORTAL_FRAME", 0), - END_ROD("END_ROD", 0), - END_STONE("ENDER_STONE", 0), - END_STONE_BRICKS("END_BRICKS", 0), - EVOKER_SPAWN_EGG("MONSTER_EGG", 0), - EXPERIENCE_BOTTLE("EXP_BOTTLE", 0), - FARMLAND("SOIL", 0), - FEATHER("FEATHER", 0), - FERMENTED_SPIDER_EYE("FERMENTED_SPIDER_EYE", 0), - FERN("LONG_GRASS", 2), - FILLED_MAP("MAP", 0), - FIRE("FIRE", 0), - FIREWORK_ROCKET("FIREWORK", 0), - FIREWORK_STAR("FIREWORK_CHARGE", 0), - FIRE_CHARGE("FIREBALL", 0), - FIRE_CORAL("STONE", 0), - FIRE_CORAL_BLOCK("STONE", 0), - FIRE_CORAL_FAN("STONE", 0), - FISHING_ROD("FISHING_ROD", 0), - FLINT("FLINT", 0), - FLINT_AND_STEEL("FLINT_AND_STEEL", 0), - FLOWER_POT("FLOWER_POT", 0), - FROSTED_ICE("FROSTED_ICE", 0), - FURNACE("FURNACE", 0), - FURNACE_MINECART("POWERED_MINECART", 0), - GHAST_SPAWN_EGG("MONSTER_EGG", 0), - GHAST_TEAR("GHAST_TEAR", 0), - GLASS("GLASS", 0), - GLASS_BOTTLE("GLASS_BOTTLE", 0), - GLASS_PANE("THIN_GLASS", 0), - GLISTERING_MELON_SLICE("SPECKLED_MELON", 0), - GLOWSTONE("GLOWSTONE", 0), - GLOWSTONE_DUST("GLOWSTONE_DUST", 0), - GOLDEN_APPLE("GOLDEN_APPLE", 0), - GOLDEN_AXE("GOLD_AXE", 0), - GOLDEN_BOOTS("GOLD_BOOTS", 0), - GOLDEN_CARROT("GOLDEN_CARROT", 0), - GOLDEN_CHESTPLATE("GOLD_CHESTPLATE", 0), - GOLDEN_HELMET("GOLD_HELMET", 0), - GOLDEN_HOE("GOLD_HOE", 0), - GOLDEN_HORSE_ARMOR("GOLD_BARDING", 0), - GOLDEN_LEGGINGS("GOLD_LEGGINGS", 0), - GOLDEN_PICKAXE("GOLD_PICKAXE", 0), - GOLDEN_SHOVEL("GOLD_SPADE", 0), - GOLDEN_SWORD("GOLD_SWORD", 0), - GOLD_BLOCK("GOLD_BLOCK", 0), - GOLD_INGOT("GOLD_INGOT", 0), - GOLD_NUGGET("GOLD_NUGGET", 0), - GOLD_ORE("GOLD_ORE", 0), - GRANITE("STONE", 1), - GRASS("GRASS", 0), - GRASS_BLOCK("GRASS", 0), - GRASS_PATH("GRASS_PATH", 0), - GRAVEL("GRAVEL", 0), - GRAY_BANNER("BANNER", 8), - GRAY_BED("BED", 7), - GRAY_CARPET("CARPET", 7), - GRAY_CONCRETE("CONCRETE", 7), - GRAY_CONCRETE_POWDER("CONCRETE_POWDER", 7), - GRAY_DYE("INK_SACK", 8), - GRAY_GLAZED_TERRACOTTA("GRAY_GLAZED_TERRACOTTA", 0), - GRAY_SHULKER_BOX("GRAY_SHULKER_BOX", 0), - GRAY_STAINED_GLASS("STAINED_GLASS", 7), - GRAY_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 7), - GRAY_TERRACOTTA("STAINED_CLAY", 7), - GRAY_WALL_BANNER("WALL_BANNER", 0), - GRAY_WOOL("WOOL", 7), - GREEN_BANNER("BANNER", 2), - GREEN_BED("BED", 13), - GREEN_CARPET("CARPET", 13), - GREEN_CONCRETE("CONCRETE", 13), - GREEN_CONCRETE_POWDER("CONCRETE_POWDER", 13), - GREEN_GLAZED_TERRACOTTA("GREEN_GLAZED_TERRACOTTA", 0), - GREEN_SHULKER_BOX("GREEN_SHULKER_BOX", 0), - GREEN_STAINED_GLASS("STAINED_GLASS", 13), - GREEN_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 13), - GREEN_TERRACOTTA("STAINED_CLAY", 13), - GREEN_WALL_BANNER("WALL_BANNER", 0), - GREEN_WOOL("WOOL", 13), - GUARDIAN_SPAWN_EGG("MONSTER_EGG", 0), - GUNPOWDER("SULPHUR", 0), - HAY_BLOCK("HAY_BLOCK", 0), - HEART_OF_THE_SEA("STONE", 0), - HEAVY_WEIGHTED_PRESSURE_PLATE("IRON_PLATE", 0), - HOPPER("HOPPER", 0), - HOPPER_MINECART("HOPPER_MINECART", 0), - HORN_CORAL("STONE", 0), - HORN_CORAL_BLOCK("STONE", 0), - HORN_CORAL_FAN("STONE", 0), - HORSE_SPAWN_EGG("MONSTER_EGG", 0), - HUSK_SPAWN_EGG("MONSTER_EGG", 0), - ICE("ICE", 0), - INFESTED_CHISELED_STONE_BRICKS("MONSTER_EGGS", 5), - INFESTED_COBBLESTONE("MONSTER_EGGS", 1), - INFESTED_CRACKED_STONE_BRICKS("MONSTER_EGGS", 4), - INFESTED_MOSSY_STONE_BRICKS("MONSTER_EGGS", 3), - INFESTED_STONE("MONSTER_EGGS", 0), - INFESTED_STONE_BRICKS("MONSTER_EGGS", 2), - INK_SAC("INK_SACK", 0), - IRON_AXE("IRON_AXE", 0), - IRON_BARS("IRON_FENCE", 0), - IRON_BLOCK("IRON_BLOCK", 0), - IRON_BOOTS("IRON_BOOTS", 0), - IRON_CHESTPLATE("IRON_CHESTPLATE", 0), - IRON_DOOR("IRON_DOOR", 0), - IRON_HELMET("IRON_HELMET", 0), - IRON_HOE("IRON_HOE", 0), - IRON_HORSE_ARMOR("IRON_BARDING", 0), - IRON_INGOT("IRON_INGOT", 0), - IRON_LEGGINGS("IRON_LEGGINGS", 0), - IRON_NUGGET("IRON_NUGGET", 0), - IRON_ORE("IRON_ORE", 0), - IRON_PICKAXE("IRON_PICKAXE", 0), - IRON_SHOVEL("IRON_SPADE", 0), - IRON_SWORD("IRON_SWORD", 0), - IRON_TRAPDOOR("IRON_TRAPDOOR", 0), - ITEM_FRAME("ITEM_FRAME", 0), - JACK_O_LANTERN("JACK_O_LANTERN", 0), - JUKEBOX("JUKEBOX", 0), - JUNGLE_BOAT("BOAT_JUNGLE", 0), - JUNGLE_BUTTON("WOOD_BUTTON", 0), - JUNGLE_DOOR("JUNGLE_DOOR", 0), - JUNGLE_FENCE("JUNGLE_FENCE", 0), - JUNGLE_FENCE_GATE("JUNGLE_FENCE_GATE", 0), - JUNGLE_LEAVES("LEAVES", 3), - JUNGLE_LOG("LOG", 3), - JUNGLE_PLANKS("WOOD", 3), - JUNGLE_PRESSURE_PLATE("WOOD_PLATE", 0), - JUNGLE_SAPLING("SAPLING", 3), - JUNGLE_SLAB("WOOD_STEP", 3), - JUNGLE_STAIRS("JUNGLE_WOOD_STAIRS", 0), - JUNGLE_TRAPDOOR("TRAP_DOOR", 0), - JUNGLE_WOOD("LOG", 3), - KELP("STONE", 0), - KELP_PLANT("STONE", 0), - KNOWLEDGE_BOOK("KNOWLEDGE_BOOK", 0), - LADDER("LADDER", 0), - LAPIS_BLOCK("LAPIS_BLOCK", 0), - LAPIS_LAZULI("INK_SACK", 4), - LAPIS_ORE("LAPIS_ORE", 0), - LARGE_FERN("DOUBLE_PLANT", 3), - LAVA("LAVA", 0), - LAVA_BUCKET("LAVA_BUCKET", 0), - LEAD("LEASH", 0), - LEATHER("LEATHER", 0), - LEATHER_BOOTS("LEATHER_BOOTS", 0), - LEATHER_CHESTPLATE("LEATHER_CHESTPLATE", 0), - LEATHER_HELMET("LEATHER_HELMET", 0), - LEATHER_LEGGINGS("LEATHER_LEGGINGS", 0), - LEVER("LEVER", 0), - LIGHT_BLUE_BANNER("BANNER", 12), - LIGHT_BLUE_BED("BED", 3), - LIGHT_BLUE_CARPET("CARPET", 3), - LIGHT_BLUE_CONCRETE("CONCRETE", 3), - LIGHT_BLUE_CONCRETE_POWDER("CONCRETE_POWDER", 3), - LIGHT_BLUE_DYE("INK_SACK", 12), - LIGHT_BLUE_GLAZED_TERRACOTTA("LIGHT_BLUE_GLAZED_TERRACOTTA", 0), - LIGHT_BLUE_SHULKER_BOX("LIGHT_BLUE_SHULKER_BOX", 0), - LIGHT_BLUE_STAINED_GLASS("STAINED_GLASS", 3), - LIGHT_BLUE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 3), - LIGHT_BLUE_TERRACOTTA("STAINED_CLAY", 3), - LIGHT_BLUE_WALL_BANNER("BANNER", 0), - LIGHT_BLUE_WOOL("WOOL", 3), - LIGHT_GRAY_BANNER("BANNER", 7), - LIGHT_GRAY_BED("BED", 8), - LIGHT_GRAY_CARPET("CARPET", 8), - LIGHT_GRAY_CONCRETE("CONCRETE", 8), - LIGHT_GRAY_CONCRETE_POWDER("CONCRETE_POWDER", 8), - LIGHT_GRAY_DYE("INK_SACK", 7), - LIGHT_GRAY_GLAZED_TERRACOTTA("SILVER_GLAZED_TERRACOTTA", 0), - LIGHT_GRAY_SHULKER_BOX("SILVER_SHULKER_BOX", 0), - LIGHT_GRAY_STAINED_GLASS("STAINED_GLASS", 8), - LIGHT_GRAY_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 8), - LIGHT_GRAY_TERRACOTTA("STAINED_CLAY", 8), - LIGHT_GRAY_WALL_BANNER("WALL_BANNER", 0), - LIGHT_GRAY_WOOL("WOOL", 8), - LIGHT_WEIGHTED_PRESSURE_PLATE("GOLD_PLATE", 0), - LILAC("DOUBLE_PLANT", 1), - LILY_PAD("WATER_LILY", 0), - LIME_BANNER("BANNER", 10), - LIME_BED("BED", 5), - LIME_CARPET("CARPET", 5), - LIME_CONCRETE("CONCRETE", 5), - LIME_CONCRETE_POWDER("CONCRETE_POWDER", 5), - LIME_DYE("INK_SACK", 10), - LIME_GLAZED_TERRACOTTA("LIME_GLAZED_TERRACOTTA", 0), - LIME_SHULKER_BOX("LIME_SHULKER_BOX", 0), - LIME_STAINED_GLASS("STAINED_GLASS", 5), - LIME_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 5), - LIME_TERRACOTTA("STAINED_CLAY", 5), - LIME_WALL_BANNER("WALL_BANNER", 0), - LIME_WOOL("WOOL", 5), - LINGERING_POTION("LINGERING_POTION", 0), - LLAMA_SPAWN_EGG("MONSTER_EGG", 0), - MAGENTA_BANNER("BANNER", 13), - MAGENTA_BED("BED", 2), - MAGENTA_CARPET("CARPET", 2), - MAGENTA_CONCRETE("CONCRETE", 2), - MAGENTA_CONCRETE_POWDER("CONCRETE_POWDER", 2), - MAGENTA_DYE("INK_SACK", 13), - MAGENTA_GLAZED_TERRACOTTA("MAGENTA_GLAZED_TERRACOTTA", 0), - MAGENTA_SHULKER_BOX("MAGENTA_SHULKER_BOX", 0), - MAGENTA_STAINED_GLASS("STAINED_GLASS", 2), - MAGENTA_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 2), - MAGENTA_TERRACOTTA("STAINED_CLAY", 2), - MAGENTA_WALL_BANNER("WALL_BANNER", 0), - MAGENTA_WOOL("WOOL", 2), - MAGMA_BLOCK("MAGMA", 0), - MAGMA_CREAM("MAGMA_CREAM", 0), - MAGMA_CUBE_SPAWN_EGG("MONSTER_EGG", 0), - MAP("MAP", 0), - MELON("MELON_BLOCK", 0), - MELON_SEEDS("MELON_SEEDS", 0), - MELON_SLICE("MELON", 0), - MELON_STEM("MELON_STEM", 0), - MILK_BUCKET("MILK_BUCKET", 0), - MINECART("MINECART", 0), - MOOSHROOM_SPAWN_EGG("MONSTER_EGG", 0), - MOSSY_COBBLESTONE("MOSSY_COBBLESTONE", 0), - MOSSY_COBBLESTONE_WALL("COBBLE_WALL", 1), - MOSSY_STONE_BRICKS("SMOOTH_BRICK", 1), - MOVING_PISTON("PISTON_MOVING_PIECE", 0), - MULE_SPAWN_EGG("MONSTER_EGG", 0), - MUSHROOM_STEM("BROWN_MUSHROOM", 0), - MUSHROOM_STEW("MUSHROOM_SOUP", 0), - MUSIC_DISC_11("GOLD_RECORD", 0), - MUSIC_DISC_13("GREEN_RECORD", 0), - MUSIC_DISC_BLOCKS("RECORD_3", 0), - MUSIC_DISC_CAT("RECORD_4", 0), - MUSIC_DISC_CHIRP("RECORD_5", 0), - MUSIC_DISC_FAR("RECORD_6", 0), - MUSIC_DISC_MALL("RECORD_7", 0), - MUSIC_DISC_MELLOHI("RECORD_8", 0), - MUSIC_DISC_STAL("RECORD_9", 0), - MUSIC_DISC_STRAD("RECORD_10", 0), - MUSIC_DISC_WAIT("RECORD_11", 0), - MUSIC_DISC_WARD("RECORD_12", 0), - MUTTON("MUTTON", 0), - MYCELIUM("MYCEL", 0), - NAME_TAG("NAME_TAG", 0), - NAUTILUS_SHELL("STONE", 0), - NETHERRACK("NETHERRACK", 0), - NETHER_BRICK("NETHER_BRICK", 0), - NETHER_BRICKS("NETHER_BRICK", 0), - NETHER_BRICK_FENCE("NETHER_FENCE", 0), - NETHER_BRICK_SLAB("STEP", 6), - NETHER_BRICK_STAIRS("NETHER_BRICK_STAIRS", 0), - NETHER_PORTAL("PORTAL", 0), - NETHER_QUARTZ_ORE("QUARTZ_ORE", 0), - NETHER_STAR("NETHER_STAR", 0), - NETHER_WART("NETHER_STALK", 0), - NETHER_WART_BLOCK("NETHER_WART_BLOCK", 0), - NOTE_BLOCK("NOTE_BLOCK", 0), - OAK_BOAT("BOAT", 0), - OAK_BUTTON("WOOD_BUTTON", 0), - OAK_DOOR("WOOD_DOOR", 0), - OAK_FENCE("FENCE", 0), - OAK_FENCE_GATE("FENCE_GATE", 0), - OAK_LEAVES("LEAVES", 0), - OAK_LOG("LOG", 0), - OAK_PLANKS("WOOD", 0), - OAK_PRESSURE_PLATE("WOOD_PLATE", 0), - OAK_SAPLING("SAPLING", 0), - OAK_SLAB("WOOD_STEP", 0), - OAK_STAIRS("WOOD_STAIRS", 0), - OAK_TRAPDOOR("TRAP_DOOR", 0), - OAK_WOOD("LOG", 0), - OBSERVER("OBSERVER", 0), - OBSIDIAN("OBSIDIAN", 0), - OCELOT_SPAWN_EGG("RECORD_12", 0), - ORANGE_BANNER("BANNER", 14), - ORANGE_BED("BED", 1), - ORANGE_CARPET("CARPET", 1), - ORANGE_CONCRETE("CONCRETE", 1), - ORANGE_CONCRETE_POWDER("CONCRETE_POWDER", 1), - ORANGE_DYE("INK_SACK", 14), - ORANGE_GLAZED_TERRACOTTA("ORANGE_GLAZED_TERRACOTTA", 0), - ORANGE_SHULKER_BOX("ORANGE_SHULKER_BOX", 0), - ORANGE_STAINED_GLASS("STAINED_GLASS", 1), - ORANGE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 1), - ORANGE_TERRACOTTA("STAINED_CLAY", 1), - ORANGE_TULIP("RED_ROSE", 5), - ORANGE_WALL_BANNER("WALL_BANNER", 0), - ORANGE_WOOL("WOOL", 1), - OXEYE_DAISY("RED_ROSE", 8), - PACKED_ICE("PACKED_ICE", 0), - PAINTING("PAINTING", 0), - PAPER("PAPER", 0), - PARROT_SPAWN_EGG("MONSTER_EGG", 0), - PEONY("DOUBLE_PLANT", 5), - PETRIFIED_OAK_SLAB("STONE", 0), - PHANTOM_MEMBRANE("STONE", 0), - PHANTOM_SPAWN_EGG("MONSTER_EGG", 0), - PIG_SPAWN_EGG("MONSTER_EGG", 0), - PINK_BANNER("BANNER", 9), - PINK_BED("BED", 6), - PINK_CARPET("CARPET", 6), - PINK_CONCRETE("CONCRETE", 6), - PINK_CONCRETE_POWDER("CONCRETE_POWDER", 6), - PINK_DYE("INK_SACK", 9), - PINK_GLAZED_TERRACOTTA("PINK_GLAZED_TERRACOTTA", 0), - PINK_SHULKER_BOX("PINK_SHULKER_BOX", 0), - PINK_STAINED_GLASS("STAINED_GLASS", 6), - PINK_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 6), - PINK_TERRACOTTA("STAINED_CLAY", 6), - PINK_TULIP("RED_ROSE", 7), - PINK_WALL_BANNER("WALL_BANNER", 0), - PINK_WOOL("WOOL", 6), - PISTON("PISTON_BASE", 0), - PISTON_HEAD("PISTON_EXTENSION", 0), - PLAYER_HEAD("SKULL", 0), - PLAYER_WALL_HEAD("SKULL", 0), - PODZOL("DIRT", 2), - POISONOUS_POTATO("POISONOUS_POTATO", 0), - POLAR_BEAR_SPAWN_EGG("MONSTER_EGG", 0), - POLISHED_ANDESITE("STONE", 6), - POLISHED_DIORITE("STONE", 4), - POLISHED_GRANITE("STONE", 2), - POPPED_CHORUS_FRUIT("CHORUS_FRUIT_POPPED", 0), - POPPY("RED_ROSE", 0), - PORKCHOP("PORK", 0), - POTATO("POTATO_ITEM", 0), - POTATOES("POTATO", 0), - POTION("POTION", 0), - POTTED_ACACIA_SAPLING("FLOWER_POT", 0), - POTTED_ALLIUM("FLOWER_POT", 0), - POTTED_AZURE_BLUET("FLOWER_POT", 0), - POTTED_BIRCH_SAPLING("FLOWER_POT", 0), - POTTED_BLUE_ORCHID("FLOWER_POT", 0), - POTTED_BROWN_MUSHROOM("FLOWER_POT", 0), - POTTED_CACTUS("FLOWER_POT", 0), - POTTED_DANDELION("FLOWER_POT", 0), - POTTED_DARK_OAK_SAPLING("FLOWER_POT", 0), - POTTED_DEAD_BUSH("FLOWER_POT", 0), - POTTED_FERN("FLOWER_POT", 0), - POTTED_JUNGLE_SAPLING("FLOWER_POT", 0), - POTTED_OAK_SAPLING("FLOWER_POT", 0), - POTTED_ORANGE_TULIP("FLOWER_POT", 0), - POTTED_OXEYE_DAISY("FLOWER_POT", 0), - POTTED_PINK_TULIP("FLOWER_POT", 0), - POTTED_POPPY("FLOWER_POT", 0), - POTTED_RED_MUSHROOM("FLOWER_POT", 0), - POTTED_RED_TULIP("FLOWER_POT", 0), - POTTED_SPRUCE_SAPLING("FLOWER_POT", 0), - POTTED_WHITE_TULIP("FLOWER_POT", 0), - POWERED_RAIL("POWERED_RAIL", 0), - PRISMARINE("PRISMARINE", 0), - PRISMARINE_BRICKS("PRISMARINE", 1), - PRISMARINE_BRICK_SLAB("STONE", 0), - PRISMARINE_BRICK_STAIRS("STONE", 0), - PRISMARINE_CRYSTALS("PRISMARINE_CRYSTALS", 0), - PRISMARINE_SHARD("PRISMARINE_SHARD", 0), - PRISMARINE_SLAB("STONE", 0), - PRISMARINE_STAIRS("STONE", 0), - PUFFERFISH("RAW_FISH", 3), - PUFFERFISH_BUCKET("STONE", 0), - PUFFERFISH_SPAWN_EGG("MONSTER_EGG", 0), - PUMPKIN("PUMPKIN", 0), - PUMPKIN_PIE("PUMPKIN_PIE", 0), - PUMPKIN_SEEDS("PUMPKIN_SEEDS", 0), - PUMPKIN_STEM("PUMPKIN_STEM", 0), - PURPLE_BANNER("BANNER", 5), - PURPLE_BED("BED", 10), - PURPLE_CARPET("CARPET", 10), - PURPLE_CONCRETE("CONCRETE", 10), - PURPLE_CONCRETE_POWDER("CONCRETE_POWDER", 10), - PURPLE_DYE("INK_SACK", 5), - PURPLE_GLAZED_TERRACOTTA("PURPLE_GLAZED_TERRACOTTA", 0), - PURPLE_SHULKER_BOX("PURPLE_SHULKER_BOX", 0), - PURPLE_STAINED_GLASS("STAINED_GLASS", 10), - PURPLE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 10), - PURPLE_TERRACOTTA("STAINED_CLAY", 10), - PURPLE_WALL_BANNER("WALL_BANNER", 0), - PURPLE_WOOL("WOOL", 10), - PURPUR_BLOCK("PURPUR_BLOCK", 0), - PURPUR_PILLAR("PURPUR_PILLAR", 0), - PURPUR_SLAB("PURPUR_SLAB", 0), - PURPUR_STAIRS("PURPUR_STAIRS", 0), - QUARTZ("QUARTZ", 0), - QUARTZ_BLOCK("QUARTZ_BLOCK", 0), - QUARTZ_PILLAR("QUARTZ_BLOCK", 2), - QUARTZ_SLAB("STEP", 7), - QUARTZ_STAIRS("QUARTZ_STAIRS", 0), - RABBIT("RABBIT", 0), - RABBIT_FOOT("RABBIT_FOOT", 0), - RABBIT_HIDE("RABBIT_HIDE", 0), - RABBIT_SPAWN_EGG("MONSTER_EGG", 0), - RABBIT_STEW("RABBIT_STEW", 0), - RAIL("RAILS", 0), - REDSTONE("REDSTONE", 0), - REDSTONE_BLOCK("REDSTONE_BLOCK", 0), - REDSTONE_LAMP("REDSTONE_LAMP_OFF", 0), - REDSTONE_ORE("REDSTONE_ORE", 0), - REDSTONE_TORCH("REDSTONE_TORCH_ON", 0), - REDSTONE_WALL_TORCH("REDSTONE_TORCH_ON", 1), - REDSTONE_WIRE("REDSTONE_WIRE", 0), - RED_BANNER("BANNER", 1), - RED_BED("BED", 14), - RED_CARPET("CARPET", 14), - RED_CONCRETE("CONCRETE", 14), - RED_CONCRETE_POWDER("CONCRETE_POWDER", 14), - RED_GLAZED_TERRACOTTA("RED_GLAZED_TERRACOTTA", 0), - RED_MUSHROOM("RED_MUSHROOM", 0), - RED_MUSHROOM_BLOCK("RED_MUSHROOM", 0), - RED_NETHER_BRICKS("RED_NETHER_BRICK", 0), - RED_SAND("SAND", 1), - RED_SANDSTONE("RED_SANDSTONE", 0), - RED_SANDSTONE_SLAB("STONE_SLAB2", 0), - RED_SANDSTONE_STAIRS("RED_SANDSTONE_STAIRS", 0), - RED_SHULKER_BOX("RED_SHULKER_BOX", 0), - RED_STAINED_GLASS("STAINED_GLASS", 14), - RED_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 14), - RED_TERRACOTTA("STAINED_CLAY", 14), - RED_TULIP("RED_ROSE", 4), - RED_WALL_BANNER("WALL_BANNER", 0), - RED_WOOL("WOOL", 14), - REPEATER("DIODE", 0), - REPEATING_COMMAND_BLOCK("COMMAND_REPEATING", 0), - ROSE_BUSH("DOUBLE_PLANT", 4), - ROSE_RED("INK_SACK", 1), - ROTTEN_FLESH("ROTTEN_FLESH", 0), - SADDLE("SADDLE", 0), - SALMON("RAW_FISH", 1), - SALMON_BUCKET("BUCKET", 0), - SALMON_SPAWN_EGG("MONSTER_EGG", 0), - SAND("SAND", 0), - SANDSTONE("SANDSTONE", 0), - SANDSTONE_SLAB("STEP", 1), - SANDSTONE_STAIRS("SANDSTONE_STAIRS", 0), - SCUTE("STONE", 0), - SEAGRASS("STONE", 0), - SEA_LANTERN("SEA_LANTERN", 0), - SEA_PICKLE("STONE", 0), - SHEARS("SHEARS", 0), - SHEEP_SPAWN_EGG("MONSTER_EGG", 0), - SHIELD("SHIELD", 0), - SHULKER_BOX("PURPLE_SHULKER_BOX", 0), - SHULKER_SHELL("SHULKER_SHELL", 0), - SHULKER_SPAWN_EGG("MONSTER_EGG", 0), - SIGN("SIGN", 0), - SILVERFISH_SPAWN_EGG("MONSTER_EGG", 0), - SKELETON_HORSE_SPAWN_EGG("MONSTER_EGG", 0), - SKELETON_SKULL("SKULL", 0), - SKELETON_SPAWN_EGG("MONSTER_EGG", 0), - SKELETON_WALL_SKULL("SKULL", 0), - SLIME_BALL("SLIME_BALL", 0), - SLIME_BLOCK("SLIME_BLOCK", 0), - SLIME_SPAWN_EGG("MONSTER_EGG", 0), - SMOOTH_QUARTZ("STONE", 0), - SMOOTH_RED_SANDSTONE("RED_SANDSTONE", 2), - SMOOTH_SANDSTONE("SANDSTONE", 2), - SMOOTH_STONE("STEP", 0), - SNOW("SNOW", 0), - SNOWBALL("SNOW_BALL", 0), - SNOW_BLOCK("SNOW_BLOCK", 0), - SOUL_SAND("SOUL_SAND", 0), - SPAWNER("MOB_SPAWNER", 0), - SPECTRAL_ARROW("SPECTRAL_ARROW", 0), - SPIDER_EYE("SPIDER_EYE", 0), - SPIDER_SPAWN_EGG("MONSTER_EGG", 0), - SPLASH_POTION("SPLASH_POTION", 0), - SPONGE("SPONGE", 0), - SPRUCE_BOAT("BOAT_SPRUCE", 0), - SPRUCE_BUTTON("WOOD_BUTTON", 0), - SPRUCE_DOOR("SPRUCE_DOOR", 0), - SPRUCE_FENCE("SPRUCE_FENCE", 0), - SPRUCE_FENCE_GATE("SPRUCE_FENCE_GATE", 0), - SPRUCE_LEAVES("LEAVES", 1), - SPRUCE_LOG("LOG", 1), - SPRUCE_PLANKS("WOOD", 1), - SPRUCE_PRESSURE_PLATE("WOOD_PLATE", 0), - SPRUCE_SAPLING("SAPLING", 1), - SPRUCE_SLAB("WOOD_STEP", 1), - SPRUCE_STAIRS("SPRUCE_WOOD_STAIRS", 0), - SPRUCE_TRAPDOOR("TRAP_DOOR", 0), - SPRUCE_WOOD("LOG", 1), - SQUID_SPAWN_EGG("MONSTER_EGG", 0), - STICK("STICK", 0), - STICKY_PISTON("PISTON_STICKY_BASE", 0), - STONE("STONE", 0), - STONE_AXE("STONE_AXE", 0), - STONE_BRICKS("SMOOTH_BRICK", 0), - STONE_BRICK_SLAB("STEP", 5), - STONE_BRICK_STAIRS("SMOOTH_STAIRS", 0), - STONE_BUTTON("STONE_BUTTON", 0), - STONE_HOE("STONE_HOE", 0), - STONE_PICKAXE("STONE_PICKAXE", 0), - STONE_PRESSURE_PLATE("STONE_PLATE", 0), - STONE_SHOVEL("STONE_SPADE", 0), - STONE_SLAB("STEP", 0), - STONE_SWORD("STONE_SWORD", 0), - STRAY_SPAWN_EGG("MONSTER_EGG", 0), - STRING("STRING", 0), - STRIPPED_ACACIA_LOG("STONE", 0), - STRIPPED_ACACIA_WOOD("STONE", 0), - STRIPPED_BIRCH_LOG("STONE", 0), - STRIPPED_BIRCH_WOOD("STONE", 0), - STRIPPED_DARK_OAK_LOG("STONE", 0), - STRIPPED_DARK_OAK_WOOD("STONE", 0), - STRIPPED_JUNGLE_LOG("STONE", 0), - STRIPPED_JUNGLE_WOOD("STONE", 0), - STRIPPED_OAK_LOG("STONE", 0), - STRIPPED_OAK_WOOD("STONE", 0), - STRIPPED_SPRUCE_LOG("STONE", 0), - STRIPPED_SPRUCE_WOOD("STONE", 0), - STRUCTURE_BLOCK("STRUCTURE_BLOCK", 0), - STRUCTURE_VOID("STRUCTURE_VOID", 0), - SUGAR("SUGAR", 0), - SUGAR_CANE("SUGAR_CANE", 0), - SUNFLOWER("DOUBLE_PLANT", 0), - TALL_GRASS("DOUBLE_PLANT", 2), - TALL_SEAGRASS("STONE", 0), - TERRACOTTA("HARD_CLAY", 0), - TIPPED_ARROW("TIPPED_ARROW", 0), - TNT("TNT", 0), - TNT_MINECART("EXPLOSIVE_MINECART", 0), - TORCH("TORCH", 0), - TOTEM_OF_UNDYING("TOTEM", 0), - TRAPPED_CHEST("TRAPPED_CHEST", 0), - TRIDENT("STONE", 0), - TRIPWIRE("TRIPWIRE", 0), - TRIPWIRE_HOOK("TRIPWIRE_HOOK", 0), - TROPICAL_FISH("RAW_FISH", 0), - TROPICAL_FISH_BUCKET("BUCKET", 0), - TROPICAL_FISH_SPAWN_EGG("MONSTER_EGG", 0), - TUBE_CORAL("STONE", 0), - TUBE_CORAL_BLOCK("STONE", 0), - TUBE_CORAL_FAN("STONE", 0), - TURTLE_EGG("MONSTER_EGG", 0), - TURTLE_HELMET("STONE", 0), - TURTLE_SPAWN_EGG("MONSTER_EGG", 0), - VEX_SPAWN_EGG("MONSTER_EGG", 0), - VILLAGER_SPAWN_EGG("MONSTER_EGG", 0), - VINDICATOR_SPAWN_EGG("MONSTER_EGG", 0), - VINE("VINE", 0), - VOID_AIR("AIR", 0), - WALL_SIGN("WALL_SIGN", 0), - WALL_TORCH("TORCH", 1), - WATER("WATER", 0), - WATER_BUCKET("WATER_BUCKET", 0), - WET_SPONGE("SPONGE", 1), - WHEAT("WHEAT", 0), - WHEAT_SEEDS("SEEDS", 0), - WHITE_BANNER("BANNER", 15), - WHITE_BED("BED", 0), - WHITE_CARPET("CARPET", 0), - WHITE_CONCRETE("CONCRETE", 0), - WHITE_CONCRETE_POWDER("CONCRETE_POWDER", 0), - WHITE_GLAZED_TERRACOTTA("WHITE_GLAZED_TERRACOTTA", 0), - WHITE_SHULKER_BOX("WHITE_SHULKER_BOX", 0), - WHITE_STAINED_GLASS("STAINED_GLASS", 0), - WHITE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 0), - WHITE_TERRACOTTA("TERRACOTTA", 0), - WHITE_TULIP("RED_ROSE", 6), - WHITE_WALL_BANNER("WALL_BANNER", 0), - WHITE_WOOL("WOOL", 0), - WITCH_SPAWN_EGG("MONSTER_EGG", 0), - WITHER_SKELETON_SKULL("SKULL", 0), - WITHER_SKELETON_SPAWN_EGG("MONSTER_EGG", 0), - WITHER_SKELETON_WALL_SKULL("SKULL", 0), - WOLF_SPAWN_EGG("MONSTER_EGG", 0), - WOODEN_AXE("WOOD_AXE", 0), - WOODEN_HOE("WOOD_HOE", 0), - WOODEN_PICKAXE("WOOD_PICKAXE", 0), - WOODEN_SHOVEL("WOOD_SPADE", 0), - WOODEN_SWORD("WOOD_SWORD", 0), - WRITABLE_BOOK("BOOK_AND_QUILL", 0), - WRITTEN_BOOK("WRITTEN_BOOK", 0), - YELLOW_BANNER("BANNER", 11), - YELLOW_BED("BED", 4), - YELLOW_CARPET("CARPET", 4), - YELLOW_CONCRETE("CONCRETE", 4), - YELLOW_CONCRETE_POWDER("CONCRETE_POWDER", 4), - YELLOW_GLAZED_TERRACOTTA("YELLOW_GLAZED_TERRACOTTA", 0), - YELLOW_SHULKER_BOX("YELLOW_SHULKER_BOX", 0), - YELLOW_STAINED_GLASS("STAINED_GLASS", 4), - YELLOW_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 4), - YELLOW_TERRACOTTA("STAINED_CLAY", 4), - YELLOW_WALL_BANNER("WALL_BANNER", 0), - YELLOW_WOOL("WOOL", 4), - ZOMBIE_HEAD("SKULL", 0), - ZOMBIE_HORSE_SPAWN_EGG("MONSTER_EGG", 0), - ZOMBIE_PIGMAN_SPAWN_EGG("MONSTER_EGG", 0), - ZOMBIE_SPAWN_EGG("MONSTER_EGG", 0), - ZOMBIE_VILLAGER_SPAWN_EGG("MONSTER_EGG", 0), - ZOMBIE_WALL_HEAD("SKULL", 0), - ; + ACACIA_BOAT("BOAT_ACACIA", 0), + ACACIA_BUTTON("WOOD_BUTTON", 0), + ACACIA_DOOR("ACACIA_DOOR", 0), + ACACIA_FENCE("ACACIA_FENCE", 0), + ACACIA_FENCE_GATE("ACACIA_FENCE_GATE", 0), + ACACIA_LEAVES("LEAVES_2", 0), + ACACIA_LOG("LOG_2", 0), + ACACIA_PLANKS("WOOD", 4), + ACACIA_PRESSURE_PLATE("WOOD_PLATE", 0), + ACACIA_SAPLING("SAPLING", 4), + ACACIA_SLAB("WOOD_STEP", 4), + ACACIA_STAIRS("ACACIA_STAIRS", 4), + ACACIA_TRAPDOOR("TRAP_DOOR", 0), + ACACIA_WOOD("LOG_2", 0), + ACTIVATOR_RAIL("ACTIVATOR_RAIL", 0), + AIR("AIR", 0), + ALLIUM("STONE", 0), + ANDESITE("STONE", 5), + ANVIL("ANVIL", 0), + APPLE("APPLE", 0), + ARMOR_STAND("ARMOR_STAND", 0), + ARROW("ARROW", 0), + ATTACHED_MELON_STEM("MELON_STEM", 7), + ATTACHED_PUMPKIN_STEM("PUMPKIN_STEM", 7), + AZURE_BLUET("RED_ROSE", 3), + BAKED_POTATO("BAKED_POTATO", 0), + BARRIER("BARRIER", 0), + BAT_SPAWN_EGG("MONSTER_EGG", 0), + BEACON("BEACON", 0), + BEDROCK("BEDROCK", 0), + BEEF("RAW_BEEF", 0), + BEETROOT("BEETROOT", 0), + BEETROOTS("BEETROOT", 0), + BEETROOT_SEEDS("BEETROOT_SEEDS", 0), + BEETROOT_SOUP("BEETROOT_SOUP", 0), + BIRCH_BOAT("BOAT_BIRCH", 0), + BIRCH_BUTTON("WOOD_BUTTON", 0), + BIRCH_DOOR("BIRCH_DOOR", 0), + BIRCH_FENCE("BIRCH_FENCE", 0), + BIRCH_FENCE_GATE("BIRCH_FENCE_GATE", 0), + BIRCH_LEAVES("LEAVES", 2), + BIRCH_LOG("LOG", 2), + BIRCH_PLANKS("WOOD", 2), + BIRCH_PRESSURE_PLATE("WOOD_PLATE", 0), + BIRCH_SAPLING("SAPLING", 2), + BIRCH_SLAB("WOOD_STEP", 2), + BIRCH_STAIRS("BIRCH_WOOD_STAIRS", 0), + BIRCH_TRAPDOOR("TRAP_DOOR", 0), + BIRCH_WOOD("LOG", 2), + BLACK_BANNER("BANNER", 0), + BLACK_BED("BED", 15), + BLACK_CARPET("CARPET", 15), + BLACK_CONCRETE("CONCRETE", 15), + BLACK_CONCRETE_POWDER("CONCRETE_POWDER", 15), + BLACK_GLAZED_TERRACOTTA("BLACK_GLAZED_TERRACOTTA", 0), + BLACK_SHULKER_BOX("BLACK_SHULKER_BOX", 0), + BLACK_STAINED_GLASS("STAINED_GLASS", 15), + BLACK_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 15), + BLACK_TERRACOTTA("STAINED_CLAY", 15), + BLACK_WALL_BANNER("WALL_BANNER", 0), + BLACK_WOOL("WOOL", 15), + BLAZE_POWDER("BLAZE_POWDER", 0), + BLAZE_ROD("BLAZE_ROD", 0), + BLAZE_SPAWN_EGG("MONSTER_EGG", 0), + BLUE_BANNER("BANNER", 11), + BLUE_BED("BED", 4), + BLUE_CARPET("CARPET", 11), + BLUE_CONCRETE("CONCRETE", 11), + BLUE_CONCRETE_POWDER("CONCRETE_POWDER", 11), + BLUE_GLAZED_TERRACOTTA("BLUE_GLAZED_TERRACOTTA", 0), + BLUE_ICE("PACKED_ICE", 0), + BLUE_ORCHID("RED_ROSE", 1), + BLUE_SHULKER_BOX("BLUE_SHULKER_BOX", 0), + BLUE_STAINED_GLASS("STAINED_GLASS", 11), + BLUE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 11), + BLUE_TERRACOTTA("STAINED_CLAY", 11), + BLUE_WALL_BANNER("WALL_BANNER", 11), + BLUE_WOOL("WOOL", 11), + BONE("BONE", 0), + BONE_BLOCK("BONE_BLOCK", 0), + BONE_MEAL("INK_SACK", 15), + BOOK("BOOK", 0), + BOOKSHELF("BOOKSHELF", 0), + BOW("BOW", 0), + BOWL("BOWL", 0), + BRAIN_CORAL("STONE", 0), + BRAIN_CORAL_BLOCK("STONE", 0), + BRAIN_CORAL_FAN("STONE", 0), + BREAD("BREAD", 0), + BREWING_STAND("BREWING_STAND", 0), + BRICK("CLAY_BRICK", 0), + BRICKS("BRICK", 0), + BRICK_SLAB("STEP", 4), + BRICK_STAIRS("BRICK_STAIRS", 0), + BROWN_BANNER("BANNER", 3), + BROWN_BED("BED", 12), + BROWN_CARPET("CARPET", 12), + BROWN_CONCRETE("CONCRETE", 12), + BROWN_CONCRETE_POWDER("CONCRETE_POWDER", 12), + BROWN_GLAZED_TERRACOTTA("BROWN_GLAZED_TERRACOTTA", 0), + BROWN_MUSHROOM("BROWN_MUSHROOM", 0), + BROWN_MUSHROOM_BLOCK("BROWN_MUSHROOM", 0), //UNSURE + BROWN_SHULKER_BOX("BROWN_SHULKER_BOX", 0), + BROWN_STAINED_GLASS("STAINED_GLASS", 12), + BROWN_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 12), + BROWN_TERRACOTTA("STAINED_CLAY", 12), + BROWN_WALL_BANNER("WALL_BANNER", 3), + BROWN_WOOL("WOOL", 12), + BUBBLE_COLUMN("STONE", 0), + BUBBLE_CORAL("STONE", 0), + BUBBLE_CORAL_BLOCK("STONE", 0), + BUBBLE_CORAL_FAN("STONE", 0), + BUCKET("BUCKET", 0), + CACTUS("CACTUS", 0), + CACTUS_GREEN("INK_SACK", 2), + CAKE("CAKE", 0), + CARROT("CARROT_ITEM", 0), + CARROTS("CARROT", 0), + CARROT_ON_A_STICK("CARROT_STICK", 0), + CARVED_PUMPKIN("PUMPKIN", 0), + CAULDRON("CAULDRON", 0), + CAVE_AIR("AIR", 0), + CAVE_SPIDER_SPAWN_EGG("MONSTER_EGG", 0), + CHAINMAIL_BOOTS("CHAINMAIL_BOOTS", 0), + CHAINMAIL_CHESTPLATE("CHAINMAIL_CHESTPLATE", 0), + CHAINMAIL_HELMET("CHAINMAIL_HELMET", 0), + CHAINMAIL_LEGGINGS("CHAINMAIL_LEGGINGS", 0), + CHAIN_COMMAND_BLOCK("COMMAND_CHAIN", 0), + CHARCOAL("COAL", 1), + CHEST("CHEST", 0), + CHEST_MINECART("STORAGE_MINECART", 0), + CHICKEN("RAW_CHICKEN", 0), + CHICKEN_SPAWN_EGG("MONSTER_EGG", 0), + CHIPPED_ANVIL("ANVIL", 1), + CHISELED_QUARTZ_BLOCK("QUARTZ_BLOCK", 1), + CHISELED_RED_SANDSTONE("RED_SANDSTONE", 1), + CHISELED_SANDSTONE("SANDSTONE", 1), + CHISELED_STONE_BRICKS("SMOOTH_BRICK", 3), + CHORUS_FLOWER("CHORUS_FLOWER", 0), + CHORUS_FRUIT("CHORUS_FRUIT", 0), + CHORUS_PLANT("CHORUS_PLANT", 0), + CLAY("CLAY", 0), + CLAY_BALL("CLAY_BALL", 0), + CLOCK("WATCH", 0), + COAL("COAL", 0), + COAL_BLOCK("COAL_BLOCK", 0), + COAL_ORE("COAL_ORE", 0), + COARSE_DIRT("DIRT", 1), + COBBLESTONE("COBBLESTONE", 0), + COBBLESTONE_SLAB("STEP", 3), + COBBLESTONE_STAIRS("COBBLESTONE_STAIRS", 0), + COBBLESTONE_WALL("COBBLE_WALL", 0), + COBWEB("WEB", 0), + COCOA("COCOA", 0), + COCOA_BEANS("INK_SACK", 3), + COD("RAW_FISH", 0), + COD_BUCKET("BUCKET", 0), + COD_SPAWN_EGG("MONSTER_EGG", 0), + COMMAND_BLOCK("COMMAND", 0), + COMMAND_BLOCK_MINECART("COMMAND_MINECART", 0), + COMPARATOR("REDSTONE_COMPARATOR", 0), + COMPASS("COMPASS", 0), + CONDUIT("STONE", 0), + COOKED_BEEF("COOKED_BEEF", 0), + COOKED_CHICKEN("COOKED_CHICKEN", 0), + COOKED_COD("COOKED_FISH", 0), + COOKED_MUTTON("COOKED_MUTTON", 0), + COOKED_PORKCHOP("GRILLED_PORK", 0), + COOKED_RABBIT("COOKED_RABBIT", 0), + COOKED_SALMON("COOKED_FISH", 1), + COOKIE("COOKIE", 0), + COW_SPAWN_EGG("MONSTER_EGG", 0), + CRACKED_STONE_BRICKS("SMOOTH_BRICK", 2), + CRAFTING_TABLE("WORKBENCH", 0), + CREEPER_HEAD("SKULL", 0), + CREEPER_SPAWN_EGG("MONSTER_EGG", 0), + CREEPER_WALL_HEAD("SKULL", 0), + CUT_RED_SANDSTONE("STONE", 0), + CUT_SANDSTONE("STONE", 0), + CYAN_BANNER("BANNER", 6), + CYAN_BED("BED", 9), + CYAN_CARPET("CARPET", 9), + CYAN_CONCRETE("CONCRETE", 9), + CYAN_CONCRETE_POWDER("CONCRETE_POWDER", 9), + CYAN_DYE("INK_SACK", 6), + CYAN_GLAZED_TERRACOTTA("CYAN_GLAZED_TERRACOTTA", 0), + CYAN_SHULKER_BOX("CYAN_SHULKER_BOX", 0), + CYAN_STAINED_GLASS("STAINED_GLASS", 9), + CYAN_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 9), + CYAN_TERRACOTTA("STAINED_CLAY", 9), + CYAN_WALL_BANNER("WALL_BANNER", 0), + CYAN_WOOL("WOOL", 9), + DAMAGED_ANVIL("ANVIL", 2), + DANDELION("YELLOW_FLOWER", 0), + DANDELION_YELLOW("INK_SACK", 11), + DARK_OAK_BOAT("BOAT_DARK_OAK", 0), + DARK_OAK_BUTTON("WOOD_BUTTON", 0), + DARK_OAK_DOOR("DARK_OAK_DOOR", 0), + DARK_OAK_FENCE("DARK_OAK_FENCE", 0), + DARK_OAK_FENCE_GATE("DARK_OAK_FENCE_GATE", 0), + DARK_OAK_LEAVES("LEAVES_2", 1), + DARK_OAK_LOG("LOG_2", 1), + DARK_OAK_PLANKS("WOOD", 5), + DARK_OAK_PRESSURE_PLATE("WOOD_PLATE", 0), + DARK_OAK_SAPLING("SAPLING", 5), + DARK_OAK_SLAB("WOOD_STEP", 0), + DARK_OAK_STAIRS("DARK_OAK_STAIRS", 0), + DARK_OAK_TRAPDOOR("TRAP_DOOR", 0), + DARK_OAK_WOOD("LOG_2", 1), + DARK_PRISMARINE("PRISMARINE", 2), + DARK_PRISMARINE_SLAB("STONE", 0), + DARK_PRISMARINE_STAIRS("STONE", 0), + DAYLIGHT_DETECTOR("DAYLIGHT_DETECTOR", 0), + DEAD_BRAIN_CORAL_BLOCK("STONE", 0), + DEAD_BUBBLE_CORAL_BLOCK("STONE", 0), + DEAD_BUSH("DEAD_BUSH", 0), + DEAD_FIRE_CORAL_BLOCK("STONE", 0), + DEAD_HORN_CORAL_BLOCK("STONE", 0), + DEAD_TUBE_CORAL_BLOCK("STONE", 0), + DEBUG_STICK("STICK", 0), + DETECTOR_RAIL("DETECTOR_RAIL", 0), + DIAMOND("DIAMOND", 0), + DIAMOND_AXE("DIAMOND_AXE", 0), + DIAMOND_BLOCK("DIAMOND_BLOCK", 0), + DIAMOND_BOOTS("DIAMOND_BOOTS", 0), + DIAMOND_CHESTPLATE("DIAMOND_CHESTPLATE", 0), + DIAMOND_HELMET("DIAMOND_HELMET", 0), + DIAMOND_HOE("DIAMOND_HOE", 0), + DIAMOND_HORSE_ARMOR("DIAMOND_BARDING", 0), + DIAMOND_LEGGINGS("DIAMOND_LEGGINGS", 0), + DIAMOND_ORE("DIAMOND_ORE", 0), + DIAMOND_PICKAXE("DIAMOND_PICKAXE", 0), + DIAMOND_SHOVEL("DIAMOND_SPADE", 0), + DIAMOND_SWORD("DIAMOND_SWORD", 0), + DIORITE("STONE", 3), + DIRT("DIRT", 0), + DISPENSER("DISPENSER", 0), + DOLPHIN_SPAWN_EGG("MONSTER_EGG", 0), + DONKEY_SPAWN_EGG("MONSTER_EGG", 0), + DRAGON_BREATH("DRAGONS_BREATH", 0), + DRAGON_EGG("DRAGON_EGG", 0), + DRAGON_HEAD("SKULL", 5), + DRAGON_WALL_HEAD("SKULL", 0), + DRIED_KELP("STONE", 0), + DRIED_KELP_BLOCK("STONE", 0), + DROPPER("DROPPER", 0), + DROWNED_SPAWN_EGG("MONSTER_EGG", 0), + EGG("EGG", 0), + ELDER_GUARDIAN_SPAWN_EGG("MONSTER_EGG", 0), + ELYTRA("ELYTRA", 0), + EMERALD("EMERALD", 0), + EMERALD_BLOCK("EMERALD_BLOCK", 0), + EMERALD_ORE("EMERALD_ORE", 0), + ENCHANTED_BOOK("ENCHANTED_BOOK", 0), + ENCHANTED_GOLDEN_APPLE("GOLDEN_APPLE", 1), + ENCHANTING_TABLE("ENCHANTING_TABLE", 0), + ENDERMAN_SPAWN_EGG("MONSTER_EGG", 0), + ENDERMITE_SPAWN_EGG("MONSTER_EGG", 0), + ENDER_CHEST("ENDER_CHEST", 0), + ENDER_EYE("EYE_OF_ENDER", 0), + ENDER_PEARL("ENDER_PEARL", 0), + END_CRYSTAL("END_CRYSTAL", 0), + END_GATEWAY("END_GATEWAY", 0), + END_PORTAL("ENDER_PORTAL", 0), + END_PORTAL_FRAME("ENDER_PORTAL_FRAME", 0), + END_ROD("END_ROD", 0), + END_STONE("ENDER_STONE", 0), + END_STONE_BRICKS("END_BRICKS", 0), + EVOKER_SPAWN_EGG("MONSTER_EGG", 0), + EXPERIENCE_BOTTLE("EXP_BOTTLE", 0), + FARMLAND("SOIL", 0), + FEATHER("FEATHER", 0), + FERMENTED_SPIDER_EYE("FERMENTED_SPIDER_EYE", 0), + FERN("LONG_GRASS", 2), + FILLED_MAP("MAP", 0), + FIRE("FIRE", 0), + FIREWORK_ROCKET("FIREWORK", 0), + FIREWORK_STAR("FIREWORK_CHARGE", 0), + FIRE_CHARGE("FIREBALL", 0), + FIRE_CORAL("STONE", 0), + FIRE_CORAL_BLOCK("STONE", 0), + FIRE_CORAL_FAN("STONE", 0), + FISHING_ROD("FISHING_ROD", 0), + FLINT("FLINT", 0), + FLINT_AND_STEEL("FLINT_AND_STEEL", 0), + FLOWER_POT("FLOWER_POT", 0), + FROSTED_ICE("FROSTED_ICE", 0), + FURNACE("FURNACE", 0), + FURNACE_MINECART("POWERED_MINECART", 0), + GHAST_SPAWN_EGG("MONSTER_EGG", 0), + GHAST_TEAR("GHAST_TEAR", 0), + GLASS("GLASS", 0), + GLASS_BOTTLE("GLASS_BOTTLE", 0), + GLASS_PANE("THIN_GLASS", 0), + GLISTERING_MELON_SLICE("SPECKLED_MELON", 0), + GLOWSTONE("GLOWSTONE", 0), + GLOWSTONE_DUST("GLOWSTONE_DUST", 0), + GOLDEN_APPLE("GOLDEN_APPLE", 0), + GOLDEN_AXE("GOLD_AXE", 0), + GOLDEN_BOOTS("GOLD_BOOTS", 0), + GOLDEN_CARROT("GOLDEN_CARROT", 0), + GOLDEN_CHESTPLATE("GOLD_CHESTPLATE", 0), + GOLDEN_HELMET("GOLD_HELMET", 0), + GOLDEN_HOE("GOLD_HOE", 0), + GOLDEN_HORSE_ARMOR("GOLD_BARDING", 0), + GOLDEN_LEGGINGS("GOLD_LEGGINGS", 0), + GOLDEN_PICKAXE("GOLD_PICKAXE", 0), + GOLDEN_SHOVEL("GOLD_SPADE", 0), + GOLDEN_SWORD("GOLD_SWORD", 0), + GOLD_BLOCK("GOLD_BLOCK", 0), + GOLD_INGOT("GOLD_INGOT", 0), + GOLD_NUGGET("GOLD_NUGGET", 0), + GOLD_ORE("GOLD_ORE", 0), + GRANITE("STONE", 1), + GRASS("GRASS", 0), + GRASS_BLOCK("GRASS", 0), + GRASS_PATH("GRASS_PATH", 0), + GRAVEL("GRAVEL", 0), + GRAY_BANNER("BANNER", 8), + GRAY_BED("BED", 7), + GRAY_CARPET("CARPET", 7), + GRAY_CONCRETE("CONCRETE", 7), + GRAY_CONCRETE_POWDER("CONCRETE_POWDER", 7), + GRAY_DYE("INK_SACK", 8), + GRAY_GLAZED_TERRACOTTA("GRAY_GLAZED_TERRACOTTA", 0), + GRAY_SHULKER_BOX("GRAY_SHULKER_BOX", 0), + GRAY_STAINED_GLASS("STAINED_GLASS", 7), + GRAY_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 7), + GRAY_TERRACOTTA("STAINED_CLAY", 7), + GRAY_WALL_BANNER("WALL_BANNER", 0), + GRAY_WOOL("WOOL", 7), + GREEN_BANNER("BANNER", 2), + GREEN_BED("BED", 13), + GREEN_CARPET("CARPET", 13), + GREEN_CONCRETE("CONCRETE", 13), + GREEN_CONCRETE_POWDER("CONCRETE_POWDER", 13), + GREEN_GLAZED_TERRACOTTA("GREEN_GLAZED_TERRACOTTA", 0), + GREEN_SHULKER_BOX("GREEN_SHULKER_BOX", 0), + GREEN_STAINED_GLASS("STAINED_GLASS", 13), + GREEN_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 13), + GREEN_TERRACOTTA("STAINED_CLAY", 13), + GREEN_WALL_BANNER("WALL_BANNER", 0), + GREEN_WOOL("WOOL", 13), + GUARDIAN_SPAWN_EGG("MONSTER_EGG", 0), + GUNPOWDER("SULPHUR", 0), + HAY_BLOCK("HAY_BLOCK", 0), + HEART_OF_THE_SEA("STONE", 0), + HEAVY_WEIGHTED_PRESSURE_PLATE("IRON_PLATE", 0), + HOPPER("HOPPER", 0), + HOPPER_MINECART("HOPPER_MINECART", 0), + HORN_CORAL("STONE", 0), + HORN_CORAL_BLOCK("STONE", 0), + HORN_CORAL_FAN("STONE", 0), + HORSE_SPAWN_EGG("MONSTER_EGG", 0), + HUSK_SPAWN_EGG("MONSTER_EGG", 0), + ICE("ICE", 0), + INFESTED_CHISELED_STONE_BRICKS("MONSTER_EGGS", 5), + INFESTED_COBBLESTONE("MONSTER_EGGS", 1), + INFESTED_CRACKED_STONE_BRICKS("MONSTER_EGGS", 4), + INFESTED_MOSSY_STONE_BRICKS("MONSTER_EGGS", 3), + INFESTED_STONE("MONSTER_EGGS", 0), + INFESTED_STONE_BRICKS("MONSTER_EGGS", 2), + INK_SAC("INK_SACK", 0), + IRON_AXE("IRON_AXE", 0), + IRON_BARS("IRON_FENCE", 0), + IRON_BLOCK("IRON_BLOCK", 0), + IRON_BOOTS("IRON_BOOTS", 0), + IRON_CHESTPLATE("IRON_CHESTPLATE", 0), + IRON_DOOR("IRON_DOOR", 0), + IRON_HELMET("IRON_HELMET", 0), + IRON_HOE("IRON_HOE", 0), + IRON_HORSE_ARMOR("IRON_BARDING", 0), + IRON_INGOT("IRON_INGOT", 0), + IRON_LEGGINGS("IRON_LEGGINGS", 0), + IRON_NUGGET("IRON_NUGGET", 0), + IRON_ORE("IRON_ORE", 0), + IRON_PICKAXE("IRON_PICKAXE", 0), + IRON_SHOVEL("IRON_SPADE", 0), + IRON_SWORD("IRON_SWORD", 0), + IRON_TRAPDOOR("IRON_TRAPDOOR", 0), + ITEM_FRAME("ITEM_FRAME", 0), + JACK_O_LANTERN("JACK_O_LANTERN", 0), + JUKEBOX("JUKEBOX", 0), + JUNGLE_BOAT("BOAT_JUNGLE", 0), + JUNGLE_BUTTON("WOOD_BUTTON", 0), + JUNGLE_DOOR("JUNGLE_DOOR", 0), + JUNGLE_FENCE("JUNGLE_FENCE", 0), + JUNGLE_FENCE_GATE("JUNGLE_FENCE_GATE", 0), + JUNGLE_LEAVES("LEAVES", 3), + JUNGLE_LOG("LOG", 3), + JUNGLE_PLANKS("WOOD", 3), + JUNGLE_PRESSURE_PLATE("WOOD_PLATE", 0), + JUNGLE_SAPLING("SAPLING", 3), + JUNGLE_SLAB("WOOD_STEP", 3), + JUNGLE_STAIRS("JUNGLE_WOOD_STAIRS", 0), + JUNGLE_TRAPDOOR("TRAP_DOOR", 0), + JUNGLE_WOOD("LOG", 3), + KELP("STONE", 0), + KELP_PLANT("STONE", 0), + KNOWLEDGE_BOOK("KNOWLEDGE_BOOK", 0), + LADDER("LADDER", 0), + LAPIS_BLOCK("LAPIS_BLOCK", 0), + LAPIS_LAZULI("INK_SACK", 4), + LAPIS_ORE("LAPIS_ORE", 0), + LARGE_FERN("DOUBLE_PLANT", 3), + LAVA("LAVA", 0), + LAVA_BUCKET("LAVA_BUCKET", 0), + LEAD("LEASH", 0), + LEATHER("LEATHER", 0), + LEATHER_BOOTS("LEATHER_BOOTS", 0), + LEATHER_CHESTPLATE("LEATHER_CHESTPLATE", 0), + LEATHER_HELMET("LEATHER_HELMET", 0), + LEATHER_LEGGINGS("LEATHER_LEGGINGS", 0), + LEVER("LEVER", 0), + LIGHT_BLUE_BANNER("BANNER", 12), + LIGHT_BLUE_BED("BED", 3), + LIGHT_BLUE_CARPET("CARPET", 3), + LIGHT_BLUE_CONCRETE("CONCRETE", 3), + LIGHT_BLUE_CONCRETE_POWDER("CONCRETE_POWDER", 3), + LIGHT_BLUE_DYE("INK_SACK", 12), + LIGHT_BLUE_GLAZED_TERRACOTTA("LIGHT_BLUE_GLAZED_TERRACOTTA", 0), + LIGHT_BLUE_SHULKER_BOX("LIGHT_BLUE_SHULKER_BOX", 0), + LIGHT_BLUE_STAINED_GLASS("STAINED_GLASS", 3), + LIGHT_BLUE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 3), + LIGHT_BLUE_TERRACOTTA("STAINED_CLAY", 3), + LIGHT_BLUE_WALL_BANNER("BANNER", 0), + LIGHT_BLUE_WOOL("WOOL", 3), + LIGHT_GRAY_BANNER("BANNER", 7), + LIGHT_GRAY_BED("BED", 8), + LIGHT_GRAY_CARPET("CARPET", 8), + LIGHT_GRAY_CONCRETE("CONCRETE", 8), + LIGHT_GRAY_CONCRETE_POWDER("CONCRETE_POWDER", 8), + LIGHT_GRAY_DYE("INK_SACK", 7), + LIGHT_GRAY_GLAZED_TERRACOTTA("SILVER_GLAZED_TERRACOTTA", 0), + LIGHT_GRAY_SHULKER_BOX("SILVER_SHULKER_BOX", 0), + LIGHT_GRAY_STAINED_GLASS("STAINED_GLASS", 8), + LIGHT_GRAY_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 8), + LIGHT_GRAY_TERRACOTTA("STAINED_CLAY", 8), + LIGHT_GRAY_WALL_BANNER("WALL_BANNER", 0), + LIGHT_GRAY_WOOL("WOOL", 8), + LIGHT_WEIGHTED_PRESSURE_PLATE("GOLD_PLATE", 0), + LILAC("DOUBLE_PLANT", 1), + LILY_PAD("WATER_LILY", 0), + LIME_BANNER("BANNER", 10), + LIME_BED("BED", 5), + LIME_CARPET("CARPET", 5), + LIME_CONCRETE("CONCRETE", 5), + LIME_CONCRETE_POWDER("CONCRETE_POWDER", 5), + LIME_DYE("INK_SACK", 10), + LIME_GLAZED_TERRACOTTA("LIME_GLAZED_TERRACOTTA", 0), + LIME_SHULKER_BOX("LIME_SHULKER_BOX", 0), + LIME_STAINED_GLASS("STAINED_GLASS", 5), + LIME_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 5), + LIME_TERRACOTTA("STAINED_CLAY", 5), + LIME_WALL_BANNER("WALL_BANNER", 0), + LIME_WOOL("WOOL", 5), + LINGERING_POTION("LINGERING_POTION", 0), + LLAMA_SPAWN_EGG("MONSTER_EGG", 0), + MAGENTA_BANNER("BANNER", 13), + MAGENTA_BED("BED", 2), + MAGENTA_CARPET("CARPET", 2), + MAGENTA_CONCRETE("CONCRETE", 2), + MAGENTA_CONCRETE_POWDER("CONCRETE_POWDER", 2), + MAGENTA_DYE("INK_SACK", 13), + MAGENTA_GLAZED_TERRACOTTA("MAGENTA_GLAZED_TERRACOTTA", 0), + MAGENTA_SHULKER_BOX("MAGENTA_SHULKER_BOX", 0), + MAGENTA_STAINED_GLASS("STAINED_GLASS", 2), + MAGENTA_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 2), + MAGENTA_TERRACOTTA("STAINED_CLAY", 2), + MAGENTA_WALL_BANNER("WALL_BANNER", 0), + MAGENTA_WOOL("WOOL", 2), + MAGMA_BLOCK("MAGMA", 0), + MAGMA_CREAM("MAGMA_CREAM", 0), + MAGMA_CUBE_SPAWN_EGG("MONSTER_EGG", 0), + MAP("MAP", 0), + MELON("MELON_BLOCK", 0), + MELON_SEEDS("MELON_SEEDS", 0), + MELON_SLICE("MELON", 0), + MELON_STEM("MELON_STEM", 0), + MILK_BUCKET("MILK_BUCKET", 0), + MINECART("MINECART", 0), + MOOSHROOM_SPAWN_EGG("MONSTER_EGG", 0), + MOSSY_COBBLESTONE("MOSSY_COBBLESTONE", 0), + MOSSY_COBBLESTONE_WALL("COBBLE_WALL", 1), + MOSSY_STONE_BRICKS("SMOOTH_BRICK", 1), + MOVING_PISTON("PISTON_MOVING_PIECE", 0), + MULE_SPAWN_EGG("MONSTER_EGG", 0), + MUSHROOM_STEM("BROWN_MUSHROOM", 0), + MUSHROOM_STEW("MUSHROOM_SOUP", 0), + MUSIC_DISC_11("GOLD_RECORD", 0), + MUSIC_DISC_13("GREEN_RECORD", 0), + MUSIC_DISC_BLOCKS("RECORD_3", 0), + MUSIC_DISC_CAT("RECORD_4", 0), + MUSIC_DISC_CHIRP("RECORD_5", 0), + MUSIC_DISC_FAR("RECORD_6", 0), + MUSIC_DISC_MALL("RECORD_7", 0), + MUSIC_DISC_MELLOHI("RECORD_8", 0), + MUSIC_DISC_STAL("RECORD_9", 0), + MUSIC_DISC_STRAD("RECORD_10", 0), + MUSIC_DISC_WAIT("RECORD_11", 0), + MUSIC_DISC_WARD("RECORD_12", 0), + MUTTON("MUTTON", 0), + MYCELIUM("MYCEL", 0), + NAME_TAG("NAME_TAG", 0), + NAUTILUS_SHELL("STONE", 0), + NETHERRACK("NETHERRACK", 0), + NETHER_BRICK("NETHER_BRICK", 0), + NETHER_BRICKS("NETHER_BRICK", 0), + NETHER_BRICK_FENCE("NETHER_FENCE", 0), + NETHER_BRICK_SLAB("STEP", 6), + NETHER_BRICK_STAIRS("NETHER_BRICK_STAIRS", 0), + NETHER_PORTAL("PORTAL", 0), + NETHER_QUARTZ_ORE("QUARTZ_ORE", 0), + NETHER_STAR("NETHER_STAR", 0), + NETHER_WART("NETHER_STALK", 0), + NETHER_WART_BLOCK("NETHER_WART_BLOCK", 0), + NOTE_BLOCK("NOTE_BLOCK", 0), + OAK_BOAT("BOAT", 0), + OAK_BUTTON("WOOD_BUTTON", 0), + OAK_DOOR("WOOD_DOOR", 0), + OAK_FENCE("FENCE", 0), + OAK_FENCE_GATE("FENCE_GATE", 0), + OAK_LEAVES("LEAVES", 0), + OAK_LOG("LOG", 0), + OAK_PLANKS("WOOD", 0), + OAK_PRESSURE_PLATE("WOOD_PLATE", 0), + OAK_SAPLING("SAPLING", 0), + OAK_SLAB("WOOD_STEP", 0), + OAK_STAIRS("WOOD_STAIRS", 0), + OAK_TRAPDOOR("TRAP_DOOR", 0), + OAK_WOOD("LOG", 0), + OBSERVER("OBSERVER", 0), + OBSIDIAN("OBSIDIAN", 0), + OCELOT_SPAWN_EGG("RECORD_12", 0), + ORANGE_BANNER("BANNER", 14), + ORANGE_BED("BED", 1), + ORANGE_CARPET("CARPET", 1), + ORANGE_CONCRETE("CONCRETE", 1), + ORANGE_CONCRETE_POWDER("CONCRETE_POWDER", 1), + ORANGE_DYE("INK_SACK", 14), + ORANGE_GLAZED_TERRACOTTA("ORANGE_GLAZED_TERRACOTTA", 0), + ORANGE_SHULKER_BOX("ORANGE_SHULKER_BOX", 0), + ORANGE_STAINED_GLASS("STAINED_GLASS", 1), + ORANGE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 1), + ORANGE_TERRACOTTA("STAINED_CLAY", 1), + ORANGE_TULIP("RED_ROSE", 5), + ORANGE_WALL_BANNER("WALL_BANNER", 0), + ORANGE_WOOL("WOOL", 1), + OXEYE_DAISY("RED_ROSE", 8), + PACKED_ICE("PACKED_ICE", 0), + PAINTING("PAINTING", 0), + PAPER("PAPER", 0), + PARROT_SPAWN_EGG("MONSTER_EGG", 0), + PEONY("DOUBLE_PLANT", 5), + PETRIFIED_OAK_SLAB("STONE", 0), + PHANTOM_MEMBRANE("STONE", 0), + PHANTOM_SPAWN_EGG("MONSTER_EGG", 0), + PIG_SPAWN_EGG("MONSTER_EGG", 0), + PINK_BANNER("BANNER", 9), + PINK_BED("BED", 6), + PINK_CARPET("CARPET", 6), + PINK_CONCRETE("CONCRETE", 6), + PINK_CONCRETE_POWDER("CONCRETE_POWDER", 6), + PINK_DYE("INK_SACK", 9), + PINK_GLAZED_TERRACOTTA("PINK_GLAZED_TERRACOTTA", 0), + PINK_SHULKER_BOX("PINK_SHULKER_BOX", 0), + PINK_STAINED_GLASS("STAINED_GLASS", 6), + PINK_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 6), + PINK_TERRACOTTA("STAINED_CLAY", 6), + PINK_TULIP("RED_ROSE", 7), + PINK_WALL_BANNER("WALL_BANNER", 0), + PINK_WOOL("WOOL", 6), + PISTON("PISTON_BASE", 0), + PISTON_HEAD("PISTON_EXTENSION", 0), + PLAYER_HEAD("SKULL", 0), + PLAYER_WALL_HEAD("SKULL", 0), + PODZOL("DIRT", 2), + POISONOUS_POTATO("POISONOUS_POTATO", 0), + POLAR_BEAR_SPAWN_EGG("MONSTER_EGG", 0), + POLISHED_ANDESITE("STONE", 6), + POLISHED_DIORITE("STONE", 4), + POLISHED_GRANITE("STONE", 2), + POPPED_CHORUS_FRUIT("CHORUS_FRUIT_POPPED", 0), + POPPY("RED_ROSE", 0), + PORKCHOP("PORK", 0), + POTATO("POTATO_ITEM", 0), + POTATOES("POTATO", 0), + POTION("POTION", 0), + POTTED_ACACIA_SAPLING("FLOWER_POT", 0), + POTTED_ALLIUM("FLOWER_POT", 0), + POTTED_AZURE_BLUET("FLOWER_POT", 0), + POTTED_BIRCH_SAPLING("FLOWER_POT", 0), + POTTED_BLUE_ORCHID("FLOWER_POT", 0), + POTTED_BROWN_MUSHROOM("FLOWER_POT", 0), + POTTED_CACTUS("FLOWER_POT", 0), + POTTED_DANDELION("FLOWER_POT", 0), + POTTED_DARK_OAK_SAPLING("FLOWER_POT", 0), + POTTED_DEAD_BUSH("FLOWER_POT", 0), + POTTED_FERN("FLOWER_POT", 0), + POTTED_JUNGLE_SAPLING("FLOWER_POT", 0), + POTTED_OAK_SAPLING("FLOWER_POT", 0), + POTTED_ORANGE_TULIP("FLOWER_POT", 0), + POTTED_OXEYE_DAISY("FLOWER_POT", 0), + POTTED_PINK_TULIP("FLOWER_POT", 0), + POTTED_POPPY("FLOWER_POT", 0), + POTTED_RED_MUSHROOM("FLOWER_POT", 0), + POTTED_RED_TULIP("FLOWER_POT", 0), + POTTED_SPRUCE_SAPLING("FLOWER_POT", 0), + POTTED_WHITE_TULIP("FLOWER_POT", 0), + POWERED_RAIL("POWERED_RAIL", 0), + PRISMARINE("PRISMARINE", 0), + PRISMARINE_BRICKS("PRISMARINE", 1), + PRISMARINE_BRICK_SLAB("STONE", 0), + PRISMARINE_BRICK_STAIRS("STONE", 0), + PRISMARINE_CRYSTALS("PRISMARINE_CRYSTALS", 0), + PRISMARINE_SHARD("PRISMARINE_SHARD", 0), + PRISMARINE_SLAB("STONE", 0), + PRISMARINE_STAIRS("STONE", 0), + PUFFERFISH("RAW_FISH", 3), + PUFFERFISH_BUCKET("STONE", 0), + PUFFERFISH_SPAWN_EGG("MONSTER_EGG", 0), + PUMPKIN("PUMPKIN", 0), + PUMPKIN_PIE("PUMPKIN_PIE", 0), + PUMPKIN_SEEDS("PUMPKIN_SEEDS", 0), + PUMPKIN_STEM("PUMPKIN_STEM", 0), + PURPLE_BANNER("BANNER", 5), + PURPLE_BED("BED", 10), + PURPLE_CARPET("CARPET", 10), + PURPLE_CONCRETE("CONCRETE", 10), + PURPLE_CONCRETE_POWDER("CONCRETE_POWDER", 10), + PURPLE_DYE("INK_SACK", 5), + PURPLE_GLAZED_TERRACOTTA("PURPLE_GLAZED_TERRACOTTA", 0), + PURPLE_SHULKER_BOX("PURPLE_SHULKER_BOX", 0), + PURPLE_STAINED_GLASS("STAINED_GLASS", 10), + PURPLE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 10), + PURPLE_TERRACOTTA("STAINED_CLAY", 10), + PURPLE_WALL_BANNER("WALL_BANNER", 0), + PURPLE_WOOL("WOOL", 10), + PURPUR_BLOCK("PURPUR_BLOCK", 0), + PURPUR_PILLAR("PURPUR_PILLAR", 0), + PURPUR_SLAB("PURPUR_SLAB", 0), + PURPUR_STAIRS("PURPUR_STAIRS", 0), + QUARTZ("QUARTZ", 0), + QUARTZ_BLOCK("QUARTZ_BLOCK", 0), + QUARTZ_PILLAR("QUARTZ_BLOCK", 2), + QUARTZ_SLAB("STEP", 7), + QUARTZ_STAIRS("QUARTZ_STAIRS", 0), + RABBIT("RABBIT", 0), + RABBIT_FOOT("RABBIT_FOOT", 0), + RABBIT_HIDE("RABBIT_HIDE", 0), + RABBIT_SPAWN_EGG("MONSTER_EGG", 0), + RABBIT_STEW("RABBIT_STEW", 0), + RAIL("RAILS", 0), + REDSTONE("REDSTONE", 0), + REDSTONE_BLOCK("REDSTONE_BLOCK", 0), + REDSTONE_LAMP("REDSTONE_LAMP_OFF", 0), + REDSTONE_ORE("REDSTONE_ORE", 0), + REDSTONE_TORCH("REDSTONE_TORCH_ON", 0), + REDSTONE_WALL_TORCH("REDSTONE_TORCH_ON", 1), + REDSTONE_WIRE("REDSTONE_WIRE", 0), + RED_BANNER("BANNER", 1), + RED_BED("BED", 14), + RED_CARPET("CARPET", 14), + RED_CONCRETE("CONCRETE", 14), + RED_CONCRETE_POWDER("CONCRETE_POWDER", 14), + RED_GLAZED_TERRACOTTA("RED_GLAZED_TERRACOTTA", 0), + RED_MUSHROOM("RED_MUSHROOM", 0), + RED_MUSHROOM_BLOCK("RED_MUSHROOM", 0), + RED_NETHER_BRICKS("RED_NETHER_BRICK", 0), + RED_SAND("SAND", 1), + RED_SANDSTONE("RED_SANDSTONE", 0), + RED_SANDSTONE_SLAB("STONE_SLAB2", 0), + RED_SANDSTONE_STAIRS("RED_SANDSTONE_STAIRS", 0), + RED_SHULKER_BOX("RED_SHULKER_BOX", 0), + RED_STAINED_GLASS("STAINED_GLASS", 14), + RED_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 14), + RED_TERRACOTTA("STAINED_CLAY", 14), + RED_TULIP("RED_ROSE", 4), + RED_WALL_BANNER("WALL_BANNER", 0), + RED_WOOL("WOOL", 14), + REPEATER("DIODE", 0), + REPEATING_COMMAND_BLOCK("COMMAND_REPEATING", 0), + ROSE_BUSH("DOUBLE_PLANT", 4), + ROSE_RED("INK_SACK", 1), + ROTTEN_FLESH("ROTTEN_FLESH", 0), + SADDLE("SADDLE", 0), + SALMON("RAW_FISH", 1), + SALMON_BUCKET("BUCKET", 0), + SALMON_SPAWN_EGG("MONSTER_EGG", 0), + SAND("SAND", 0), + SANDSTONE("SANDSTONE", 0), + SANDSTONE_SLAB("STEP", 1), + SANDSTONE_STAIRS("SANDSTONE_STAIRS", 0), + SCUTE("STONE", 0), + SEAGRASS("STONE", 0), + SEA_LANTERN("SEA_LANTERN", 0), + SEA_PICKLE("STONE", 0), + SHEARS("SHEARS", 0), + SHEEP_SPAWN_EGG("MONSTER_EGG", 0), + SHIELD("SHIELD", 0), + SHULKER_BOX("PURPLE_SHULKER_BOX", 0), + SHULKER_SHELL("SHULKER_SHELL", 0), + SHULKER_SPAWN_EGG("MONSTER_EGG", 0), + SIGN("SIGN", 0), + SILVERFISH_SPAWN_EGG("MONSTER_EGG", 0), + SKELETON_HORSE_SPAWN_EGG("MONSTER_EGG", 0), + SKELETON_SKULL("SKULL", 0), + SKELETON_SPAWN_EGG("MONSTER_EGG", 0), + SKELETON_WALL_SKULL("SKULL", 0), + SLIME_BALL("SLIME_BALL", 0), + SLIME_BLOCK("SLIME_BLOCK", 0), + SLIME_SPAWN_EGG("MONSTER_EGG", 0), + SMOOTH_QUARTZ("STONE", 0), + SMOOTH_RED_SANDSTONE("RED_SANDSTONE", 2), + SMOOTH_SANDSTONE("SANDSTONE", 2), + SMOOTH_STONE("STEP", 0), + SNOW("SNOW", 0), + SNOWBALL("SNOW_BALL", 0), + SNOW_BLOCK("SNOW_BLOCK", 0), + SOUL_SAND("SOUL_SAND", 0), + SPAWNER("MOB_SPAWNER", 0), + SPECTRAL_ARROW("SPECTRAL_ARROW", 0), + SPIDER_EYE("SPIDER_EYE", 0), + SPIDER_SPAWN_EGG("MONSTER_EGG", 0), + SPLASH_POTION("SPLASH_POTION", 0), + SPONGE("SPONGE", 0), + SPRUCE_BOAT("BOAT_SPRUCE", 0), + SPRUCE_BUTTON("WOOD_BUTTON", 0), + SPRUCE_DOOR("SPRUCE_DOOR", 0), + SPRUCE_FENCE("SPRUCE_FENCE", 0), + SPRUCE_FENCE_GATE("SPRUCE_FENCE_GATE", 0), + SPRUCE_LEAVES("LEAVES", 1), + SPRUCE_LOG("LOG", 1), + SPRUCE_PLANKS("WOOD", 1), + SPRUCE_PRESSURE_PLATE("WOOD_PLATE", 0), + SPRUCE_SAPLING("SAPLING", 1), + SPRUCE_SLAB("WOOD_STEP", 1), + SPRUCE_STAIRS("SPRUCE_WOOD_STAIRS", 0), + SPRUCE_TRAPDOOR("TRAP_DOOR", 0), + SPRUCE_WOOD("LOG", 1), + SQUID_SPAWN_EGG("MONSTER_EGG", 0), + STICK("STICK", 0), + STICKY_PISTON("PISTON_STICKY_BASE", 0), + STONE("STONE", 0), + STONE_AXE("STONE_AXE", 0), + STONE_BRICKS("SMOOTH_BRICK", 0), + STONE_BRICK_SLAB("STEP", 5), + STONE_BRICK_STAIRS("SMOOTH_STAIRS", 0), + STONE_BUTTON("STONE_BUTTON", 0), + STONE_HOE("STONE_HOE", 0), + STONE_PICKAXE("STONE_PICKAXE", 0), + STONE_PRESSURE_PLATE("STONE_PLATE", 0), + STONE_SHOVEL("STONE_SPADE", 0), + STONE_SLAB("STEP", 0), + STONE_SWORD("STONE_SWORD", 0), + STRAY_SPAWN_EGG("MONSTER_EGG", 0), + STRING("STRING", 0), + STRIPPED_ACACIA_LOG("STONE", 0), + STRIPPED_ACACIA_WOOD("STONE", 0), + STRIPPED_BIRCH_LOG("STONE", 0), + STRIPPED_BIRCH_WOOD("STONE", 0), + STRIPPED_DARK_OAK_LOG("STONE", 0), + STRIPPED_DARK_OAK_WOOD("STONE", 0), + STRIPPED_JUNGLE_LOG("STONE", 0), + STRIPPED_JUNGLE_WOOD("STONE", 0), + STRIPPED_OAK_LOG("STONE", 0), + STRIPPED_OAK_WOOD("STONE", 0), + STRIPPED_SPRUCE_LOG("STONE", 0), + STRIPPED_SPRUCE_WOOD("STONE", 0), + STRUCTURE_BLOCK("STRUCTURE_BLOCK", 0), + STRUCTURE_VOID("STRUCTURE_VOID", 0), + SUGAR("SUGAR", 0), + SUGAR_CANE("SUGAR_CANE", 0), + SUNFLOWER("DOUBLE_PLANT", 0), + TALL_GRASS("DOUBLE_PLANT", 2), + TALL_SEAGRASS("STONE", 0), + TERRACOTTA("HARD_CLAY", 0), + TIPPED_ARROW("TIPPED_ARROW", 0), + TNT("TNT", 0), + TNT_MINECART("EXPLOSIVE_MINECART", 0), + TORCH("TORCH", 0), + TOTEM_OF_UNDYING("TOTEM", 0), + TRAPPED_CHEST("TRAPPED_CHEST", 0), + TRIDENT("STONE", 0), + TRIPWIRE("TRIPWIRE", 0), + TRIPWIRE_HOOK("TRIPWIRE_HOOK", 0), + TROPICAL_FISH("RAW_FISH", 0), + TROPICAL_FISH_BUCKET("BUCKET", 0), + TROPICAL_FISH_SPAWN_EGG("MONSTER_EGG", 0), + TUBE_CORAL("STONE", 0), + TUBE_CORAL_BLOCK("STONE", 0), + TUBE_CORAL_FAN("STONE", 0), + TURTLE_EGG("MONSTER_EGG", 0), + TURTLE_HELMET("STONE", 0), + TURTLE_SPAWN_EGG("MONSTER_EGG", 0), + VEX_SPAWN_EGG("MONSTER_EGG", 0), + VILLAGER_SPAWN_EGG("MONSTER_EGG", 0), + VINDICATOR_SPAWN_EGG("MONSTER_EGG", 0), + VINE("VINE", 0), + VOID_AIR("AIR", 0), + WALL_SIGN("WALL_SIGN", 0), + WALL_TORCH("TORCH", 1), + WATER("WATER", 0), + WATER_BUCKET("WATER_BUCKET", 0), + WET_SPONGE("SPONGE", 1), + WHEAT("WHEAT", 0), + WHEAT_SEEDS("SEEDS", 0), + WHITE_BANNER("BANNER", 15), + WHITE_BED("BED", 0), + WHITE_CARPET("CARPET", 0), + WHITE_CONCRETE("CONCRETE", 0), + WHITE_CONCRETE_POWDER("CONCRETE_POWDER", 0), + WHITE_GLAZED_TERRACOTTA("WHITE_GLAZED_TERRACOTTA", 0), + WHITE_SHULKER_BOX("WHITE_SHULKER_BOX", 0), + WHITE_STAINED_GLASS("STAINED_GLASS", 0), + WHITE_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 0), + WHITE_TERRACOTTA("TERRACOTTA", 0), + WHITE_TULIP("RED_ROSE", 6), + WHITE_WALL_BANNER("WALL_BANNER", 0), + WHITE_WOOL("WOOL", 0), + WITCH_SPAWN_EGG("MONSTER_EGG", 0), + WITHER_SKELETON_SKULL("SKULL", 0), + WITHER_SKELETON_SPAWN_EGG("MONSTER_EGG", 0), + WITHER_SKELETON_WALL_SKULL("SKULL", 0), + WOLF_SPAWN_EGG("MONSTER_EGG", 0), + WOODEN_AXE("WOOD_AXE", 0), + WOODEN_HOE("WOOD_HOE", 0), + WOODEN_PICKAXE("WOOD_PICKAXE", 0), + WOODEN_SHOVEL("WOOD_SPADE", 0), + WOODEN_SWORD("WOOD_SWORD", 0), + WRITABLE_BOOK("BOOK_AND_QUILL", 0), + WRITTEN_BOOK("WRITTEN_BOOK", 0), + YELLOW_BANNER("BANNER", 11), + YELLOW_BED("BED", 4), + YELLOW_CARPET("CARPET", 4), + YELLOW_CONCRETE("CONCRETE", 4), + YELLOW_CONCRETE_POWDER("CONCRETE_POWDER", 4), + YELLOW_GLAZED_TERRACOTTA("YELLOW_GLAZED_TERRACOTTA", 0), + YELLOW_SHULKER_BOX("YELLOW_SHULKER_BOX", 0), + YELLOW_STAINED_GLASS("STAINED_GLASS", 4), + YELLOW_STAINED_GLASS_PANE("STAINED_GLASS_PANE", 4), + YELLOW_TERRACOTTA("STAINED_CLAY", 4), + YELLOW_WALL_BANNER("WALL_BANNER", 0), + YELLOW_WOOL("WOOL", 4), + ZOMBIE_HEAD("SKULL", 0), + ZOMBIE_HORSE_SPAWN_EGG("MONSTER_EGG", 0), + ZOMBIE_PIGMAN_SPAWN_EGG("MONSTER_EGG", 0), + ZOMBIE_SPAWN_EGG("MONSTER_EGG", 0), + ZOMBIE_VILLAGER_SPAWN_EGG("MONSTER_EGG", 0), + ZOMBIE_WALL_HEAD("SKULL", 0), + ; - static int newV = -1; - private static HashMap cachedSearch = new HashMap<>(); - String m; - int data; + static int newV = -1; + private static HashMap cachedSearch = new HashMap<>(); + String m; + int data; - MultiversionMaterials(String m, int data) { - this.m = m; - this.data = data; - } + MultiversionMaterials(String m, int data) { + this.m = m; + this.data = data; + } - public static boolean isNewVersion() { - if (newV == 0) return false; - if (newV == 1) return true; + public static boolean isNewVersion() { + if (newV == 0) return false; + if (newV == 1) return true; - Material mat = Material.matchMaterial("RED_WOOL"); - if (mat != null) { - newV = 1; - return true; - } + Material mat = Material.matchMaterial("RED_WOOL"); + if (mat != null) { + newV = 1; + return true; + } - newV = 0; - return false; - } + newV = 0; + return false; + } - public static MultiversionMaterials requestXMaterial(String name, byte data) { - if (cachedSearch.containsKey(name.toUpperCase() + "," + data)) { - return cachedSearch.get(name.toUpperCase() + "," + data); - } - for (MultiversionMaterials mat : MultiversionMaterials.values()) { - if (name.toUpperCase().equals(mat.m) && ((byte) mat.data) == data) { - cachedSearch.put(mat.m + "," + data, mat); - return mat; - } - } - return null; - } + public static MultiversionMaterials requestXMaterial(String name, byte data) { + if (cachedSearch.containsKey(name.toUpperCase() + "," + data)) { + return cachedSearch.get(name.toUpperCase() + "," + data); + } + for (MultiversionMaterials mat : MultiversionMaterials.values()) { + if (name.toUpperCase().equals(mat.m) && ((byte) mat.data) == data) { + cachedSearch.put(mat.m + "," + data, mat); + return mat; + } + } + return null; + } - public static MultiversionMaterials fromString(String key) { - try { - return MultiversionMaterials.valueOf(key); - } catch (IllegalArgumentException e) { - String[] split = key.split(":"); + public static MultiversionMaterials fromString(String key) { + try { + return MultiversionMaterials.valueOf(key); + } catch (IllegalArgumentException e) { + String[] split = key.split(":"); - return split.length == 1 ? requestXMaterial(key, (byte) 0) : requestXMaterial(split[0], (byte) Integer.parseInt(split[1])); - } - } + return split.length == 1 ? requestXMaterial(key, (byte) 0) : requestXMaterial(split[0], (byte) Integer.parseInt(split[1])); + } + } - public ItemStack parseItem() { - Material mat = parseMaterial(); - if (isNewVersion()) { - return new ItemStack(mat); - } - return new ItemStack(mat, 1, (byte) data); - } + public ItemStack parseItem() { + Material mat = parseMaterial(); + if (isNewVersion()) { + return new ItemStack(mat); + } + return new ItemStack(mat, 1, (byte) data); + } - public boolean isSameMaterial(ItemStack comp) { - if (isNewVersion()) { - return comp.getType() == this.parseMaterial(); - } - if (comp.getType() == this.parseMaterial() && - (int) comp.getData().getData() == this.data) { - return true; - } - MultiversionMaterials xmat = fromMaterial(comp.getType()); - if (isDamageable(xmat)) { - return this.parseMaterial() == comp.getType(); - } - return false; - } + public boolean isSameMaterial(ItemStack comp) { + if (isNewVersion()) { + return comp.getType() == this.parseMaterial(); + } + if (comp.getType() == this.parseMaterial() && + (int) comp.getData().getData() == this.data) { + return true; + } + MultiversionMaterials xmat = fromMaterial(comp.getType()); + if (isDamageable(xmat)) { + return this.parseMaterial() == comp.getType(); + } + return false; + } - public MultiversionMaterials fromMaterial(Material mat) { - try { - return MultiversionMaterials.valueOf(mat.toString()); - } catch (IllegalArgumentException e) { - for (MultiversionMaterials xmat : MultiversionMaterials.values()) { - if (xmat.m.equals(mat.toString())) { - return xmat; - } - } - } - return null; - } + public MultiversionMaterials fromMaterial(Material mat) { + try { + return MultiversionMaterials.valueOf(mat.toString()); + } catch (IllegalArgumentException e) { + for (MultiversionMaterials xmat : MultiversionMaterials.values()) { + if (xmat.m.equals(mat.toString())) { + return xmat; + } + } + } + return null; + } - public boolean isDamageable(MultiversionMaterials type) { - String[] split = type.toString().split("_"); + public boolean isDamageable(MultiversionMaterials type) { + String[] split = type.toString().split("_"); - switch (split[split.length - 1]) { - case "HELMET": - case "CHESTPLATE": - case "LEGGINGS": - case "BOOTS": - case "SWORD": - case "AXE": - case "PICKAXE": - case "SHOVEL": - case "HOE": - case "ELYTRA": - case "TURTLE_HELMET": - case "TRIDENT": - case "HORSE_ARMOR": - case "SHEARS": - return true; - default: - return false; - } - } + switch (split[split.length - 1]) { + case "HELMET": + case "CHESTPLATE": + case "LEGGINGS": + case "BOOTS": + case "SWORD": + case "AXE": + case "PICKAXE": + case "SHOVEL": + case "HOE": + case "ELYTRA": + case "TURTLE_HELMET": + case "TRIDENT": + case "HORSE_ARMOR": + case "SHEARS": + return true; + default: + return false; + } + } - public Material parseMaterial() { - Material mat = Material.matchMaterial(this.toString()); - return mat != null ? mat : Material.matchMaterial(m); - } + public Material parseMaterial() { + Material mat = Material.matchMaterial(this.toString()); + return mat != null ? mat : Material.matchMaterial(m); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java index 72f5376d..d689c6f0 100644 --- a/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/MyLocationTypeAdapter.java @@ -9,51 +9,51 @@ import java.util.logging.Level; public class MyLocationTypeAdapter implements JsonDeserializer, JsonSerializer { - private static final String WORLD = "world"; - private static final String X = "x"; - private static final String Y = "y"; - private static final String Z = "z"; - private static final String YAW = "yaw"; - private static final String PITCH = "pitch"; + private static final String WORLD = "world"; + private static final String X = "x"; + private static final String Y = "y"; + private static final String Z = "z"; + private static final String YAW = "yaw"; + private static final String PITCH = "pitch"; - @Override - public LazyLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { - try { - JsonObject obj = json.getAsJsonObject(); + @Override + public LazyLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + try { + JsonObject obj = json.getAsJsonObject(); - String worldName = obj.get(WORLD).getAsString(); - double x = obj.get(X).getAsDouble(); - double y = obj.get(Y).getAsDouble(); - double z = obj.get(Z).getAsDouble(); - float yaw = obj.get(YAW).getAsFloat(); - float pitch = obj.get(PITCH).getAsFloat(); + String worldName = obj.get(WORLD).getAsString(); + double x = obj.get(X).getAsDouble(); + double y = obj.get(Y).getAsDouble(); + double z = obj.get(Z).getAsDouble(); + float yaw = obj.get(YAW).getAsFloat(); + float pitch = obj.get(PITCH).getAsFloat(); - return new LazyLocation(worldName, x, y, z, yaw, pitch); + return new LazyLocation(worldName, x, y, z, yaw, pitch); - } catch (Exception ex) { - ex.printStackTrace(); - SavageFactions.plugin.log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); - return null; - } - } + } catch (Exception ex) { + ex.printStackTrace(); + SavageFactions.plugin.log(Level.WARNING, "Error encountered while deserializing a LazyLocation."); + return null; + } + } - @Override - public JsonElement serialize(LazyLocation src, Type typeOfSrc, JsonSerializationContext context) { - JsonObject obj = new JsonObject(); + @Override + public JsonElement serialize(LazyLocation src, Type typeOfSrc, JsonSerializationContext context) { + JsonObject obj = new JsonObject(); - try { - obj.addProperty(WORLD, src.getWorldName()); - obj.addProperty(X, src.getX()); - obj.addProperty(Y, src.getY()); - obj.addProperty(Z, src.getZ()); - obj.addProperty(YAW, src.getYaw()); - obj.addProperty(PITCH, src.getPitch()); + try { + obj.addProperty(WORLD, src.getWorldName()); + obj.addProperty(X, src.getX()); + obj.addProperty(Y, src.getY()); + obj.addProperty(Z, src.getZ()); + obj.addProperty(YAW, src.getYaw()); + obj.addProperty(PITCH, src.getPitch()); - return obj; - } catch (Exception ex) { - ex.printStackTrace(); - SavageFactions.plugin.log(Level.WARNING, "Error encountered while serializing a LazyLocation."); - return obj; - } - } + return obj; + } catch (Exception ex) { + ex.printStackTrace(); + SavageFactions.plugin.log(Level.WARNING, "Error encountered while serializing a LazyLocation."); + return obj; + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/Particles/ParticleEffect.java b/src/main/java/com/massivecraft/factions/util/Particles/ParticleEffect.java index ab152c08..cf4ff3b7 100644 --- a/src/main/java/com/massivecraft/factions/util/Particles/ParticleEffect.java +++ b/src/main/java/com/massivecraft/factions/util/Particles/ParticleEffect.java @@ -40,1559 +40,1559 @@ import java.util.Map.Entry; * @version 1.7 */ public enum ParticleEffect { - /** - * A particle effect which is displayed by exploding tnt and creepers: - *
    - *
  • It looks like a white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - EXPLOSION_NORMAL("explode", 0, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by exploding ghast fireballs and wither skulls: - *
    - *
  • It looks like a gray ball which is fading away - *
  • The speed value slightly influences the size of this particle effect - *
- */ - EXPLOSION_LARGE("largeexplode", 1, -1), - /** - * A particle effect which is displayed by exploding tnt and creepers: - *
    - *
  • It looks like a crowd of gray balls which are fading away - *
  • The speed value has no influence on this particle effect - *
- */ - EXPLOSION_HUGE("hugeexplosion", 2, -1), - /** - * A particle effect which is displayed by launching fireworks: - *
    - *
  • It looks like a white star which is sparkling - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - FIREWORKS_SPARK("fireworksSpark", 3, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by swimming entities and arrows in water: - *
    - *
  • It looks like a bubble - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - WATER_BUBBLE("bubble", 4, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_WATER), - /** - * A particle effect which is displayed by swimming entities and shaking wolves: - *
    - *
  • It looks like a blue drop - *
  • The speed value has no influence on this particle effect - *
- */ - WATER_SPLASH("splash", 5, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed on water when fishing: - *
    - *
  • It looks like a blue droplet - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - WATER_WAKE("wake", 6, 7, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by water: - *
    - *
  • It looks like a tiny blue square - *
  • The speed value has no influence on this particle effect - *
- */ - SUSPENDED("suspended", 7, -1, ParticleProperty.REQUIRES_WATER), - /** - * A particle effect which is displayed by air when close to bedrock and the in the void: - *
    - *
  • It looks like a tiny gray square - *
  • The speed value has no influence on this particle effect - *
- */ - SUSPENDED_DEPTH("depthSuspend", 8, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when landing a critical hit and by arrows: - *
    - *
  • It looks like a light brown cross - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CRIT("crit", 9, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when landing a hit with an enchanted weapon: - *
    - *
  • It looks like a cyan star - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CRIT_MAGIC("magicCrit", 10, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by primed tnt, torches, droppers, dispensers, end portals, brewing stands and monster spawners: - *
    - *
  • It looks like a little gray cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SMOKE_NORMAL("smoke", 11, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by fire, minecarts with furnace and blazes: - *
    - *
  • It looks like a large gray cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SMOKE_LARGE("largesmoke", 12, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed when splash potions or bottles o' enchanting hit something: - *
    - *
  • It looks like a white swirl - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL("spell", 13, -1), - /** - * A particle effect which is displayed when instant splash potions hit something: - *
    - *
  • It looks like a white cross - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL_INSTANT("instantSpell", 14, -1), - /** - * A particle effect which is displayed by entities with active potion effects: - *
    - *
  • It looks like a colored swirl - *
  • The speed value causes the particle to be colored black when set to 0 - *
  • The particle color gets lighter when increasing the speed and darker when decreasing the speed - *
- */ - SPELL_MOB("mobSpell", 15, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by entities with active potion effects applied through a beacon: - *
    - *
  • It looks like a transparent colored swirl - *
  • The speed value causes the particle to be always colored black when set to 0 - *
  • The particle color gets lighter when increasing the speed and darker when decreasing the speed - *
- */ - SPELL_MOB_AMBIENT("mobSpellAmbient", 16, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by witches: - *
    - *
  • It looks like a purple cross - *
  • The speed value causes the particle to only move upwards when set to 0 - *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 - *
- */ - SPELL_WITCH("witchMagic", 17, -1), - /** - * A particle effect which is displayed by blocks beneath a water source: - *
    - *
  • It looks like a blue drip - *
  • The speed value has no influence on this particle effect - *
- */ - DRIP_WATER("dripWater", 18, -1), - /** - * A particle effect which is displayed by blocks beneath a lava source: - *
    - *
  • It looks like an orange drip - *
  • The speed value has no influence on this particle effect - *
- */ - DRIP_LAVA("dripLava", 19, -1), - /** - * A particle effect which is displayed when attacking a villager in a village: - *
    - *
  • It looks like a cracked gray heart - *
  • The speed value has no influence on this particle effect - *
- */ - VILLAGER_ANGRY("angryVillager", 20, -1), - /** - * A particle effect which is displayed when using bone meal and trading with a villager in a village: - *
    - *
  • It looks like a green star - *
  • The speed value has no influence on this particle effect - *
- */ - VILLAGER_HAPPY("happyVillager", 21, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by mycelium: - *
    - *
  • It looks like a tiny gray square - *
  • The speed value has no influence on this particle effect - *
- */ - TOWN_AURA("townaura", 22, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by note blocks: - *
    - *
  • It looks like a colored note - *
  • The speed value causes the particle to be colored green when set to 0 - *
- */ - NOTE("note", 23, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed by nether portals, endermen, ender pearls, eyes of ender, ender chests and dragon eggs: - *
    - *
  • It looks like a purple cloud - *
  • The speed value influences the spread of this particle effect - *
- */ - PORTAL("portal", 24, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by enchantment tables which are nearby bookshelves: - *
    - *
  • It looks like a cryptic white letter - *
  • The speed value influences the spread of this particle effect - *
- */ - ENCHANTMENT_TABLE("enchantmenttable", 25, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by torches, active furnaces, magma cubes and monster spawners: - *
    - *
  • It looks like a tiny flame - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - FLAME("flame", 26, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by lava: - *
    - *
  • It looks like a spark - *
  • The speed value has no influence on this particle effect - *
- */ - LAVA("lava", 27, -1), - /** - * A particle effect which is currently unused: - *
    - *
  • It looks like a transparent gray square - *
  • The speed value has no influence on this particle effect - *
- */ - FOOTSTEP("footstep", 28, -1), - /** - * A particle effect which is displayed when a mob dies: - *
    - *
  • It looks like a large white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - CLOUD("cloud", 29, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by redstone ore, powered redstone, redstone torches and redstone repeaters: - *
    - *
  • It looks like a tiny colored cloud - *
  • The speed value causes the particle to be colored red when set to 0 - *
- */ - REDSTONE("reddust", 30, -1, ParticleProperty.COLORABLE), - /** - * A particle effect which is displayed when snowballs hit a block: - *
    - *
  • It looks like a little piece with the snowball texture - *
  • The speed value has no influence on this particle effect - *
- */ - SNOWBALL("snowballpoof", 31, -1), - /** - * A particle effect which is currently unused: - *
    - *
  • It looks like a tiny white cloud - *
  • The speed value influences the velocity at which the particle flies off - *
- */ - SNOW_SHOVEL("snowshovel", 32, -1, ParticleProperty.DIRECTIONAL), - /** - * A particle effect which is displayed by slimes: - *
    - *
  • It looks like a tiny part of the slimeball icon - *
  • The speed value has no influence on this particle effect - *
- */ - SLIME("slime", 33, -1), - /** - * A particle effect which is displayed when breeding and taming animals: - *
    - *
  • It looks like a red heart - *
  • The speed value has no influence on this particle effect - *
- */ - HEART("heart", 34, -1), - /** - * A particle effect which is displayed by barriers: - *
    - *
  • It looks like a red box with a slash through it - *
  • The speed value has no influence on this particle effect - *
- */ - BARRIER("barrier", 35, 8), - /** - * A particle effect which is displayed when breaking a tool or eggs hit a block: - *
    - *
  • It looks like a little piece with an item texture - *
- */ - ITEM_CRACK("iconcrack", 36, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when breaking blocks or sprinting: - *
    - *
  • It looks like a little piece with a block texture - *
  • The speed value has no influence on this particle effect - *
- */ - BLOCK_CRACK("blockcrack", 37, -1, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when falling: - *
    - *
  • It looks like a little piece with a block texture - *
- */ - BLOCK_DUST("blockdust", 38, 7, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), - /** - * A particle effect which is displayed when rain hits the ground: - *
    - *
  • It looks like a blue droplet - *
  • The speed value has no influence on this particle effect - *
- */ - WATER_DROP("droplet", 39, 8), - /** - * A particle effect which is currently unused: - *
    - *
  • It has no visual effect - *
- */ - ITEM_TAKE("take", 40, 8), - /** - * A particle effect which is displayed by elder guardians: - *
    - *
  • It looks like the shape of the elder guardian - *
  • The speed value has no influence on this particle effect - *
  • The offset values have no influence on this particle effect - *
- */ - MOB_APPEARANCE("mobappearance", 41, 8); - - private static final Map NAME_MAP = new HashMap(); - private static final Map ID_MAP = new HashMap(); - - // Initialize map for quick name and id lookup - static { - for (ParticleEffect effect : values()) { - NAME_MAP.put(effect.name, effect); - ID_MAP.put(effect.id, effect); - } - } - - private final String name; - private final int id; - private final int requiredVersion; - private final List properties; - - /** - * Construct a new particle effect - * - * @param name Name of this particle effect - * @param id Id of this particle effect - * @param requiredVersion Version which is required (1.x) - * @param properties Properties of this particle effect - */ - ParticleEffect(String name, int id, int requiredVersion, ParticleProperty... properties) { - this.name = name; - this.id = id; - this.requiredVersion = requiredVersion; - this.properties = Arrays.asList(properties); - } - - /** - * Returns the particle effect with the given name - * - * @param name Name of the particle effect - * @return The particle effect - */ - public static ParticleEffect fromName(String name) { - for (Entry entry : NAME_MAP.entrySet()) { - if (!entry.getKey().equalsIgnoreCase(name)) { - continue; - } - return entry.getValue(); - } - return null; - } - - /** - * Returns the particle effect with the given id - * - * @param id Id of the particle effect - * @return The particle effect - */ - public static ParticleEffect fromId(int id) { - for (Entry entry : ID_MAP.entrySet()) { - if (entry.getKey() != id) { - continue; - } - return entry.getValue(); - } - return null; - } - - /** - * Determine if water is at a certain location - * - * @param location Location to check - * @return Whether water is at this location or not - */ - private static boolean isWater(Location location) { - Material material = location.getBlock().getType(); - return material == Material.WATER || material == SavageFactions.plugin.STATIONARY_WATER; - } - - /** - * Determine if the distance between @param location and one of the players exceeds 256 - * - * @param location Location to check - * @return Whether the distance exceeds 256 or not - */ - private static boolean isLongDistance(Location location, List players) { - String world = location.getWorld().getName(); - for (Player player : players) { - Location playerLocation = player.getLocation(); - if (!world.equals(playerLocation.getWorld().getName()) || playerLocation.distanceSquared(location) < 65536) { - continue; - } - return true; - } - return false; - } - - /** - * Determine if the data type for a particle effect is correct - * - * @param effect Particle effect - * @param data Particle data - * @return Whether the data type is correct or not - */ - private static boolean isDataCorrect(ParticleEffect effect, ParticleData data) { - return ((effect == BLOCK_CRACK || effect == BLOCK_DUST) && data instanceof BlockData) || (effect == ITEM_CRACK && data instanceof ItemData); - } - - /** - * Determine if the color type for a particle effect is correct - * - * @param effect Particle effect - * @param color Particle color - * @return Whether the color type is correct or not - */ - private static boolean isColorCorrect(ParticleEffect effect, ParticleColor color) { - return ((effect == SPELL_MOB || effect == SPELL_MOB_AMBIENT || effect == REDSTONE) && color instanceof OrdinaryColor) || (effect == NOTE && color instanceof NoteColor); - } - - /** - * Returns the name of this particle effect - * - * @return The name - */ - public String getName() { - return name; - } - - /** - * Returns the id of this particle effect - * - * @return The id - */ - public int getId() { - return id; - } - - /** - * Returns the required version for this particle effect (1.x) - * - * @return The required version - */ - public int getRequiredVersion() { - return requiredVersion; - } - - /** - * Determine if this particle effect has a specific property - * - * @param property - property to check. - * @return Whether it has the property or not - */ - public boolean hasProperty(ParticleProperty property) { - return properties.contains(property); - } - - /** - * Determine if this particle effect is supported by your current server version - * - * @return Whether the particle effect is supported or not - */ - public boolean isSupported() { - if (requiredVersion == -1) { - return true; - } - return ParticlePacket.getVersion() >= requiredVersion; - } - - /** - * Displays a particle effect which is only visible for all players within a certain range in the world of @param center - * - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect requires water and none is at the center location - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, null).sendTo(center, range); - } - - /** - * Displays a particle effect which is only visible for the specified players - * - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect requires water and none is at the center location - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players); - } - - /** - * Displays a particle effect which is only visible for the specified players - * - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect requires water and none is at the center location - * @see #display(float, float, float, float, int, Location, List) - */ - public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - display(offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which flies into a determined direction and is only visible for all players within a certain range in the world of @param center - * - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location - * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, ParticleData) - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (!hasProperty(ParticleProperty.DIRECTIONAL)) { - throw new IllegalArgumentException("This particle effect is not directional"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, direction, speed, range > 256, null).sendTo(center, range); - } - - /** - * Displays a single particle which flies into a determined direction and is only visible for the specified players - * - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location - * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, ParticleData) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect requires additional data"); - } - if (!hasProperty(ParticleProperty.DIRECTIONAL)) { - throw new IllegalArgumentException("This particle effect is not directional"); - } - if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { - throw new IllegalArgumentException("There is no water at the center location"); - } - new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players); - } - - /** - * Displays a single particle which flies into a determined direction and is only visible for the specified players - * - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect requires additional data - * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location - * @see #display(Vector, float, Location, List) - */ - public void display(Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { - display(direction, speed, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which is colored and only visible for all players within a certain range in the world of @param center - * - * @param color Color of the particle - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleColor color, Location center, double range) throws ParticleVersionException, ParticleColorException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.COLORABLE)) { - throw new ParticleColorException("This particle effect is not colorable"); - } - if (!isColorCorrect(this, color)) { - throw new ParticleColorException("The particle color type is incorrect"); - } - new ParticlePacket(this, color, range > 256).sendTo(center, range); - } - - /** - * Displays a single particle which is colored and only visible for the specified players - * - * @param color Color of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleColor color, Location center, List players) throws ParticleVersionException, ParticleColorException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.COLORABLE)) { - throw new ParticleColorException("This particle effect is not colorable"); - } - if (!isColorCorrect(this, color)) { - throw new ParticleColorException("The particle color type is incorrect"); - } - new ParticlePacket(this, color, isLongDistance(center, players)).sendTo(center, players); - } - - /** - * Displays a single particle which is colored and only visible for the specified players - * - * @param color Color of the particle - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect - * @see #display(ParticleColor, Location, List) - */ - public void display(ParticleColor color, Location center, Player... players) throws ParticleVersionException, ParticleColorException { - display(color, center, Arrays.asList(players)); - } - - /** - * Displays a particle effect which requires additional data and is only visible for all players within a certain range in the world of @param center - * - * @param data Data of the effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); - } - - /** - * Displays a particle effect which requires additional data and is only visible for the specified players - * - * @param data Data of the effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players); - } - - /** - * Displays a particle effect which requires additional data and is only visible for the specified players - * - * @param data Data of the effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see #display(ParticleData, float, float, float, float, int, Location, List) - */ - public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException { - display(data, offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); - } - - /** - * Displays a single particle which requires additional data that flies into a determined direction and is only visible for all players within a certain range in the world of @param center - * - * @param data Data of the effect - * @param direction Direction of the particle - * @param speed Display speed of the particles - * @param center Center location of the effect - * @param range Range of the visibility - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, double) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, direction, speed, range > 256, data).sendTo(center, range); - } - - /** - * Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players - * - * @param data Data of the effect - * @param direction Direction of the particle - * @param speed Display speed of the particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see ParticlePacket - * @see ParticlePacket#sendTo(Location, List) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException { - if (!isSupported()) { - throw new ParticleVersionException("This particle effect is not supported by your server version"); - } - if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { - throw new ParticleDataException("This particle effect does not require additional data"); - } - if (!isDataCorrect(this, data)) { - throw new ParticleDataException("The particle data type is incorrect"); - } - new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players); - } - - /** - * Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players - * - * @param data Data of the effect - * @param direction Direction of the particle - * @param speed Display speed of the particles - * @param center Center location of the effect - * @param players Receivers of the effect - * @throws ParticleVersionException If the particle effect is not supported by the server version - * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect - * @see #display(ParticleData, Vector, float, Location, List) - */ - public void display(ParticleData data, Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException { - display(data, direction, speed, center, Arrays.asList(players)); - } - - /** - * Represents the property of a particle effect - * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public enum ParticleProperty { - /** - * The particle effect requires water to be displayed - */ - REQUIRES_WATER, - /** - * The particle effect requires block or item data to be displayed - */ - REQUIRES_DATA, - /** - * The particle effect uses the offsets as direction values - */ - DIRECTIONAL, - /** - * The particle effect uses the offsets as color values - */ - COLORABLE - } - - /** - * Represents the particle data for effects like {@link ParticleEffect#ITEM_CRACK}, {@link ParticleEffect#BLOCK_CRACK} and {@link ParticleEffect#BLOCK_DUST} - * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static abstract class ParticleData { - private final Material material; - private final byte data; - private final int[] packetData; - - /** - * Construct a new particle data - * - * @param material Material of the item/block - * @param data Data value of the item/block - */ - @SuppressWarnings("deprecation") - public ParticleData(Material material, byte data) { - this.material = material; - this.data = data; - this.packetData = new int[]{material.getId(), data}; - } - - /** - * Returns the material of this data - * - * @return The material - */ - public Material getMaterial() { - return material; - } - - /** - * Returns the data value of this data - * - * @return The data value - */ - public byte getData() { - return data; - } - - /** - * Returns the data as an int array for packet construction - * - * @return The data for the packet - */ - public int[] getPacketData() { - return packetData; - } - - /** - * Returns the data as a string for pre 1.8 versions - * - * @return The data string for the packet - */ - public String getPacketDataString() { - return "_" + packetData[0] + "_" + packetData[1]; - } - } - - /** - * Represents the item data for the {@link ParticleEffect#ITEM_CRACK} effect - * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static final class ItemData extends ParticleData { - /** - * Construct a new item data - * - * @param material Material of the item - * @param data Data value of the item - * @see ParticleData#ParticleData(Material, byte) - */ - public ItemData(Material material, byte data) { - super(material, data); - } - } - - /** - * Represents the block data for the {@link ParticleEffect#BLOCK_CRACK} and {@link ParticleEffect#BLOCK_DUST} effects - * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - public static final class BlockData extends ParticleData { - /** - * Construct a new block data - * - * @param material Material of the block - * @param data Data value of the block - * @throws IllegalArgumentException If the material is not a block - * @see ParticleData#ParticleData(Material, byte) - */ - public BlockData(Material material, byte data) throws IllegalArgumentException { - super(material, data); - if (!material.isBlock()) { - throw new IllegalArgumentException("The material is not a block"); - } - } - } - - /** - * Represents the color for effects like {@link ParticleEffect#SPELL_MOB}, {@link ParticleEffect#SPELL_MOB_AMBIENT}, {@link ParticleEffect#REDSTONE} and {@link ParticleEffect#NOTE} - * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static abstract class ParticleColor { - /** - * Returns the value for the offsetX field - * - * @return The offsetX value - */ - public abstract float getValueX(); - - /** - * Returns the value for the offsetY field - * - * @return The offsetY value - */ - public abstract float getValueY(); - - /** - * Returns the value for the offsetZ field - * - * @return The offsetZ value - */ - public abstract float getValueZ(); - } - - /** - * Represents the color for effects like {@link ParticleEffect#SPELL_MOB}, {@link ParticleEffect#SPELL_MOB_AMBIENT} and {@link ParticleEffect#NOTE} - * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static final class OrdinaryColor extends ParticleColor { - private final int red; - private final int green; - private final int blue; - - /** - * Construct a new ordinary color - * - * @param red Red value of the RGB format - * @param green Green value of the RGB format - * @param blue Blue value of the RGB format - * @throws IllegalArgumentException If one of the values is lower than 0 or higher than 255 - */ - public OrdinaryColor(int red, int green, int blue) throws IllegalArgumentException { - if (red < 0) { - throw new IllegalArgumentException("The red value is lower than 0"); - } - if (red > 255) { - throw new IllegalArgumentException("The red value is higher than 255"); - } - this.red = red; - if (green < 0) { - throw new IllegalArgumentException("The green value is lower than 0"); - } - if (green > 255) { - throw new IllegalArgumentException("The green value is higher than 255"); - } - this.green = green; - if (blue < 0) { - throw new IllegalArgumentException("The blue value is lower than 0"); - } - if (blue > 255) { - throw new IllegalArgumentException("The blue value is higher than 255"); - } - this.blue = blue; - } - - /** - * Construct a new ordinary color - * - * @param color Bukkit color - */ - public OrdinaryColor(Color color) { - this(color.getRed(), color.getGreen(), color.getBlue()); - } - - /** - * Returns the red value of the RGB format - * - * @return The red value - */ - public int getRed() { - return red; - } - - /** - * Returns the green value of the RGB format - * - * @return The green value - */ - public int getGreen() { - return green; - } - - /** - * Returns the blue value of the RGB format - * - * @return The blue value - */ - public int getBlue() { - return blue; - } - - /** - * Returns the red value divided by 255 - * - * @return The offsetX value - */ - @Override - public float getValueX() { - return (float) red / 255F; - } - - /** - * Returns the green value divided by 255 - * - * @return The offsetY value - */ - @Override - public float getValueY() { - return (float) green / 255F; - } - - /** - * Returns the blue value divided by 255 - * - * @return The offsetZ value - */ - @Override - public float getValueZ() { - return (float) blue / 255F; - } - } - - /** - * Represents the color for the {@link ParticleEffect#NOTE} effect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - public static final class NoteColor extends ParticleColor { - private final int note; - - /** - * Construct a new note color - * - * @param note Note id which determines color - * @throws IllegalArgumentException If the note value is lower than 0 or higher than 24 - */ - public NoteColor(int note) throws IllegalArgumentException { - if (note < 0) { - throw new IllegalArgumentException("The note value is lower than 0"); - } - if (note > 24) { - throw new IllegalArgumentException("The note value is higher than 24"); - } - this.note = note; - } - - /** - * Returns the note value divided by 24 - * - * @return The offsetX value - */ - @Override - public float getValueX() { - return (float) note / 24F; - } - - /** - * Returns zero because the offsetY value is unused - * - * @return zero - */ - @Override - public float getValueY() { - return 0; - } - - /** - * Returns zero because the offsetZ value is unused - * - * @return zero - */ - @Override - public float getValueZ() { - return 0; - } - - } - - /** - * Represents a runtime exception that is thrown either if the displayed particle effect requires data and has none or vice-versa or if the data type is incorrect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - private static final class ParticleDataException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle data exception - * - * @param message Message that will be logged - */ - public ParticleDataException(String message) { - super(message); - } - } - - /** - * Represents a runtime exception that is thrown either if the displayed particle effect is not colorable or if the particle color type is incorrect - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.7 - */ - private static final class ParticleColorException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle color exception - * - * @param message Message that will be logged - */ - public ParticleColorException(String message) { - super(message); - } - } - - /** - * Represents a runtime exception that is thrown if the displayed particle effect requires a newer version - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.6 - */ - private static final class ParticleVersionException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new particle version exception - * - * @param message Message that will be logged - */ - public ParticleVersionException(String message) { - super(message); - } - } - - /** - * Represents a particle effect packet with all attributes which is used for sending packets to the players - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.5 - */ - public static final class ParticlePacket { - private static int version; - private static Class enumParticle; - private static Constructor packetConstructor; - private static Method getHandle; - private static Field playerConnection; - private static Method sendPacket; - private static boolean initialized; - private final ParticleEffect effect; - private final float offsetY; - private final float offsetZ; - private final float speed; - private final int amount; - private final boolean longDistance; - private final ParticleData data; - private float offsetX; - private Object packet; - - /** - * Construct a new particle packet - * - * @param effect Particle effect - * @param offsetX Maximum distance particles can fly away from the center on the x-axis - * @param offsetY Maximum distance particles can fly away from the center on the y-axis - * @param offsetZ Maximum distance particles can fly away from the center on the z-axis - * @param speed Display speed of the particles - * @param amount Amount of particles - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - * @param data Data of the effect - * @throws IllegalArgumentException If the speed or amount is lower than 0 - * @see #initialize() - */ - public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float offsetZ, float speed, int amount, boolean longDistance, ParticleData data) throws IllegalArgumentException { - initialize(); - if (speed < 0) { - throw new IllegalArgumentException("The speed is lower than 0"); - } - if (amount < 0) { - throw new IllegalArgumentException("The amount is lower than 0"); - } - this.effect = effect; - this.offsetX = offsetX; - this.offsetY = offsetY; - this.offsetZ = offsetZ; - this.speed = speed; - this.amount = amount; - this.longDistance = longDistance; - this.data = data; - } - - /** - * Construct a new particle packet of a single particle flying into a determined direction - * - * @param effect Particle effect - * @param direction Direction of the particle - * @param speed Display speed of the particle - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - * @param data Data of the effect - * @throws IllegalArgumentException If the speed is lower than 0 - */ - public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException { - this(effect, (float) direction.getX(), (float) direction.getY(), (float) direction.getZ(), speed, 0, longDistance, data); - } - - /** - * Construct a new particle packet of a single colored particle - * - * @param effect Particle effect - * @param color Color of the particle - * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 - */ - public ParticlePacket(ParticleEffect effect, ParticleColor color, boolean longDistance) { - this(effect, color.getValueX(), color.getValueY(), color.getValueZ(), 1, 0, longDistance, null); - if (effect == ParticleEffect.REDSTONE && color instanceof OrdinaryColor && ((OrdinaryColor) color).getRed() == 0) { - offsetX = Float.MIN_NORMAL; - } - } - - /** - * Initializes {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} and sets {@link #initialized} to true if it succeeds - * - * Note: These fields only have to be initialized once, so it will return if {@link #initialized} is already set to true - * - * @throws VersionIncompatibleException if your bukkit version is not supported by this library - */ - public static void initialize() throws VersionIncompatibleException { - if (initialized) { - return; - } - try { - version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); - if (version > 7) { - enumParticle = ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass("EnumParticle"); - } - - Class packetClass = ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); - - packetConstructor = ReflectionUtils.getConstructor(packetClass); - getHandle = ReflectionUtils.getMethod("CraftPlayer", ReflectionUtils.PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); - playerConnection = ReflectionUtils.getField("EntityPlayer", ReflectionUtils.PackageType.MINECRAFT_SERVER, false, "playerConnection"); - sendPacket = ReflectionUtils.getMethod(playerConnection.getType(), "sendPacket", ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass("Packet")); - } catch (Exception exception) { - throw new VersionIncompatibleException("Your current bukkit version seems to be incompatible with this library", exception); - } - initialized = true; - } - - /** - * Returns the version of your server (1.x) - * - * @return The version number - */ - public static int getVersion() { - if (!initialized) { - initialize(); - } - return version; - } - - /** - * Determine if {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} are initialized - * - * @return Whether these fields are initialized or not - * @see #initialize() - */ - public static boolean isInitialized() { - return initialized; - } - - /** - * Initializes {@link #packet} with all set values - * - * @param center Center location of the effect - * @throws PacketInstantiationException If instantion fails due to an unknown error - */ - private void initializePacket(Location center) throws PacketInstantiationException { - if (packet != null) { - return; - } - try { - packet = packetConstructor.newInstance(); - if (version < 8) { - String name = effect.getName(); - if (data != null) { - name += data.getPacketDataString(); - } - ReflectionUtils.setValue(packet, true, "a", name); - } else { - ReflectionUtils.setValue(packet, true, "a", enumParticle.getEnumConstants()[effect.getId()]); - ReflectionUtils.setValue(packet, true, "j", longDistance); - if (data != null) { - int[] packetData = data.getPacketData(); - ReflectionUtils.setValue(packet, true, "k", effect == ParticleEffect.ITEM_CRACK ? packetData : new int[]{packetData[0] | (packetData[1] << 12)}); - } - } - ReflectionUtils.setValue(packet, true, "b", (float) center.getX()); - ReflectionUtils.setValue(packet, true, "c", (float) center.getY()); - ReflectionUtils.setValue(packet, true, "d", (float) center.getZ()); - ReflectionUtils.setValue(packet, true, "e", offsetX); - ReflectionUtils.setValue(packet, true, "f", offsetY); - ReflectionUtils.setValue(packet, true, "g", offsetZ); - ReflectionUtils.setValue(packet, true, "h", speed); - ReflectionUtils.setValue(packet, true, "i", amount); - } catch (Exception exception) { - throw new PacketInstantiationException("Packet instantiation failed", exception); - } - } - - /** - * Sends the packet to a single player and caches it - * - * @param center Center location of the effect - * @param player Receiver of the packet - * @throws PacketInstantiationException If instantion fails due to an unknown error - * @throws PacketSendingException If sending fails due to an unknown error - * @see #initializePacket(Location) - */ - public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException { - initializePacket(center); - try { - sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); - } catch (Exception exception) { - throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception); - } - } - - /** - * Sends the packet to all players in the list - * - * @param center Center location of the effect - * @param players Receivers of the packet - * @throws IllegalArgumentException If the player list is empty - * @see #sendTo(Location center, Player player) - */ - public void sendTo(Location center, List players) throws IllegalArgumentException { - if (players.isEmpty()) { - throw new IllegalArgumentException("The player list is empty"); - } - for (Player player : players) { - sendTo(center, player); - } - } - - /** - * Sends the packet to all players in a certain range - * - * @param center Center location of the effect - * @param range Range in which players will receive the packet (Maximum range for particles is usually 16, but it can differ for some types) - * @throws IllegalArgumentException If the range is lower than 1 - * @see #sendTo(Location center, Player player) - */ - public void sendTo(Location center, double range) throws IllegalArgumentException { - if (range < 1) { - throw new IllegalArgumentException("The range is lower than 1"); - } - String worldName = center.getWorld().getName(); - double squared = range * range; - for (Player player : Bukkit.getOnlinePlayers()) { - if (!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) { - continue; - } - sendTo(center, player); - } - } - - /** - * Represents a runtime exception that is thrown if a bukkit version is not compatible with this library - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.5 - */ - private static final class VersionIncompatibleException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new version incompatible exception - * - * @param message Message that will be logged - * @param cause Cause of the exception - */ - public VersionIncompatibleException(String message, Throwable cause) { - super(message, cause); - } - } - - /** - * Represents a runtime exception that is thrown if packet instantiation fails - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.4 - */ - private static final class PacketInstantiationException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new packet instantiation exception - * - * @param message Message that will be logged - * @param cause Cause of the exception - */ - public PacketInstantiationException(String message, Throwable cause) { - super(message, cause); - } - } - - /** - * Represents a runtime exception that is thrown if packet sending fails - *

- * This class is part of the ParticleEffect Library and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.4 - */ - private static final class PacketSendingException extends RuntimeException { - private static final long serialVersionUID = 3203085387160737484L; - - /** - * Construct a new packet sending exception - * - * @param message Message that will be logged - * @param cause Cause of the exception - */ - public PacketSendingException(String message, Throwable cause) { - super(message, cause); - } - } - } + /** + * A particle effect which is displayed by exploding tnt and creepers: + *

    + *
  • It looks like a white cloud + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + EXPLOSION_NORMAL("explode", 0, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by exploding ghast fireballs and wither skulls: + *
    + *
  • It looks like a gray ball which is fading away + *
  • The speed value slightly influences the size of this particle effect + *
+ */ + EXPLOSION_LARGE("largeexplode", 1, -1), + /** + * A particle effect which is displayed by exploding tnt and creepers: + *
    + *
  • It looks like a crowd of gray balls which are fading away + *
  • The speed value has no influence on this particle effect + *
+ */ + EXPLOSION_HUGE("hugeexplosion", 2, -1), + /** + * A particle effect which is displayed by launching fireworks: + *
    + *
  • It looks like a white star which is sparkling + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + FIREWORKS_SPARK("fireworksSpark", 3, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by swimming entities and arrows in water: + *
    + *
  • It looks like a bubble + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + WATER_BUBBLE("bubble", 4, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_WATER), + /** + * A particle effect which is displayed by swimming entities and shaking wolves: + *
    + *
  • It looks like a blue drop + *
  • The speed value has no influence on this particle effect + *
+ */ + WATER_SPLASH("splash", 5, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed on water when fishing: + *
    + *
  • It looks like a blue droplet + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + WATER_WAKE("wake", 6, 7, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by water: + *
    + *
  • It looks like a tiny blue square + *
  • The speed value has no influence on this particle effect + *
+ */ + SUSPENDED("suspended", 7, -1, ParticleProperty.REQUIRES_WATER), + /** + * A particle effect which is displayed by air when close to bedrock and the in the void: + *
    + *
  • It looks like a tiny gray square + *
  • The speed value has no influence on this particle effect + *
+ */ + SUSPENDED_DEPTH("depthSuspend", 8, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed when landing a critical hit and by arrows: + *
    + *
  • It looks like a light brown cross + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + CRIT("crit", 9, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed when landing a hit with an enchanted weapon: + *
    + *
  • It looks like a cyan star + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + CRIT_MAGIC("magicCrit", 10, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by primed tnt, torches, droppers, dispensers, end portals, brewing stands and monster spawners: + *
    + *
  • It looks like a little gray cloud + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + SMOKE_NORMAL("smoke", 11, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by fire, minecarts with furnace and blazes: + *
    + *
  • It looks like a large gray cloud + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + SMOKE_LARGE("largesmoke", 12, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed when splash potions or bottles o' enchanting hit something: + *
    + *
  • It looks like a white swirl + *
  • The speed value causes the particle to only move upwards when set to 0 + *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 + *
+ */ + SPELL("spell", 13, -1), + /** + * A particle effect which is displayed when instant splash potions hit something: + *
    + *
  • It looks like a white cross + *
  • The speed value causes the particle to only move upwards when set to 0 + *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 + *
+ */ + SPELL_INSTANT("instantSpell", 14, -1), + /** + * A particle effect which is displayed by entities with active potion effects: + *
    + *
  • It looks like a colored swirl + *
  • The speed value causes the particle to be colored black when set to 0 + *
  • The particle color gets lighter when increasing the speed and darker when decreasing the speed + *
+ */ + SPELL_MOB("mobSpell", 15, -1, ParticleProperty.COLORABLE), + /** + * A particle effect which is displayed by entities with active potion effects applied through a beacon: + *
    + *
  • It looks like a transparent colored swirl + *
  • The speed value causes the particle to be always colored black when set to 0 + *
  • The particle color gets lighter when increasing the speed and darker when decreasing the speed + *
+ */ + SPELL_MOB_AMBIENT("mobSpellAmbient", 16, -1, ParticleProperty.COLORABLE), + /** + * A particle effect which is displayed by witches: + *
    + *
  • It looks like a purple cross + *
  • The speed value causes the particle to only move upwards when set to 0 + *
  • Only the motion on the y-axis can be controlled, the motion on the x- and z-axis are multiplied by 0.1 when setting the values to 0 + *
+ */ + SPELL_WITCH("witchMagic", 17, -1), + /** + * A particle effect which is displayed by blocks beneath a water source: + *
    + *
  • It looks like a blue drip + *
  • The speed value has no influence on this particle effect + *
+ */ + DRIP_WATER("dripWater", 18, -1), + /** + * A particle effect which is displayed by blocks beneath a lava source: + *
    + *
  • It looks like an orange drip + *
  • The speed value has no influence on this particle effect + *
+ */ + DRIP_LAVA("dripLava", 19, -1), + /** + * A particle effect which is displayed when attacking a villager in a village: + *
    + *
  • It looks like a cracked gray heart + *
  • The speed value has no influence on this particle effect + *
+ */ + VILLAGER_ANGRY("angryVillager", 20, -1), + /** + * A particle effect which is displayed when using bone meal and trading with a villager in a village: + *
    + *
  • It looks like a green star + *
  • The speed value has no influence on this particle effect + *
+ */ + VILLAGER_HAPPY("happyVillager", 21, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by mycelium: + *
    + *
  • It looks like a tiny gray square + *
  • The speed value has no influence on this particle effect + *
+ */ + TOWN_AURA("townaura", 22, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by note blocks: + *
    + *
  • It looks like a colored note + *
  • The speed value causes the particle to be colored green when set to 0 + *
+ */ + NOTE("note", 23, -1, ParticleProperty.COLORABLE), + /** + * A particle effect which is displayed by nether portals, endermen, ender pearls, eyes of ender, ender chests and dragon eggs: + *
    + *
  • It looks like a purple cloud + *
  • The speed value influences the spread of this particle effect + *
+ */ + PORTAL("portal", 24, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by enchantment tables which are nearby bookshelves: + *
    + *
  • It looks like a cryptic white letter + *
  • The speed value influences the spread of this particle effect + *
+ */ + ENCHANTMENT_TABLE("enchantmenttable", 25, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by torches, active furnaces, magma cubes and monster spawners: + *
    + *
  • It looks like a tiny flame + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + FLAME("flame", 26, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by lava: + *
    + *
  • It looks like a spark + *
  • The speed value has no influence on this particle effect + *
+ */ + LAVA("lava", 27, -1), + /** + * A particle effect which is currently unused: + *
    + *
  • It looks like a transparent gray square + *
  • The speed value has no influence on this particle effect + *
+ */ + FOOTSTEP("footstep", 28, -1), + /** + * A particle effect which is displayed when a mob dies: + *
    + *
  • It looks like a large white cloud + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + CLOUD("cloud", 29, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by redstone ore, powered redstone, redstone torches and redstone repeaters: + *
    + *
  • It looks like a tiny colored cloud + *
  • The speed value causes the particle to be colored red when set to 0 + *
+ */ + REDSTONE("reddust", 30, -1, ParticleProperty.COLORABLE), + /** + * A particle effect which is displayed when snowballs hit a block: + *
    + *
  • It looks like a little piece with the snowball texture + *
  • The speed value has no influence on this particle effect + *
+ */ + SNOWBALL("snowballpoof", 31, -1), + /** + * A particle effect which is currently unused: + *
    + *
  • It looks like a tiny white cloud + *
  • The speed value influences the velocity at which the particle flies off + *
+ */ + SNOW_SHOVEL("snowshovel", 32, -1, ParticleProperty.DIRECTIONAL), + /** + * A particle effect which is displayed by slimes: + *
    + *
  • It looks like a tiny part of the slimeball icon + *
  • The speed value has no influence on this particle effect + *
+ */ + SLIME("slime", 33, -1), + /** + * A particle effect which is displayed when breeding and taming animals: + *
    + *
  • It looks like a red heart + *
  • The speed value has no influence on this particle effect + *
+ */ + HEART("heart", 34, -1), + /** + * A particle effect which is displayed by barriers: + *
    + *
  • It looks like a red box with a slash through it + *
  • The speed value has no influence on this particle effect + *
+ */ + BARRIER("barrier", 35, 8), + /** + * A particle effect which is displayed when breaking a tool or eggs hit a block: + *
    + *
  • It looks like a little piece with an item texture + *
+ */ + ITEM_CRACK("iconcrack", 36, -1, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), + /** + * A particle effect which is displayed when breaking blocks or sprinting: + *
    + *
  • It looks like a little piece with a block texture + *
  • The speed value has no influence on this particle effect + *
+ */ + BLOCK_CRACK("blockcrack", 37, -1, ParticleProperty.REQUIRES_DATA), + /** + * A particle effect which is displayed when falling: + *
    + *
  • It looks like a little piece with a block texture + *
+ */ + BLOCK_DUST("blockdust", 38, 7, ParticleProperty.DIRECTIONAL, ParticleProperty.REQUIRES_DATA), + /** + * A particle effect which is displayed when rain hits the ground: + *
    + *
  • It looks like a blue droplet + *
  • The speed value has no influence on this particle effect + *
+ */ + WATER_DROP("droplet", 39, 8), + /** + * A particle effect which is currently unused: + *
    + *
  • It has no visual effect + *
+ */ + ITEM_TAKE("take", 40, 8), + /** + * A particle effect which is displayed by elder guardians: + *
    + *
  • It looks like the shape of the elder guardian + *
  • The speed value has no influence on this particle effect + *
  • The offset values have no influence on this particle effect + *
+ */ + MOB_APPEARANCE("mobappearance", 41, 8); + + private static final Map NAME_MAP = new HashMap(); + private static final Map ID_MAP = new HashMap(); + + // Initialize map for quick name and id lookup + static { + for (ParticleEffect effect : values()) { + NAME_MAP.put(effect.name, effect); + ID_MAP.put(effect.id, effect); + } + } + + private final String name; + private final int id; + private final int requiredVersion; + private final List properties; + + /** + * Construct a new particle effect + * + * @param name Name of this particle effect + * @param id Id of this particle effect + * @param requiredVersion Version which is required (1.x) + * @param properties Properties of this particle effect + */ + ParticleEffect(String name, int id, int requiredVersion, ParticleProperty... properties) { + this.name = name; + this.id = id; + this.requiredVersion = requiredVersion; + this.properties = Arrays.asList(properties); + } + + /** + * Returns the particle effect with the given name + * + * @param name Name of the particle effect + * @return The particle effect + */ + public static ParticleEffect fromName(String name) { + for (Entry entry : NAME_MAP.entrySet()) { + if (!entry.getKey().equalsIgnoreCase(name)) { + continue; + } + return entry.getValue(); + } + return null; + } + + /** + * Returns the particle effect with the given id + * + * @param id Id of the particle effect + * @return The particle effect + */ + public static ParticleEffect fromId(int id) { + for (Entry entry : ID_MAP.entrySet()) { + if (entry.getKey() != id) { + continue; + } + return entry.getValue(); + } + return null; + } + + /** + * Determine if water is at a certain location + * + * @param location Location to check + * @return Whether water is at this location or not + */ + private static boolean isWater(Location location) { + Material material = location.getBlock().getType(); + return material == Material.WATER || material == SavageFactions.plugin.STATIONARY_WATER; + } + + /** + * Determine if the distance between @param location and one of the players exceeds 256 + * + * @param location Location to check + * @return Whether the distance exceeds 256 or not + */ + private static boolean isLongDistance(Location location, List players) { + String world = location.getWorld().getName(); + for (Player player : players) { + Location playerLocation = player.getLocation(); + if (!world.equals(playerLocation.getWorld().getName()) || playerLocation.distanceSquared(location) < 65536) { + continue; + } + return true; + } + return false; + } + + /** + * Determine if the data type for a particle effect is correct + * + * @param effect Particle effect + * @param data Particle data + * @return Whether the data type is correct or not + */ + private static boolean isDataCorrect(ParticleEffect effect, ParticleData data) { + return ((effect == BLOCK_CRACK || effect == BLOCK_DUST) && data instanceof BlockData) || (effect == ITEM_CRACK && data instanceof ItemData); + } + + /** + * Determine if the color type for a particle effect is correct + * + * @param effect Particle effect + * @param color Particle color + * @return Whether the color type is correct or not + */ + private static boolean isColorCorrect(ParticleEffect effect, ParticleColor color) { + return ((effect == SPELL_MOB || effect == SPELL_MOB_AMBIENT || effect == REDSTONE) && color instanceof OrdinaryColor) || (effect == NOTE && color instanceof NoteColor); + } + + /** + * Returns the name of this particle effect + * + * @return The name + */ + public String getName() { + return name; + } + + /** + * Returns the id of this particle effect + * + * @return The id + */ + public int getId() { + return id; + } + + /** + * Returns the required version for this particle effect (1.x) + * + * @return The required version + */ + public int getRequiredVersion() { + return requiredVersion; + } + + /** + * Determine if this particle effect has a specific property + * + * @param property - property to check. + * @return Whether it has the property or not + */ + public boolean hasProperty(ParticleProperty property) { + return properties.contains(property); + } + + /** + * Determine if this particle effect is supported by your current server version + * + * @return Whether the particle effect is supported or not + */ + public boolean isSupported() { + if (requiredVersion == -1) { + return true; + } + return ParticlePacket.getVersion() >= requiredVersion; + } + + /** + * Displays a particle effect which is only visible for all players within a certain range in the world of @param center + * + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect requires water and none is at the center location + * @see ParticlePacket + * @see ParticlePacket#sendTo(Location, double) + */ + public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect requires additional data"); + } + if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { + throw new IllegalArgumentException("There is no water at the center location"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, null).sendTo(center, range); + } + + /** + * Displays a particle effect which is only visible for the specified players + * + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect requires water and none is at the center location + * @see ParticlePacket + * @see ParticlePacket#sendTo(Location, List) + */ + public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect requires additional data"); + } + if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { + throw new IllegalArgumentException("There is no water at the center location"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players); + } + + /** + * Displays a particle effect which is only visible for the specified players + * + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect requires water and none is at the center location + * @see #display(float, float, float, float, int, Location, List) + */ + public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + display(offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); + } + + /** + * Displays a single particle which flies into a determined direction and is only visible for all players within a certain range in the world of @param center + * + * @param direction Direction of the particle + * @param speed Display speed of the particle + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location + * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, ParticleData) + * @see ParticlePacket#sendTo(Location, double) + */ + public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect requires additional data"); + } + if (!hasProperty(ParticleProperty.DIRECTIONAL)) { + throw new IllegalArgumentException("This particle effect is not directional"); + } + if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { + throw new IllegalArgumentException("There is no water at the center location"); + } + new ParticlePacket(this, direction, speed, range > 256, null).sendTo(center, range); + } + + /** + * Displays a single particle which flies into a determined direction and is only visible for the specified players + * + * @param direction Direction of the particle + * @param speed Display speed of the particle + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location + * @see ParticlePacket#ParticlePacket(ParticleEffect, Vector, float, boolean, ParticleData) + * @see ParticlePacket#sendTo(Location, List) + */ + public void display(Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect requires additional data"); + } + if (!hasProperty(ParticleProperty.DIRECTIONAL)) { + throw new IllegalArgumentException("This particle effect is not directional"); + } + if (hasProperty(ParticleProperty.REQUIRES_WATER) && !isWater(center)) { + throw new IllegalArgumentException("There is no water at the center location"); + } + new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players); + } + + /** + * Displays a single particle which flies into a determined direction and is only visible for the specified players + * + * @param direction Direction of the particle + * @param speed Display speed of the particle + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect requires additional data + * @throws IllegalArgumentException If the particle effect is not directional or if it requires water and none is at the center location + * @see #display(Vector, float, Location, List) + */ + public void display(Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException { + display(direction, speed, center, Arrays.asList(players)); + } + + /** + * Displays a single particle which is colored and only visible for all players within a certain range in the world of @param center + * + * @param color Color of the particle + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect + * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) + * @see ParticlePacket#sendTo(Location, double) + */ + public void display(ParticleColor color, Location center, double range) throws ParticleVersionException, ParticleColorException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (!hasProperty(ParticleProperty.COLORABLE)) { + throw new ParticleColorException("This particle effect is not colorable"); + } + if (!isColorCorrect(this, color)) { + throw new ParticleColorException("The particle color type is incorrect"); + } + new ParticlePacket(this, color, range > 256).sendTo(center, range); + } + + /** + * Displays a single particle which is colored and only visible for the specified players + * + * @param color Color of the particle + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect + * @see ParticlePacket#ParticlePacket(ParticleEffect, ParticleColor, boolean) + * @see ParticlePacket#sendTo(Location, List) + */ + public void display(ParticleColor color, Location center, List players) throws ParticleVersionException, ParticleColorException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (!hasProperty(ParticleProperty.COLORABLE)) { + throw new ParticleColorException("This particle effect is not colorable"); + } + if (!isColorCorrect(this, color)) { + throw new ParticleColorException("The particle color type is incorrect"); + } + new ParticlePacket(this, color, isLongDistance(center, players)).sendTo(center, players); + } + + /** + * Displays a single particle which is colored and only visible for the specified players + * + * @param color Color of the particle + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleColorException If the particle effect is not colorable or the color type is incorrect + * @see #display(ParticleColor, Location, List) + */ + public void display(ParticleColor color, Location center, Player... players) throws ParticleVersionException, ParticleColorException { + display(color, center, Arrays.asList(players)); + } + + /** + * Displays a particle effect which requires additional data and is only visible for all players within a certain range in the world of @param center + * + * @param data Data of the effect + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect + * @see ParticlePacket + * @see ParticlePacket#sendTo(Location, double) + */ + public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect does not require additional data"); + } + if (!isDataCorrect(this, data)) { + throw new ParticleDataException("The particle data type is incorrect"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 256, data).sendTo(center, range); + } + + /** + * Displays a particle effect which requires additional data and is only visible for the specified players + * + * @param data Data of the effect + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect + * @see ParticlePacket + * @see ParticlePacket#sendTo(Location, List) + */ + public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List players) throws ParticleVersionException, ParticleDataException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect does not require additional data"); + } + if (!isDataCorrect(this, data)) { + throw new ParticleDataException("The particle data type is incorrect"); + } + new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players); + } + + /** + * Displays a particle effect which requires additional data and is only visible for the specified players + * + * @param data Data of the effect + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect + * @see #display(ParticleData, float, float, float, float, int, Location, List) + */ + public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException { + display(data, offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players)); + } + + /** + * Displays a single particle which requires additional data that flies into a determined direction and is only visible for all players within a certain range in the world of @param center + * + * @param data Data of the effect + * @param direction Direction of the particle + * @param speed Display speed of the particles + * @param center Center location of the effect + * @param range Range of the visibility + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect + * @see ParticlePacket + * @see ParticlePacket#sendTo(Location, double) + */ + public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect does not require additional data"); + } + if (!isDataCorrect(this, data)) { + throw new ParticleDataException("The particle data type is incorrect"); + } + new ParticlePacket(this, direction, speed, range > 256, data).sendTo(center, range); + } + + /** + * Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players + * + * @param data Data of the effect + * @param direction Direction of the particle + * @param speed Display speed of the particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect + * @see ParticlePacket + * @see ParticlePacket#sendTo(Location, List) + */ + public void display(ParticleData data, Vector direction, float speed, Location center, List players) throws ParticleVersionException, ParticleDataException { + if (!isSupported()) { + throw new ParticleVersionException("This particle effect is not supported by your server version"); + } + if (!hasProperty(ParticleProperty.REQUIRES_DATA)) { + throw new ParticleDataException("This particle effect does not require additional data"); + } + if (!isDataCorrect(this, data)) { + throw new ParticleDataException("The particle data type is incorrect"); + } + new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players); + } + + /** + * Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players + * + * @param data Data of the effect + * @param direction Direction of the particle + * @param speed Display speed of the particles + * @param center Center location of the effect + * @param players Receivers of the effect + * @throws ParticleVersionException If the particle effect is not supported by the server version + * @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect + * @see #display(ParticleData, Vector, float, Location, List) + */ + public void display(ParticleData data, Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException { + display(data, direction, speed, center, Arrays.asList(players)); + } + + /** + * Represents the property of a particle effect + * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public enum ParticleProperty { + /** + * The particle effect requires water to be displayed + */ + REQUIRES_WATER, + /** + * The particle effect requires block or item data to be displayed + */ + REQUIRES_DATA, + /** + * The particle effect uses the offsets as direction values + */ + DIRECTIONAL, + /** + * The particle effect uses the offsets as color values + */ + COLORABLE + } + + /** + * Represents the particle data for effects like {@link ParticleEffect#ITEM_CRACK}, {@link ParticleEffect#BLOCK_CRACK} and {@link ParticleEffect#BLOCK_DUST} + * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + public static abstract class ParticleData { + private final Material material; + private final byte data; + private final int[] packetData; + + /** + * Construct a new particle data + * + * @param material Material of the item/block + * @param data Data value of the item/block + */ + @SuppressWarnings("deprecation") + public ParticleData(Material material, byte data) { + this.material = material; + this.data = data; + this.packetData = new int[]{material.getId(), data}; + } + + /** + * Returns the material of this data + * + * @return The material + */ + public Material getMaterial() { + return material; + } + + /** + * Returns the data value of this data + * + * @return The data value + */ + public byte getData() { + return data; + } + + /** + * Returns the data as an int array for packet construction + * + * @return The data for the packet + */ + public int[] getPacketData() { + return packetData; + } + + /** + * Returns the data as a string for pre 1.8 versions + * + * @return The data string for the packet + */ + public String getPacketDataString() { + return "_" + packetData[0] + "_" + packetData[1]; + } + } + + /** + * Represents the item data for the {@link ParticleEffect#ITEM_CRACK} effect + * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + public static final class ItemData extends ParticleData { + /** + * Construct a new item data + * + * @param material Material of the item + * @param data Data value of the item + * @see ParticleData#ParticleData(Material, byte) + */ + public ItemData(Material material, byte data) { + super(material, data); + } + } + + /** + * Represents the block data for the {@link ParticleEffect#BLOCK_CRACK} and {@link ParticleEffect#BLOCK_DUST} effects + * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + public static final class BlockData extends ParticleData { + /** + * Construct a new block data + * + * @param material Material of the block + * @param data Data value of the block + * @throws IllegalArgumentException If the material is not a block + * @see ParticleData#ParticleData(Material, byte) + */ + public BlockData(Material material, byte data) throws IllegalArgumentException { + super(material, data); + if (!material.isBlock()) { + throw new IllegalArgumentException("The material is not a block"); + } + } + } + + /** + * Represents the color for effects like {@link ParticleEffect#SPELL_MOB}, {@link ParticleEffect#SPELL_MOB_AMBIENT}, {@link ParticleEffect#REDSTONE} and {@link ParticleEffect#NOTE} + * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public static abstract class ParticleColor { + /** + * Returns the value for the offsetX field + * + * @return The offsetX value + */ + public abstract float getValueX(); + + /** + * Returns the value for the offsetY field + * + * @return The offsetY value + */ + public abstract float getValueY(); + + /** + * Returns the value for the offsetZ field + * + * @return The offsetZ value + */ + public abstract float getValueZ(); + } + + /** + * Represents the color for effects like {@link ParticleEffect#SPELL_MOB}, {@link ParticleEffect#SPELL_MOB_AMBIENT} and {@link ParticleEffect#NOTE} + * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public static final class OrdinaryColor extends ParticleColor { + private final int red; + private final int green; + private final int blue; + + /** + * Construct a new ordinary color + * + * @param red Red value of the RGB format + * @param green Green value of the RGB format + * @param blue Blue value of the RGB format + * @throws IllegalArgumentException If one of the values is lower than 0 or higher than 255 + */ + public OrdinaryColor(int red, int green, int blue) throws IllegalArgumentException { + if (red < 0) { + throw new IllegalArgumentException("The red value is lower than 0"); + } + if (red > 255) { + throw new IllegalArgumentException("The red value is higher than 255"); + } + this.red = red; + if (green < 0) { + throw new IllegalArgumentException("The green value is lower than 0"); + } + if (green > 255) { + throw new IllegalArgumentException("The green value is higher than 255"); + } + this.green = green; + if (blue < 0) { + throw new IllegalArgumentException("The blue value is lower than 0"); + } + if (blue > 255) { + throw new IllegalArgumentException("The blue value is higher than 255"); + } + this.blue = blue; + } + + /** + * Construct a new ordinary color + * + * @param color Bukkit color + */ + public OrdinaryColor(Color color) { + this(color.getRed(), color.getGreen(), color.getBlue()); + } + + /** + * Returns the red value of the RGB format + * + * @return The red value + */ + public int getRed() { + return red; + } + + /** + * Returns the green value of the RGB format + * + * @return The green value + */ + public int getGreen() { + return green; + } + + /** + * Returns the blue value of the RGB format + * + * @return The blue value + */ + public int getBlue() { + return blue; + } + + /** + * Returns the red value divided by 255 + * + * @return The offsetX value + */ + @Override + public float getValueX() { + return (float) red / 255F; + } + + /** + * Returns the green value divided by 255 + * + * @return The offsetY value + */ + @Override + public float getValueY() { + return (float) green / 255F; + } + + /** + * Returns the blue value divided by 255 + * + * @return The offsetZ value + */ + @Override + public float getValueZ() { + return (float) blue / 255F; + } + } + + /** + * Represents the color for the {@link ParticleEffect#NOTE} effect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + public static final class NoteColor extends ParticleColor { + private final int note; + + /** + * Construct a new note color + * + * @param note Note id which determines color + * @throws IllegalArgumentException If the note value is lower than 0 or higher than 24 + */ + public NoteColor(int note) throws IllegalArgumentException { + if (note < 0) { + throw new IllegalArgumentException("The note value is lower than 0"); + } + if (note > 24) { + throw new IllegalArgumentException("The note value is higher than 24"); + } + this.note = note; + } + + /** + * Returns the note value divided by 24 + * + * @return The offsetX value + */ + @Override + public float getValueX() { + return (float) note / 24F; + } + + /** + * Returns zero because the offsetY value is unused + * + * @return zero + */ + @Override + public float getValueY() { + return 0; + } + + /** + * Returns zero because the offsetZ value is unused + * + * @return zero + */ + @Override + public float getValueZ() { + return 0; + } + + } + + /** + * Represents a runtime exception that is thrown either if the displayed particle effect requires data and has none or vice-versa or if the data type is incorrect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + private static final class ParticleDataException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new particle data exception + * + * @param message Message that will be logged + */ + public ParticleDataException(String message) { + super(message); + } + } + + /** + * Represents a runtime exception that is thrown either if the displayed particle effect is not colorable or if the particle color type is incorrect + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.7 + */ + private static final class ParticleColorException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new particle color exception + * + * @param message Message that will be logged + */ + public ParticleColorException(String message) { + super(message); + } + } + + /** + * Represents a runtime exception that is thrown if the displayed particle effect requires a newer version + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.6 + */ + private static final class ParticleVersionException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new particle version exception + * + * @param message Message that will be logged + */ + public ParticleVersionException(String message) { + super(message); + } + } + + /** + * Represents a particle effect packet with all attributes which is used for sending packets to the players + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.5 + */ + public static final class ParticlePacket { + private static int version; + private static Class enumParticle; + private static Constructor packetConstructor; + private static Method getHandle; + private static Field playerConnection; + private static Method sendPacket; + private static boolean initialized; + private final ParticleEffect effect; + private final float offsetY; + private final float offsetZ; + private final float speed; + private final int amount; + private final boolean longDistance; + private final ParticleData data; + private float offsetX; + private Object packet; + + /** + * Construct a new particle packet + * + * @param effect Particle effect + * @param offsetX Maximum distance particles can fly away from the center on the x-axis + * @param offsetY Maximum distance particles can fly away from the center on the y-axis + * @param offsetZ Maximum distance particles can fly away from the center on the z-axis + * @param speed Display speed of the particles + * @param amount Amount of particles + * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 + * @param data Data of the effect + * @throws IllegalArgumentException If the speed or amount is lower than 0 + * @see #initialize() + */ + public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float offsetZ, float speed, int amount, boolean longDistance, ParticleData data) throws IllegalArgumentException { + initialize(); + if (speed < 0) { + throw new IllegalArgumentException("The speed is lower than 0"); + } + if (amount < 0) { + throw new IllegalArgumentException("The amount is lower than 0"); + } + this.effect = effect; + this.offsetX = offsetX; + this.offsetY = offsetY; + this.offsetZ = offsetZ; + this.speed = speed; + this.amount = amount; + this.longDistance = longDistance; + this.data = data; + } + + /** + * Construct a new particle packet of a single particle flying into a determined direction + * + * @param effect Particle effect + * @param direction Direction of the particle + * @param speed Display speed of the particle + * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 + * @param data Data of the effect + * @throws IllegalArgumentException If the speed is lower than 0 + */ + public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException { + this(effect, (float) direction.getX(), (float) direction.getY(), (float) direction.getZ(), speed, 0, longDistance, data); + } + + /** + * Construct a new particle packet of a single colored particle + * + * @param effect Particle effect + * @param color Color of the particle + * @param longDistance Indicates whether the maximum distance is increased from 256 to 65536 + */ + public ParticlePacket(ParticleEffect effect, ParticleColor color, boolean longDistance) { + this(effect, color.getValueX(), color.getValueY(), color.getValueZ(), 1, 0, longDistance, null); + if (effect == ParticleEffect.REDSTONE && color instanceof OrdinaryColor && ((OrdinaryColor) color).getRed() == 0) { + offsetX = Float.MIN_NORMAL; + } + } + + /** + * Initializes {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} and sets {@link #initialized} to true if it succeeds + * + * Note: These fields only have to be initialized once, so it will return if {@link #initialized} is already set to true + * + * @throws VersionIncompatibleException if your bukkit version is not supported by this library + */ + public static void initialize() throws VersionIncompatibleException { + if (initialized) { + return; + } + try { + version = Integer.parseInt(ReflectionUtils.PackageType.getServerVersion().split("_")[1]); + if (version > 7) { + enumParticle = ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass("EnumParticle"); + } + + Class packetClass = ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles"); + + packetConstructor = ReflectionUtils.getConstructor(packetClass); + getHandle = ReflectionUtils.getMethod("CraftPlayer", ReflectionUtils.PackageType.CRAFTBUKKIT_ENTITY, "getHandle"); + playerConnection = ReflectionUtils.getField("EntityPlayer", ReflectionUtils.PackageType.MINECRAFT_SERVER, false, "playerConnection"); + sendPacket = ReflectionUtils.getMethod(playerConnection.getType(), "sendPacket", ReflectionUtils.PackageType.MINECRAFT_SERVER.getClass("Packet")); + } catch (Exception exception) { + throw new VersionIncompatibleException("Your current bukkit version seems to be incompatible with this library", exception); + } + initialized = true; + } + + /** + * Returns the version of your server (1.x) + * + * @return The version number + */ + public static int getVersion() { + if (!initialized) { + initialize(); + } + return version; + } + + /** + * Determine if {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} are initialized + * + * @return Whether these fields are initialized or not + * @see #initialize() + */ + public static boolean isInitialized() { + return initialized; + } + + /** + * Initializes {@link #packet} with all set values + * + * @param center Center location of the effect + * @throws PacketInstantiationException If instantion fails due to an unknown error + */ + private void initializePacket(Location center) throws PacketInstantiationException { + if (packet != null) { + return; + } + try { + packet = packetConstructor.newInstance(); + if (version < 8) { + String name = effect.getName(); + if (data != null) { + name += data.getPacketDataString(); + } + ReflectionUtils.setValue(packet, true, "a", name); + } else { + ReflectionUtils.setValue(packet, true, "a", enumParticle.getEnumConstants()[effect.getId()]); + ReflectionUtils.setValue(packet, true, "j", longDistance); + if (data != null) { + int[] packetData = data.getPacketData(); + ReflectionUtils.setValue(packet, true, "k", effect == ParticleEffect.ITEM_CRACK ? packetData : new int[]{packetData[0] | (packetData[1] << 12)}); + } + } + ReflectionUtils.setValue(packet, true, "b", (float) center.getX()); + ReflectionUtils.setValue(packet, true, "c", (float) center.getY()); + ReflectionUtils.setValue(packet, true, "d", (float) center.getZ()); + ReflectionUtils.setValue(packet, true, "e", offsetX); + ReflectionUtils.setValue(packet, true, "f", offsetY); + ReflectionUtils.setValue(packet, true, "g", offsetZ); + ReflectionUtils.setValue(packet, true, "h", speed); + ReflectionUtils.setValue(packet, true, "i", amount); + } catch (Exception exception) { + throw new PacketInstantiationException("Packet instantiation failed", exception); + } + } + + /** + * Sends the packet to a single player and caches it + * + * @param center Center location of the effect + * @param player Receiver of the packet + * @throws PacketInstantiationException If instantion fails due to an unknown error + * @throws PacketSendingException If sending fails due to an unknown error + * @see #initializePacket(Location) + */ + public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException { + initializePacket(center); + try { + sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet); + } catch (Exception exception) { + throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception); + } + } + + /** + * Sends the packet to all players in the list + * + * @param center Center location of the effect + * @param players Receivers of the packet + * @throws IllegalArgumentException If the player list is empty + * @see #sendTo(Location center, Player player) + */ + public void sendTo(Location center, List players) throws IllegalArgumentException { + if (players.isEmpty()) { + throw new IllegalArgumentException("The player list is empty"); + } + for (Player player : players) { + sendTo(center, player); + } + } + + /** + * Sends the packet to all players in a certain range + * + * @param center Center location of the effect + * @param range Range in which players will receive the packet (Maximum range for particles is usually 16, but it can differ for some types) + * @throws IllegalArgumentException If the range is lower than 1 + * @see #sendTo(Location center, Player player) + */ + public void sendTo(Location center, double range) throws IllegalArgumentException { + if (range < 1) { + throw new IllegalArgumentException("The range is lower than 1"); + } + String worldName = center.getWorld().getName(); + double squared = range * range; + for (Player player : Bukkit.getOnlinePlayers()) { + if (!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) { + continue; + } + sendTo(center, player); + } + } + + /** + * Represents a runtime exception that is thrown if a bukkit version is not compatible with this library + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.5 + */ + private static final class VersionIncompatibleException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new version incompatible exception + * + * @param message Message that will be logged + * @param cause Cause of the exception + */ + public VersionIncompatibleException(String message, Throwable cause) { + super(message, cause); + } + } + + /** + * Represents a runtime exception that is thrown if packet instantiation fails + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.4 + */ + private static final class PacketInstantiationException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new packet instantiation exception + * + * @param message Message that will be logged + * @param cause Cause of the exception + */ + public PacketInstantiationException(String message, Throwable cause) { + super(message, cause); + } + } + + /** + * Represents a runtime exception that is thrown if packet sending fails + *

+ * This class is part of the ParticleEffect Library and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.4 + */ + private static final class PacketSendingException extends RuntimeException { + private static final long serialVersionUID = 3203085387160737484L; + + /** + * Construct a new packet sending exception + * + * @param message Message that will be logged + * @param cause Cause of the exception + */ + public PacketSendingException(String message, Throwable cause) { + super(message, cause); + } + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/util/Particles/ReflectionUtils.java b/src/main/java/com/massivecraft/factions/util/Particles/ReflectionUtils.java index e3923367..4184eb08 100644 --- a/src/main/java/com/massivecraft/factions/util/Particles/ReflectionUtils.java +++ b/src/main/java/com/massivecraft/factions/util/Particles/ReflectionUtils.java @@ -26,583 +26,583 @@ import java.util.Map; * @version 1.1 */ public final class ReflectionUtils { - // Prevent accidental construction - private ReflectionUtils() { - } + // Prevent accidental construction + private ReflectionUtils() { + } - /** - * Returns the constructor of a given class with the given parameter types - * - * @param clazz Target class - * @param parameterTypes Parameter types of the desired constructor - * @return The constructor of the target class with the specified parameter types - * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found - * @see DataType - * @see DataType#getPrimitive(Class[]) - * @see DataType#compare(Class[], Class[]) - */ - public static Constructor getConstructor(Class clazz, Class... parameterTypes) throws NoSuchMethodException { - Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); - for (Constructor constructor : clazz.getConstructors()) { - if (!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) { - continue; - } - return constructor; - } - throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types"); - } + /** + * Returns the constructor of a given class with the given parameter types + * + * @param clazz Target class + * @param parameterTypes Parameter types of the desired constructor + * @return The constructor of the target class with the specified parameter types + * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found + * @see DataType + * @see DataType#getPrimitive(Class[]) + * @see DataType#compare(Class[], Class[]) + */ + public static Constructor getConstructor(Class clazz, Class... parameterTypes) throws NoSuchMethodException { + Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); + for (Constructor constructor : clazz.getConstructors()) { + if (!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) { + continue; + } + return constructor; + } + throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types"); + } - /** - * Returns the constructor of a desired class with the given parameter types - * - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param parameterTypes Parameter types of the desired constructor - * @return The constructor of the desired target class with the specified parameter types - * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found - * @throws ClassNotFoundException ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass() (String, PackageType) - * @see #getConstructor(Class, Class...) - */ - public static Constructor getConstructor(String className, PackageType packageType, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { - return getConstructor(packageType.getClass(className), parameterTypes); - } + /** + * Returns the constructor of a desired class with the given parameter types + * + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param parameterTypes Parameter types of the desired constructor + * @return The constructor of the desired target class with the specified parameter types + * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found + * @throws ClassNotFoundException ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #getClass() (String, PackageType) + * @see #getConstructor(Class, Class...) + */ + public static Constructor getConstructor(String className, PackageType packageType, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { + return getConstructor(packageType.getClass(className), parameterTypes); + } - /** - * Returns an instance of a class with the given arguments - * - * @param clazz Target class - * @param arguments Arguments which are used to construct an object of the target class - * @return The instance of the target class with the specified arguments - * @throws InstantiationException If you cannot create an instance of the target class due to certain circumstances - * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances - * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments) - * @throws InvocationTargetException If the desired constructor cannot be invoked - * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found - */ - public static Object instantiateObject(Class clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { - return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); - } + /** + * Returns an instance of a class with the given arguments + * + * @param clazz Target class + * @param arguments Arguments which are used to construct an object of the target class + * @return The instance of the target class with the specified arguments + * @throws InstantiationException If you cannot create an instance of the target class due to certain circumstances + * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances + * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments) + * @throws InvocationTargetException If the desired constructor cannot be invoked + * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found + */ + public static Object instantiateObject(Class clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); + } - /** - * Returns an instance of a desired class with the given arguments - * - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param arguments Arguments which are used to construct an object of the desired target class - * @return The instance of the desired target class with the specified arguments - * @throws InstantiationException If you cannot create an instance of the desired target class due to certain circumstances - * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances - * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments) - * @throws InvocationTargetException If the desired constructor cannot be invoked - * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found - * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass() (String, PackageType) - * @see #instantiateObject(Class, Object...) - */ - public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { - return instantiateObject(packageType.getClass(className), arguments); - } + /** + * Returns an instance of a desired class with the given arguments + * + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param arguments Arguments which are used to construct an object of the desired target class + * @return The instance of the desired target class with the specified arguments + * @throws InstantiationException If you cannot create an instance of the desired target class due to certain circumstances + * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances + * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments) + * @throws InvocationTargetException If the desired constructor cannot be invoked + * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found + * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #getClass() (String, PackageType) + * @see #instantiateObject(Class, Object...) + */ + public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + return instantiateObject(packageType.getClass(className), arguments); + } - /** - * Returns a method of a class with the given parameter types - * - * @param clazz Target class - * @param methodName Name of the desired method - * @param parameterTypes Parameter types of the desired method - * @return The method of the target class with the specified name and parameter types - * @throws NoSuchMethodException If the desired method of the target class with the specified name and parameter types cannot be found - * @see DataType#getPrimitive(Class[]) - * @see DataType#compare(Class[], Class[]) - */ - public static Method getMethod(Class clazz, String methodName, Class... parameterTypes) throws NoSuchMethodException { - Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); - for (Method method : clazz.getMethods()) { - if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) { - continue; - } - return method; - } - throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types"); - } + /** + * Returns a method of a class with the given parameter types + * + * @param clazz Target class + * @param methodName Name of the desired method + * @param parameterTypes Parameter types of the desired method + * @return The method of the target class with the specified name and parameter types + * @throws NoSuchMethodException If the desired method of the target class with the specified name and parameter types cannot be found + * @see DataType#getPrimitive(Class[]) + * @see DataType#compare(Class[], Class[]) + */ + public static Method getMethod(Class clazz, String methodName, Class... parameterTypes) throws NoSuchMethodException { + Class[] primitiveTypes = DataType.getPrimitive(parameterTypes); + for (Method method : clazz.getMethods()) { + if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) { + continue; + } + return method; + } + throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types"); + } - /** - * Returns a method of a desired class with the given parameter types - * - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param methodName Name of the desired method - * @param parameterTypes Parameter types of the desired method - * @return The method of the desired target class with the specified name and parameter types - * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and parameter types cannot be found - * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass() (String, PackageType) - * @see #getMethod(Class, String, Class...) - */ - public static Method getMethod(String className, PackageType packageType, String methodName, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { - return getMethod(packageType.getClass(className), methodName, parameterTypes); - } + /** + * Returns a method of a desired class with the given parameter types + * + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param methodName Name of the desired method + * @param parameterTypes Parameter types of the desired method + * @return The method of the desired target class with the specified name and parameter types + * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and parameter types cannot be found + * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #getClass() (String, PackageType) + * @see #getMethod(Class, String, Class...) + */ + public static Method getMethod(String className, PackageType packageType, String methodName, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { + return getMethod(packageType.getClass(className), methodName, parameterTypes); + } - /** - * Invokes a method on an object with the given arguments - * - * @param instance Target object - * @param methodName Name of the desired method - * @param arguments Arguments which are used to invoke the desired method - * @return The result of invoking the desired method on the target object - * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances - * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) - * @throws InvocationTargetException If the desired method cannot be invoked on the target object - * @throws NoSuchMethodException If the desired method of the class of the target object with the specified name and arguments cannot be found - * @see #getMethod(Class, String, Class...) - * @see DataType#getPrimitive(Object[]) - */ - public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { - return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); - } + /** + * Invokes a method on an object with the given arguments + * + * @param instance Target object + * @param methodName Name of the desired method + * @param arguments Arguments which are used to invoke the desired method + * @return The result of invoking the desired method on the target object + * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances + * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) + * @throws InvocationTargetException If the desired method cannot be invoked on the target object + * @throws NoSuchMethodException If the desired method of the class of the target object with the specified name and arguments cannot be found + * @see #getMethod(Class, String, Class...) + * @see DataType#getPrimitive(Object[]) + */ + public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); + } - /** - * Invokes a method of the target class on an object with the given arguments - * - * @param instance Target object - * @param clazz Target class - * @param methodName Name of the desired method - * @param arguments Arguments which are used to invoke the desired method - * @return The result of invoking the desired method on the target object - * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances - * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) - * @throws InvocationTargetException If the desired method cannot be invoked on the target object - * @throws NoSuchMethodException If the desired method of the target class with the specified name and arguments cannot be found - * @see #getMethod(Class, String, Class...) - * @see DataType#getPrimitive(Object[]) - */ - public static Object invokeMethod(Object instance, Class clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { - return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); - } + /** + * Invokes a method of the target class on an object with the given arguments + * + * @param instance Target object + * @param clazz Target class + * @param methodName Name of the desired method + * @param arguments Arguments which are used to invoke the desired method + * @return The result of invoking the desired method on the target object + * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances + * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) + * @throws InvocationTargetException If the desired method cannot be invoked on the target object + * @throws NoSuchMethodException If the desired method of the target class with the specified name and arguments cannot be found + * @see #getMethod(Class, String, Class...) + * @see DataType#getPrimitive(Object[]) + */ + public static Object invokeMethod(Object instance, Class clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { + return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); + } - /** - * Invokes a method of a desired class on an object with the given arguments - * - * @param instance Target object - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param methodName Name of the desired method - * @param arguments Arguments which are used to invoke the desired method - * @return The result of invoking the desired method on the target object - * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances - * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) - * @throws InvocationTargetException If the desired method cannot be invoked on the target object - * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and arguments cannot be found - * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getClass() (String, PackageType) - * @see #invokeMethod(Object, Class, String, Object...) - */ - public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { - return invokeMethod(instance, packageType.getClass(className), methodName, arguments); - } + /** + * Invokes a method of a desired class on an object with the given arguments + * + * @param instance Target object + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param methodName Name of the desired method + * @param arguments Arguments which are used to invoke the desired method + * @return The result of invoking the desired method on the target object + * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances + * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) + * @throws InvocationTargetException If the desired method cannot be invoked on the target object + * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and arguments cannot be found + * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #getClass() (String, PackageType) + * @see #invokeMethod(Object, Class, String, Object...) + */ + public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + return invokeMethod(instance, packageType.getClass(className), methodName, arguments); + } - /** - * Returns a field of the target class with the given name - * - * @param clazz Target class - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @return The field of the target class with the specified name - * @throws NoSuchFieldException If the desired field of the given class cannot be found - * @throws SecurityException If the desired field cannot be made accessible - */ - public static Field getField(Class clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { - Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); - field.setAccessible(true); - return field; - } + /** + * Returns a field of the target class with the given name + * + * @param clazz Target class + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @return The field of the target class with the specified name + * @throws NoSuchFieldException If the desired field of the given class cannot be found + * @throws SecurityException If the desired field cannot be made accessible + */ + public static Field getField(Class clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { + Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); + field.setAccessible(true); + return field; + } - /** - * Returns a field of a desired class with the given name - * - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @return The field of the desired target class with the specified name - * @throws NoSuchFieldException If the desired field of the desired class cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getField(Class, boolean, String) - */ - public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { - return getField(packageType.getClass(className), declared, fieldName); - } + /** + * Returns a field of a desired class with the given name + * + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @return The field of the desired target class with the specified name + * @throws NoSuchFieldException If the desired field of the desired class cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #getField(Class, boolean, String) + */ + public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { + return getField(packageType.getClass(className), declared, fieldName); + } - /** - * Returns the value of a field of the given class of an object - * - * @param instance Target object - * @param clazz Target class - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @return The value of field of the target object - * @throws IllegalArgumentException If the target object does not feature the desired field - * @throws IllegalAccessException If the desired field cannot be accessed - * @throws NoSuchFieldException If the desired field of the target class cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @see #getField(Class, boolean, String) - */ - public static Object getValue(Object instance, Class clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - return getField(clazz, declared, fieldName).get(instance); - } + /** + * Returns the value of a field of the given class of an object + * + * @param instance Target object + * @param clazz Target class + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @return The value of field of the target object + * @throws IllegalArgumentException If the target object does not feature the desired field + * @throws IllegalAccessException If the desired field cannot be accessed + * @throws NoSuchFieldException If the desired field of the target class cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @see #getField(Class, boolean, String) + */ + public static Object getValue(Object instance, Class clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + return getField(clazz, declared, fieldName).get(instance); + } - /** - * Returns the value of a field of a desired class of an object - * - * @param instance Target object - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @return The value of field of the target object - * @throws IllegalArgumentException If the target object does not feature the desired field - * @throws IllegalAccessException If the desired field cannot be accessed - * @throws NoSuchFieldException If the desired field of the desired class cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #getValue(Object, Class, boolean, String) - */ - public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { - return getValue(instance, packageType.getClass(className), declared, fieldName); - } + /** + * Returns the value of a field of a desired class of an object + * + * @param instance Target object + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @return The value of field of the target object + * @throws IllegalArgumentException If the target object does not feature the desired field + * @throws IllegalAccessException If the desired field cannot be accessed + * @throws NoSuchFieldException If the desired field of the desired class cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #getValue(Object, Class, boolean, String) + */ + public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { + return getValue(instance, packageType.getClass(className), declared, fieldName); + } - /** - * Returns the value of a field with the given name of an object - * - * @param instance Target object - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @return The value of field of the target object - * @throws IllegalArgumentException If the target object does not feature the desired field (should not occur since it searches for a field with the given name in the class of the object) - * @throws IllegalAccessException If the desired field cannot be accessed - * @throws NoSuchFieldException If the desired field of the target object cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @see #getValue(Object, Class, boolean, String) - */ - public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - return getValue(instance, instance.getClass(), declared, fieldName); - } + /** + * Returns the value of a field with the given name of an object + * + * @param instance Target object + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @return The value of field of the target object + * @throws IllegalArgumentException If the target object does not feature the desired field (should not occur since it searches for a field with the given name in the class of the object) + * @throws IllegalAccessException If the desired field cannot be accessed + * @throws NoSuchFieldException If the desired field of the target object cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @see #getValue(Object, Class, boolean, String) + */ + public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + return getValue(instance, instance.getClass(), declared, fieldName); + } - /** - * Sets the value of a field of the given class of an object - * - * @param instance Target object - * @param clazz Target class - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @param value New value - * @throws IllegalArgumentException If the type of the value does not match the type of the desired field - * @throws IllegalAccessException If the desired field cannot be accessed - * @throws NoSuchFieldException If the desired field of the target class cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @see #getField(Class, boolean, String) - */ - public static void setValue(Object instance, Class clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - getField(clazz, declared, fieldName).set(instance, value); - } + /** + * Sets the value of a field of the given class of an object + * + * @param instance Target object + * @param clazz Target class + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @param value New value + * @throws IllegalArgumentException If the type of the value does not match the type of the desired field + * @throws IllegalAccessException If the desired field cannot be accessed + * @throws NoSuchFieldException If the desired field of the target class cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @see #getField(Class, boolean, String) + */ + public static void setValue(Object instance, Class clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + getField(clazz, declared, fieldName).set(instance, value); + } - /** - * Sets the value of a field of a desired class of an object - * - * @param instance Target object - * @param className Name of the desired target class - * @param packageType Package where the desired target class is located - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @param value New value - * @throws IllegalArgumentException If the type of the value does not match the type of the desired field - * @throws IllegalAccessException If the desired field cannot be accessed - * @throws NoSuchFieldException If the desired field of the desired class cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found - * @see #setValue(Object, Class, boolean, String, Object) - */ - public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { - setValue(instance, packageType.getClass(className), declared, fieldName, value); - } + /** + * Sets the value of a field of a desired class of an object + * + * @param instance Target object + * @param className Name of the desired target class + * @param packageType Package where the desired target class is located + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @param value New value + * @throws IllegalArgumentException If the type of the value does not match the type of the desired field + * @throws IllegalAccessException If the desired field cannot be accessed + * @throws NoSuchFieldException If the desired field of the desired class cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found + * @see #setValue(Object, Class, boolean, String, Object) + */ + public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { + setValue(instance, packageType.getClass(className), declared, fieldName, value); + } - /** - * Sets the value of a field with the given name of an object - * - * @param instance Target object - * @param declared Whether the desired field is declared or not - * @param fieldName Name of the desired field - * @param value New value - * @throws IllegalArgumentException If the type of the value does not match the type of the desired field - * @throws IllegalAccessException If the desired field cannot be accessed - * @throws NoSuchFieldException If the desired field of the target object cannot be found - * @throws SecurityException If the desired field cannot be made accessible - * @see #setValue(Object, Class, boolean, String, Object) - */ - public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { - setValue(instance, instance.getClass(), declared, fieldName, value); - } + /** + * Sets the value of a field with the given name of an object + * + * @param instance Target object + * @param declared Whether the desired field is declared or not + * @param fieldName Name of the desired field + * @param value New value + * @throws IllegalArgumentException If the type of the value does not match the type of the desired field + * @throws IllegalAccessException If the desired field cannot be accessed + * @throws NoSuchFieldException If the desired field of the target object cannot be found + * @throws SecurityException If the desired field cannot be made accessible + * @see #setValue(Object, Class, boolean, String, Object) + */ + public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { + setValue(instance, instance.getClass(), declared, fieldName, value); + } - /** - * Represents an enumeration of dynamic packages of NMS and CraftBukkit - *

- * This class is part of the ReflectionUtils and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.0 - */ - public enum PackageType { - MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()), - CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()), - CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"), - CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"), - CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"), - CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"), - CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"), - CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"), - CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"), - CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"), - CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"), - CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"), - CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"), - CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"), - CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"), - CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"), - CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"), - CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"), - CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"), - CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util"); + /** + * Represents an enumeration of dynamic packages of NMS and CraftBukkit + *

+ * This class is part of the ReflectionUtils and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.0 + */ + public enum PackageType { + MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()), + CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()), + CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"), + CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"), + CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"), + CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"), + CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"), + CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"), + CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"), + CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"), + CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"), + CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"), + CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"), + CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"), + CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"), + CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"), + CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"), + CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"), + CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"), + CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util"); - private final String path; + private final String path; - /** - * Construct a new package type - * - * @param path Path of the package - */ - PackageType(String path) { - this.path = path; - } + /** + * Construct a new package type + * + * @param path Path of the package + */ + PackageType(String path) { + this.path = path; + } - /** - * Construct a new package type - * - * @param parent Parent package of the package - * @param path Path of the package - */ - PackageType(PackageType parent, String path) { - this(parent + "." + path); - } + /** + * Construct a new package type + * + * @param parent Parent package of the package + * @param path Path of the package + */ + PackageType(PackageType parent, String path) { + this(parent + "." + path); + } - /** - * Returns the version of your server - * - * @return The server version - */ - public static String getServerVersion() { - return Bukkit.getServer().getClass().getName().split("\\.")[3]; - } + /** + * Returns the version of your server + * + * @return The server version + */ + public static String getServerVersion() { + return Bukkit.getServer().getClass().getName().split("\\.")[3]; + } - /** - * Returns the path of this package type - * - * @return The path - */ - public String getPath() { - return path; - } + /** + * Returns the path of this package type + * + * @return The path + */ + public String getPath() { + return path; + } - /** - * Returns the class with the given name - * - * @param className Name of the desired class - * @return The class with the specified name - * @throws ClassNotFoundException If the desired class with the specified name and package cannot be found - */ - public Class getClass(String className) throws ClassNotFoundException { - return Class.forName(this + "." + className); - } + /** + * Returns the class with the given name + * + * @param className Name of the desired class + * @return The class with the specified name + * @throws ClassNotFoundException If the desired class with the specified name and package cannot be found + */ + public Class getClass(String className) throws ClassNotFoundException { + return Class.forName(this + "." + className); + } - // Override for convenience - @Override - public String toString() { - return path; - } - } + // Override for convenience + @Override + public String toString() { + return path; + } + } - /** - * Represents an enumeration of Java data types with corresponding classes - *

- * This class is part of the ReflectionUtils and follows the same usage conditions - * - * @author DarkBlade12 - * @since 1.0 - */ - public enum DataType { - BYTE(byte.class, Byte.class), - SHORT(short.class, Short.class), - INTEGER(int.class, Integer.class), - LONG(long.class, Long.class), - CHARACTER(char.class, Character.class), - FLOAT(float.class, Float.class), - DOUBLE(double.class, Double.class), - BOOLEAN(boolean.class, Boolean.class); + /** + * Represents an enumeration of Java data types with corresponding classes + *

+ * This class is part of the ReflectionUtils and follows the same usage conditions + * + * @author DarkBlade12 + * @since 1.0 + */ + public enum DataType { + BYTE(byte.class, Byte.class), + SHORT(short.class, Short.class), + INTEGER(int.class, Integer.class), + LONG(long.class, Long.class), + CHARACTER(char.class, Character.class), + FLOAT(float.class, Float.class), + DOUBLE(double.class, Double.class), + BOOLEAN(boolean.class, Boolean.class); - private static final Map, DataType> CLASS_MAP = new HashMap, DataType>(); + private static final Map, DataType> CLASS_MAP = new HashMap, DataType>(); - // Initialize map for quick class lookup - static { - for (DataType type : values()) { - CLASS_MAP.put(type.primitive, type); - CLASS_MAP.put(type.reference, type); - } - } + // Initialize map for quick class lookup + static { + for (DataType type : values()) { + CLASS_MAP.put(type.primitive, type); + CLASS_MAP.put(type.reference, type); + } + } - private final Class primitive; - private final Class reference; + private final Class primitive; + private final Class reference; - /** - * Construct a new data type - * - * @param primitive Primitive class of this data type - * @param reference Reference class of this data type - */ - DataType(Class primitive, Class reference) { - this.primitive = primitive; - this.reference = reference; - } + /** + * Construct a new data type + * + * @param primitive Primitive class of this data type + * @param reference Reference class of this data type + */ + DataType(Class primitive, Class reference) { + this.primitive = primitive; + this.reference = reference; + } - /** - * Returns the data type with the given primitive/reference class - * - * @param clazz Primitive/Reference class of the data type - * @return The data type - */ - public static DataType fromClass(Class clazz) { - return CLASS_MAP.get(clazz); - } + /** + * Returns the data type with the given primitive/reference class + * + * @param clazz Primitive/Reference class of the data type + * @return The data type + */ + public static DataType fromClass(Class clazz) { + return CLASS_MAP.get(clazz); + } - /** - * Returns the primitive class of the data type with the given reference class - * - * @param clazz Reference class of the data type - * @return The primitive class - */ - public static Class getPrimitive(Class clazz) { - DataType type = fromClass(clazz); - return type == null ? clazz : type.getPrimitive(); - } + /** + * Returns the primitive class of the data type with the given reference class + * + * @param clazz Reference class of the data type + * @return The primitive class + */ + public static Class getPrimitive(Class clazz) { + DataType type = fromClass(clazz); + return type == null ? clazz : type.getPrimitive(); + } - /** - * Returns the reference class of the data type with the given primitive class - * - * @param clazz Primitive class of the data type - * @return The reference class - */ - public static Class getReference(Class clazz) { - DataType type = fromClass(clazz); - return type == null ? clazz : type.getReference(); - } + /** + * Returns the reference class of the data type with the given primitive class + * + * @param clazz Primitive class of the data type + * @return The reference class + */ + public static Class getReference(Class clazz) { + DataType type = fromClass(clazz); + return type == null ? clazz : type.getReference(); + } - /** - * Returns the primitive class array of the given class array - * - * @param classes Given class array - * @return The primitive class array - */ - public static Class[] getPrimitive(Class[] classes) { - int length = classes == null ? 0 : classes.length; - Class[] types = new Class[length]; - for (int index = 0; index < length; index++) { - types[index] = getPrimitive(classes[index]); - } - return types; - } + /** + * Returns the primitive class array of the given class array + * + * @param classes Given class array + * @return The primitive class array + */ + public static Class[] getPrimitive(Class[] classes) { + int length = classes == null ? 0 : classes.length; + Class[] types = new Class[length]; + for (int index = 0; index < length; index++) { + types[index] = getPrimitive(classes[index]); + } + return types; + } - /** - * Returns the reference class array of the given class array - * - * @param classes Given class array - * @return The reference class array - */ - public static Class[] getReference(Class[] classes) { - int length = classes == null ? 0 : classes.length; - Class[] types = new Class[length]; - for (int index = 0; index < length; index++) { - types[index] = getReference(classes[index]); - } - return types; - } + /** + * Returns the reference class array of the given class array + * + * @param classes Given class array + * @return The reference class array + */ + public static Class[] getReference(Class[] classes) { + int length = classes == null ? 0 : classes.length; + Class[] types = new Class[length]; + for (int index = 0; index < length; index++) { + types[index] = getReference(classes[index]); + } + return types; + } - /** - * Returns the primitive class array of the given object array - * - * @param objects Given object array - * @return The primitive class array - */ - public static Class[] getPrimitive(Object[] objects) { - int length = objects == null ? 0 : objects.length; - Class[] types = new Class[length]; - for (int index = 0; index < length; index++) { - types[index] = getPrimitive(objects[index].getClass()); - } - return types; - } + /** + * Returns the primitive class array of the given object array + * + * @param objects Given object array + * @return The primitive class array + */ + public static Class[] getPrimitive(Object[] objects) { + int length = objects == null ? 0 : objects.length; + Class[] types = new Class[length]; + for (int index = 0; index < length; index++) { + types[index] = getPrimitive(objects[index].getClass()); + } + return types; + } - /** - * Returns the reference class array of the given object array - * - * @param objects Given object array - * @return The reference class array - */ - public static Class[] getReference(Object[] objects) { - int length = objects == null ? 0 : objects.length; - Class[] types = new Class[length]; - for (int index = 0; index < length; index++) { - types[index] = getReference(objects[index].getClass()); - } - return types; - } + /** + * Returns the reference class array of the given object array + * + * @param objects Given object array + * @return The reference class array + */ + public static Class[] getReference(Object[] objects) { + int length = objects == null ? 0 : objects.length; + Class[] types = new Class[length]; + for (int index = 0; index < length; index++) { + types[index] = getReference(objects[index].getClass()); + } + return types; + } - /** - * Compares two class arrays on equivalence - * - * @param primary Primary class array - * @param secondary Class array which is compared to the primary array - * @return Whether these arrays are equal or not - */ - public static boolean compare(Class[] primary, Class[] secondary) { - if (primary == null || secondary == null || primary.length != secondary.length) { - return false; - } - for (int index = 0; index < primary.length; index++) { - Class primaryClass = primary[index]; - Class secondaryClass = secondary[index]; - if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) { - continue; - } - return false; - } - return true; - } + /** + * Compares two class arrays on equivalence + * + * @param primary Primary class array + * @param secondary Class array which is compared to the primary array + * @return Whether these arrays are equal or not + */ + public static boolean compare(Class[] primary, Class[] secondary) { + if (primary == null || secondary == null || primary.length != secondary.length) { + return false; + } + for (int index = 0; index < primary.length; index++) { + Class primaryClass = primary[index]; + Class secondaryClass = secondary[index]; + if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) { + continue; + } + return false; + } + return true; + } - /** - * Returns the primitive class of this data type - * - * @return The primitive class - */ - public Class getPrimitive() { - return primitive; - } + /** + * Returns the primitive class of this data type + * + * @return The primitive class + */ + public Class getPrimitive() { + return primitive; + } - /** - * Returns the reference class of this data type - * - * @return The reference class - */ - public Class getReference() { - return reference; - } - } + /** + * Returns the reference class of this data type + * + * @return The reference class + */ + public Class getReference() { + return reference; + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/util/PermissionsMapTypeAdapter.java b/src/main/java/com/massivecraft/factions/util/PermissionsMapTypeAdapter.java index aeb8de97..efd66b29 100644 --- a/src/main/java/com/massivecraft/factions/util/PermissionsMapTypeAdapter.java +++ b/src/main/java/com/massivecraft/factions/util/PermissionsMapTypeAdapter.java @@ -17,82 +17,82 @@ import java.util.logging.Level; public class PermissionsMapTypeAdapter implements JsonDeserializer>> { - @Override - public Map> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { + @Override + public Map> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { - try { - JsonObject obj = json.getAsJsonObject(); - if (obj == null) { - return null; - } + try { + JsonObject obj = json.getAsJsonObject(); + if (obj == null) { + return null; + } - Map> permissionsMap = new ConcurrentHashMap<>(); + Map> permissionsMap = new ConcurrentHashMap<>(); - // Top level is Relation - for (Map.Entry entry : obj.entrySet()) { - Permissable permissable = getPermissable(entry.getKey()); + // Top level is Relation + for (Map.Entry entry : obj.entrySet()) { + Permissable permissable = getPermissable(entry.getKey()); - if (permissable == null) { - continue; - } + if (permissable == null) { + continue; + } - // Second level is the map between action -> access - Map accessMap = new HashMap<>(); - for (Map.Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { - PermissableAction permissableAction = PermissableAction.fromString(entry2.getKey()); - if (permissableAction == null) { - switch (entry2.getKey()) { - case "frostwalk": - permissableAction = PermissableAction.FROST_WALK; - break; - case "painbuild": - permissableAction = PermissableAction.PAIN_BUILD; - break; - case "items": - permissableAction = PermissableAction.ITEM; - break; - } - } - Access access = Access.fromString(entry2.getValue().getAsString()); - accessMap.put(permissableAction, access); - } - permissionsMap.put(permissable, accessMap); - } + // Second level is the map between action -> access + Map accessMap = new HashMap<>(); + for (Map.Entry entry2 : entry.getValue().getAsJsonObject().entrySet()) { + PermissableAction permissableAction = PermissableAction.fromString(entry2.getKey()); + if (permissableAction == null) { + switch (entry2.getKey()) { + case "frostwalk": + permissableAction = PermissableAction.FROST_WALK; + break; + case "painbuild": + permissableAction = PermissableAction.PAIN_BUILD; + break; + case "items": + permissableAction = PermissableAction.ITEM; + break; + } + } + Access access = Access.fromString(entry2.getValue().getAsString()); + accessMap.put(permissableAction, access); + } + permissionsMap.put(permissable, accessMap); + } - return permissionsMap; + return permissionsMap; - } catch (Exception ex) { - SavageFactions.plugin.log(Level.WARNING, "Error encountered while deserializing a PermissionsMap."); - ex.printStackTrace(); - return null; - } - } + } catch (Exception ex) { + SavageFactions.plugin.log(Level.WARNING, "Error encountered while deserializing a PermissionsMap."); + ex.printStackTrace(); + return null; + } + } - private Permissable getPermissable(String name) { - // If name is uppercase then it is (probably, no way to completely know) valid if not begin conversion - if (name.equals(name.toUpperCase())) { - if (Role.fromString(name.toUpperCase()) != null) { - return Role.fromString(name.toUpperCase()); - } else if (Relation.fromString(name.toUpperCase()) != null) { - return Relation.fromString(name.toUpperCase()); - } else { - return null; - } - } else { - if (name.equals(TL.ROLE_RECRUIT.toString())) { - return Role.RECRUIT; - } else if (name.equals(TL.ROLE_NORMAL.toString())) { - return Role.NORMAL; - } else if (name.equals(TL.ROLE_MODERATOR.toString())) { - return Role.MODERATOR; - } else { - // If it is explicitly member and its old data then it refers to relation member not role, skip it - if (name.equals("member")) { - return null; - } - return Relation.fromString(name); - } - } - } + private Permissable getPermissable(String name) { + // If name is uppercase then it is (probably, no way to completely know) valid if not begin conversion + if (name.equals(name.toUpperCase())) { + if (Role.fromString(name.toUpperCase()) != null) { + return Role.fromString(name.toUpperCase()); + } else if (Relation.fromString(name.toUpperCase()) != null) { + return Relation.fromString(name.toUpperCase()); + } else { + return null; + } + } else { + if (name.equals(TL.ROLE_RECRUIT.toString())) { + return Role.RECRUIT; + } else if (name.equals(TL.ROLE_NORMAL.toString())) { + return Role.NORMAL; + } else if (name.equals(TL.ROLE_MODERATOR.toString())) { + return Role.MODERATOR; + } else { + // If it is explicitly member and its old data then it refers to relation member not role, skip it + if (name.equals("member")) { + return null; + } + return Relation.fromString(name); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/util/RelationUtil.java b/src/main/java/com/massivecraft/factions/util/RelationUtil.java index 4c656f84..0912b81c 100644 --- a/src/main/java/com/massivecraft/factions/util/RelationUtil.java +++ b/src/main/java/com/massivecraft/factions/util/RelationUtil.java @@ -11,101 +11,101 @@ import org.bukkit.ChatColor; public class RelationUtil { - public static String describeThatToMe(RelationParticipator that, RelationParticipator me, boolean ucfirst) { - String ret = ""; + public static String describeThatToMe(RelationParticipator that, RelationParticipator me, boolean ucfirst) { + String ret = ""; - Faction thatFaction = getFaction(that); - if (thatFaction == null) { - return "ERROR"; // ERROR - } + Faction thatFaction = getFaction(that); + if (thatFaction == null) { + return "ERROR"; // ERROR + } - Faction myFaction = getFaction(me); + Faction myFaction = getFaction(me); // if (myFaction == null) return that.describeTo(null); // no relation, but can show basic name or tag - if (that instanceof Faction) { - if (me instanceof FPlayer && myFaction == thatFaction) { - ret = TL.GENERIC_YOURFACTION.toString(); - } else { - ret = thatFaction.getTag(); - } - } else if (that instanceof FPlayer) { - FPlayer fplayerthat = (FPlayer) that; - if (that == me) { - ret = TL.GENERIC_YOU.toString(); - } else if (thatFaction == myFaction) { - ret = fplayerthat.getNameAndTitle(); - } else { - ret = fplayerthat.getNameAndTag(); - } - } + if (that instanceof Faction) { + if (me instanceof FPlayer && myFaction == thatFaction) { + ret = TL.GENERIC_YOURFACTION.toString(); + } else { + ret = thatFaction.getTag(); + } + } else if (that instanceof FPlayer) { + FPlayer fplayerthat = (FPlayer) that; + if (that == me) { + ret = TL.GENERIC_YOU.toString(); + } else if (thatFaction == myFaction) { + ret = fplayerthat.getNameAndTitle(); + } else { + ret = fplayerthat.getNameAndTag(); + } + } - if (ucfirst) { - ret = TextUtil.upperCaseFirst(ret); - } + if (ucfirst) { + ret = TextUtil.upperCaseFirst(ret); + } - return "" + getColorOfThatToMe(that, me) + ret; - } + return "" + getColorOfThatToMe(that, me) + ret; + } - public static String describeThatToMe(RelationParticipator that, RelationParticipator me) { - return describeThatToMe(that, me, false); - } + public static String describeThatToMe(RelationParticipator that, RelationParticipator me) { + return describeThatToMe(that, me, false); + } - public static Relation getRelationTo(RelationParticipator me, RelationParticipator that) { - return getRelationTo(that, me, false); - } + public static Relation getRelationTo(RelationParticipator me, RelationParticipator that) { + return getRelationTo(that, me, false); + } - public static Relation getRelationTo(RelationParticipator me, RelationParticipator that, boolean ignorePeaceful) { - Faction fthat = getFaction(that); - Faction fme = getFaction(me); + public static Relation getRelationTo(RelationParticipator me, RelationParticipator that, boolean ignorePeaceful) { + Faction fthat = getFaction(that); + Faction fme = getFaction(me); - if (fthat == null || fme == null) { - return Relation.NEUTRAL; // ERROR - } + if (fthat == null || fme == null) { + return Relation.NEUTRAL; // ERROR + } - if (!fthat.isNormal() || !fme.isNormal()) { - return Relation.NEUTRAL; - } + if (!fthat.isNormal() || !fme.isNormal()) { + return Relation.NEUTRAL; + } - if (fthat.equals(fme)) { - return Relation.MEMBER; - } + if (fthat.equals(fme)) { + return Relation.MEMBER; + } - if (!ignorePeaceful && (fme.isPeaceful() || fthat.isPeaceful())) { - return Relation.NEUTRAL; - } + if (!ignorePeaceful && (fme.isPeaceful() || fthat.isPeaceful())) { + return Relation.NEUTRAL; + } - if (fme.getRelationWish(fthat).value >= fthat.getRelationWish(fme).value) { - return fthat.getRelationWish(fme); - } + if (fme.getRelationWish(fthat).value >= fthat.getRelationWish(fme).value) { + return fthat.getRelationWish(fme); + } - return fme.getRelationWish(fthat); - } + return fme.getRelationWish(fthat); + } - public static Faction getFaction(RelationParticipator rp) { - if (rp instanceof Faction) { - return (Faction) rp; - } + public static Faction getFaction(RelationParticipator rp) { + if (rp instanceof Faction) { + return (Faction) rp; + } - if (rp instanceof FPlayer) { - return ((FPlayer) rp).getFaction(); - } + if (rp instanceof FPlayer) { + return ((FPlayer) rp).getFaction(); + } - // ERROR - return null; - } + // ERROR + return null; + } - public static ChatColor getColorOfThatToMe(RelationParticipator that, RelationParticipator me) { - Faction thatFaction = getFaction(that); + public static ChatColor getColorOfThatToMe(RelationParticipator that, RelationParticipator me) { + Faction thatFaction = getFaction(that); - if (thatFaction != null && thatFaction != getFaction(me)) { - if (thatFaction.isPeaceful()) - return Conf.colorPeaceful; - else if (thatFaction.isSafeZone()) - return Conf.colorPeaceful; - else if (thatFaction.isWarZone()) - return Conf.colorWar; - } + if (thatFaction != null && thatFaction != getFaction(me)) { + if (thatFaction.isPeaceful()) + return Conf.colorPeaceful; + else if (thatFaction.isSafeZone()) + return Conf.colorPeaceful; + else if (thatFaction.isWarZone()) + return Conf.colorWar; + } - return getRelationTo(that, me).getColor(); - } + return getRelationTo(that, me).getColor(); + } } diff --git a/src/main/java/com/massivecraft/factions/util/SpiralTask.java b/src/main/java/com/massivecraft/factions/util/SpiralTask.java index 1124bf8b..1b209fd4 100644 --- a/src/main/java/com/massivecraft/factions/util/SpiralTask.java +++ b/src/main/java/com/massivecraft/factions/util/SpiralTask.java @@ -24,186 +24,186 @@ import java.util.logging.Level; public abstract class SpiralTask implements Runnable { - // general task-related reference data - private transient World world = null; - private transient boolean readyToGo = false; - private transient int taskID = -1; - private transient int limit = 0; + // general task-related reference data + private transient World world = null; + private transient boolean readyToGo = false; + private transient int taskID = -1; + private transient int limit = 0; - // values for the spiral pattern routine - private transient int x = 0; - private transient int z = 0; - private transient boolean isZLeg = false; - private transient boolean isNeg = false; - private transient int length = -1; - private transient int current = 0; + // values for the spiral pattern routine + private transient int x = 0; + private transient int z = 0; + private transient boolean isZLeg = false; + private transient boolean isNeg = false; + private transient int length = -1; + private transient int current = 0; - @SuppressWarnings("LeakingThisInConstructor") - public SpiralTask(FLocation fLocation, int radius) { - // limit is determined based on spiral leg length for given radius; see insideRadius() - this.limit = (radius - 1) * 2; + @SuppressWarnings("LeakingThisInConstructor") + public SpiralTask(FLocation fLocation, int radius) { + // limit is determined based on spiral leg length for given radius; see insideRadius() + this.limit = (radius - 1) * 2; - this.world = Bukkit.getWorld(fLocation.getWorldName()); - if (this.world == null) { - SavageFactions.plugin.log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); - this.stop(); - return; - } + this.world = Bukkit.getWorld(fLocation.getWorldName()); + if (this.world == null) { + SavageFactions.plugin.log(Level.WARNING, "[SpiralTask] A valid world must be specified!"); + this.stop(); + return; + } - this.x = (int) fLocation.getX(); - this.z = (int) fLocation.getZ(); + this.x = (int) fLocation.getX(); + this.z = (int) fLocation.getZ(); - this.readyToGo = true; + this.readyToGo = true; - // get this party started - this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, this, 2, 2)); - } + // get this party started + this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, this, 2, 2)); + } - private static long now() { - return System.currentTimeMillis(); - } + private static long now() { + return System.currentTimeMillis(); + } - /* - * This is where the necessary work is done; you'll need to override this method with whatever you want - * done at each chunk in the spiral pattern. - * Return false if the entire task needs to be aborted, otherwise return true to continue. - */ - public abstract boolean work(); + /* + * This is where the necessary work is done; you'll need to override this method with whatever you want + * done at each chunk in the spiral pattern. + * Return false if the entire task needs to be aborted, otherwise return true to continue. + */ + public abstract boolean work(); - /* - * Returns an FLocation pointing at the current chunk X and Z values. - */ - public final FLocation currentFLocation() { - return new FLocation(world.getName(), x, z); - } + /* + * Returns an FLocation pointing at the current chunk X and Z values. + */ + public final FLocation currentFLocation() { + return new FLocation(world.getName(), x, z); + } - /* - * Returns a Location pointing at the current chunk X and Z values. - * note that the Location is at the corner of the chunk, not the center. - */ - public final Location currentLocation() { - return new Location(world, FLocation.chunkToBlock(x), 65.0, FLocation.chunkToBlock(z)); - } + /* + * Returns a Location pointing at the current chunk X and Z values. + * note that the Location is at the corner of the chunk, not the center. + */ + public final Location currentLocation() { + return new Location(world, FLocation.chunkToBlock(x), 65.0, FLocation.chunkToBlock(z)); + } - /* - * Returns current chunk X and Z values. - */ - public final int getX() { - return x; - } + /* + * Returns current chunk X and Z values. + */ + public final int getX() { + return x; + } - /* - * Below are the guts of the class, which you normally wouldn't need to mess with. - */ + /* + * Below are the guts of the class, which you normally wouldn't need to mess with. + */ - public final int getZ() { - return z; - } + public final int getZ() { + return z; + } - public final void setTaskID(int ID) { - if (ID == -1) { - this.stop(); - } - taskID = ID; - } + public final void setTaskID(int ID) { + if (ID == -1) { + this.stop(); + } + taskID = ID; + } - public final void run() { - if (!this.valid() || !readyToGo) { - return; - } + public final void run() { + if (!this.valid() || !readyToGo) { + return; + } - // this is set so it only does one iteration at a time, no matter how frequently the timer fires - readyToGo = false; + // this is set so it only does one iteration at a time, no matter how frequently the timer fires + readyToGo = false; - // make sure we're still inside the specified radius - if (!this.insideRadius()) { - return; - } + // make sure we're still inside the specified radius + if (!this.insideRadius()) { + return; + } - // track this to keep one iteration from dragging on too long and possibly choking the system - long loopStartTime = now(); + // track this to keep one iteration from dragging on too long and possibly choking the system + long loopStartTime = now(); - // keep going until the task has been running for 20ms or more, then stop to take a breather - while (now() < loopStartTime + 20) { - // run the primary task on the current X/Z coordinates - if (!this.work()) { - this.finish(); - return; - } + // keep going until the task has been running for 20ms or more, then stop to take a breather + while (now() < loopStartTime + 20) { + // run the primary task on the current X/Z coordinates + if (!this.work()) { + this.finish(); + return; + } - // move on to next chunk in spiral - if (!this.moveToNext()) { - return; - } - } + // move on to next chunk in spiral + if (!this.moveToNext()) { + return; + } + } - // ready for the next iteration to run - readyToGo = true; - } + // ready for the next iteration to run + readyToGo = true; + } - // step through chunks in spiral pattern from center; returns false if we're done, otherwise returns true - public final boolean moveToNext() { - if (!this.valid()) { - return false; - } + // step through chunks in spiral pattern from center; returns false if we're done, otherwise returns true + public final boolean moveToNext() { + if (!this.valid()) { + return false; + } - // make sure we don't need to turn down the next leg of the spiral - if (current < length) { - current++; + // make sure we don't need to turn down the next leg of the spiral + if (current < length) { + current++; - // if we're outside the radius, we're done - if (!this.insideRadius()) { - return false; - } - } else { // one leg/side of the spiral down... - current = 0; - isZLeg ^= true; - // every second leg (between X and Z legs, negative or positive), length increases - if (isZLeg) { - isNeg ^= true; - length++; - } - } + // if we're outside the radius, we're done + if (!this.insideRadius()) { + return false; + } + } else { // one leg/side of the spiral down... + current = 0; + isZLeg ^= true; + // every second leg (between X and Z legs, negative or positive), length increases + if (isZLeg) { + isNeg ^= true; + length++; + } + } - // move one chunk further in the appropriate direction - if (isZLeg) { - z += (isNeg) ? -1 : 1; - } else { - x += (isNeg) ? -1 : 1; - } + // move one chunk further in the appropriate direction + if (isZLeg) { + z += (isNeg) ? -1 : 1; + } else { + x += (isNeg) ? -1 : 1; + } - return true; - } + return true; + } - public final boolean insideRadius() { - boolean inside = current < limit; - if (!inside) { - this.finish(); - } - return inside; - } + public final boolean insideRadius() { + boolean inside = current < limit; + if (!inside) { + this.finish(); + } + return inside; + } - // for successful completion - public void finish() { + // for successful completion + public void finish() { // SavageFactions.plugin.log("SpiralTask successfully completed!"); - this.stop(); - } + this.stop(); + } - // we're done, whether finished or cancelled - public final void stop() { - if (!this.valid()) { - return; - } + // we're done, whether finished or cancelled + public final void stop() { + if (!this.valid()) { + return; + } - readyToGo = false; - Bukkit.getServer().getScheduler().cancelTask(taskID); - taskID = -1; - } + readyToGo = false; + Bukkit.getServer().getScheduler().cancelTask(taskID); + taskID = -1; + } - // is this task still valid/workable? - public final boolean valid() { - return taskID != -1; - } + // is this task still valid/workable? + public final boolean valid() { + return taskID != -1; + } } diff --git a/src/main/java/com/massivecraft/factions/util/UtilFly.java b/src/main/java/com/massivecraft/factions/util/UtilFly.java index 4a8a11f0..c8acf539 100644 --- a/src/main/java/com/massivecraft/factions/util/UtilFly.java +++ b/src/main/java/com/massivecraft/factions/util/UtilFly.java @@ -12,103 +12,103 @@ import java.util.Iterator; public class UtilFly { - public static ArrayList playersFlying; + public static ArrayList playersFlying; - static { - playersFlying = SavageFactions.playersFlying; - } + static { + playersFlying = SavageFactions.playersFlying; + } - public UtilFly() { - } + public UtilFly() { + } - public static void run() { - if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { - playersFlying.clear(); - Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { - public void run() { - Iterator var2 = UtilFly.playersFlying.iterator(); + public static void run() { + if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { + playersFlying.clear(); + Bukkit.getScheduler().scheduleSyncRepeatingTask(SavageFactions.plugin, new Runnable() { + public void run() { + Iterator var2 = UtilFly.playersFlying.iterator(); - while (var2.hasNext()) { - FPlayer fp = (FPlayer) var2.next(); - if (fp != null) { - fp.checkIfNearbyEnemies(); - } - } + while (var2.hasNext()) { + FPlayer fp = (FPlayer) var2.next(); + if (fp != null) { + fp.checkIfNearbyEnemies(); + } + } - } - }, 0L, (long) SavageFactions.plugin.getConfig().getInt("fly-task-interval", 10)); - } - } + } + }, 0L, (long) SavageFactions.plugin.getConfig().getInt("fly-task-interval", 10)); + } + } - public static void setFly(FPlayer fp, boolean fly, boolean silent, boolean damage) { - if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { - fp.getPlayer().setAllowFlight(fly); - fp.getPlayer().setFlying(fly); - fp.setFlying(fly); - if (fly) { - playersFlying.add(fp); - } else { - playersFlying.remove(fp); - } + public static void setFly(FPlayer fp, boolean fly, boolean silent, boolean damage) { + if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { + fp.getPlayer().setAllowFlight(fly); + fp.getPlayer().setFlying(fly); + fp.setFlying(fly); + if (fly) { + playersFlying.add(fp); + } else { + playersFlying.remove(fp); + } - if (!silent) { - if (!damage) { - fp.msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); - } else { - fp.msg(TL.COMMAND_FLY_DAMAGE); - } - } + if (!silent) { + if (!damage) { + fp.msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); + } else { + fp.msg(TL.COMMAND_FLY_DAMAGE); + } + } - setFallDamage(fp, fly, damage); - } - } + setFallDamage(fp, fly, damage); + } + } - public static void checkFly(FPlayer me, Faction factionTo) { - if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { - if (!me.isAdminBypassing() || !me.isFlying()) { - Relation relationTo; - if (!me.isFlying()) { - if (me.isAdminBypassing()) { - setFly(me, true, false, false); - return; - } + public static void checkFly(FPlayer me, Faction factionTo) { + if (SavageFactions.plugin.getConfig().getBoolean("enable-faction-flight")) { + if (!me.isAdminBypassing() || !me.isFlying()) { + Relation relationTo; + if (!me.isFlying()) { + if (me.isAdminBypassing()) { + setFly(me, true, false, false); + return; + } - if (factionTo == me.getFaction() && me.getPlayer().hasPermission("factions.fly")) { - setFly(me, true, false, false); - } else { - relationTo = factionTo.getRelationTo(me); - if (factionTo.isWilderness() && me.canflyinWilderness() || factionTo.isWarZone() && me.canflyinWarzone() || factionTo.isSafeZone() && me.canflyinSafezone() || relationTo == Relation.ENEMY && me.canflyinEnemy() || relationTo == Relation.ALLY && me.canflyinAlly() || relationTo == Relation.TRUCE && me.canflyinTruce() || relationTo == Relation.NEUTRAL && me.canflyinNeutral()) { - setFly(me, true, false, false); - } - } - } else { - relationTo = factionTo.getRelationTo(me); - if (factionTo.equals(me.getFaction()) && !me.getPlayer().hasPermission("factions.fly") || factionTo.isWilderness() && !me.canflyinWilderness() || factionTo.isWarZone() && !me.canflyinWarzone() || factionTo.isSafeZone() && !me.canflyinSafezone() || relationTo == Relation.ENEMY && !me.canflyinEnemy() || relationTo == Relation.ALLY && !me.canflyinAlly() || relationTo == Relation.TRUCE && !me.canflyinTruce() || relationTo == Relation.NEUTRAL && !me.canflyinNeutral()) { - setFly(me, false, false, false); - } - } + if (factionTo == me.getFaction() && me.getPlayer().hasPermission("factions.fly")) { + setFly(me, true, false, false); + } else { + relationTo = factionTo.getRelationTo(me); + if (factionTo.isWilderness() && me.canflyinWilderness() || factionTo.isWarZone() && me.canflyinWarzone() || factionTo.isSafeZone() && me.canflyinSafezone() || relationTo == Relation.ENEMY && me.canflyinEnemy() || relationTo == Relation.ALLY && me.canflyinAlly() || relationTo == Relation.TRUCE && me.canflyinTruce() || relationTo == Relation.NEUTRAL && me.canflyinNeutral()) { + setFly(me, true, false, false); + } + } + } else { + relationTo = factionTo.getRelationTo(me); + if (factionTo.equals(me.getFaction()) && !me.getPlayer().hasPermission("factions.fly") || factionTo.isWilderness() && !me.canflyinWilderness() || factionTo.isWarZone() && !me.canflyinWarzone() || factionTo.isSafeZone() && !me.canflyinSafezone() || relationTo == Relation.ENEMY && !me.canflyinEnemy() || relationTo == Relation.ALLY && !me.canflyinAlly() || relationTo == Relation.TRUCE && !me.canflyinTruce() || relationTo == Relation.NEUTRAL && !me.canflyinNeutral()) { + setFly(me, false, false, false); + } + } - } - } - } + } + } + } - public static void setFallDamage(final FPlayer fp, boolean fly, boolean damage) { - if (!fly) { - if (!damage) { - fp.sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", String.valueOf(SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3)))); - } + public static void setFallDamage(final FPlayer fp, boolean fly, boolean damage) { + if (!fly) { + if (!damage) { + fp.sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", String.valueOf(SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3)))); + } - int cooldown = SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3); - if (cooldown > 0) { - fp.setTakeFallDamage(false); - Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { - public void run() { - fp.setTakeFallDamage(true); - } - }, 20L * (long) cooldown); - } - } + int cooldown = SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3); + if (cooldown > 0) { + fp.setTakeFallDamage(false); + Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { + public void run() { + fp.setTakeFallDamage(true); + } + }, 20L * (long) cooldown); + } + } - } + } } diff --git a/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java b/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java index a817e166..f786900e 100644 --- a/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java +++ b/src/main/java/com/massivecraft/factions/util/VisualizeUtil.java @@ -9,64 +9,64 @@ import java.util.*; public class VisualizeUtil { - protected static Map> playerLocations = new HashMap<>(); + protected static Map> playerLocations = new HashMap<>(); - public static Set getPlayerLocations(Player player) { - return getPlayerLocations(player.getUniqueId()); - } + public static Set getPlayerLocations(Player player) { + return getPlayerLocations(player.getUniqueId()); + } - public static Set getPlayerLocations(UUID uuid) { - Set ret = playerLocations.get(uuid); - if (ret == null) { - ret = new HashSet<>(); - playerLocations.put(uuid, ret); - } - return ret; - } + public static Set getPlayerLocations(UUID uuid) { + Set ret = playerLocations.get(uuid); + if (ret == null) { + ret = new HashSet<>(); + playerLocations.put(uuid, ret); + } + return ret; + } - @SuppressWarnings("deprecation") - public static void addLocation(Player player, Location location, Material type, byte data) { - getPlayerLocations(player).add(location); - player.sendBlockChange(location, type, data); - } + @SuppressWarnings("deprecation") + public static void addLocation(Player player, Location location, Material type, byte data) { + getPlayerLocations(player).add(location); + player.sendBlockChange(location, type, data); + } - @SuppressWarnings("deprecation") - public static void addLocation(Player player, Location location, Material material) { - getPlayerLocations(player).add(location); - player.sendBlockChange(location, material, (byte) 0); - } + @SuppressWarnings("deprecation") + public static void addLocation(Player player, Location location, Material material) { + getPlayerLocations(player).add(location); + player.sendBlockChange(location, material, (byte) 0); + } - @SuppressWarnings("deprecation") - public static void addLocations(Player player, Collection locations, Material material) { - Set ploc = getPlayerLocations(player); - for (Location location : locations) { - ploc.add(location); - player.sendBlockChange(location, material, (byte) 0); - } - } + @SuppressWarnings("deprecation") + public static void addLocations(Player player, Collection locations, Material material) { + Set ploc = getPlayerLocations(player); + for (Location location : locations) { + ploc.add(location); + player.sendBlockChange(location, material, (byte) 0); + } + } - @SuppressWarnings("deprecation") - public static void addBlocks(Player player, Collection blocks, Material material) { - Set ploc = getPlayerLocations(player); - for (Block block : blocks) { - Location location = block.getLocation(); - ploc.add(location); - player.sendBlockChange(location, material, (byte) 0); - } - } + @SuppressWarnings("deprecation") + public static void addBlocks(Player player, Collection blocks, Material material) { + Set ploc = getPlayerLocations(player); + for (Block block : blocks) { + Location location = block.getLocation(); + ploc.add(location); + player.sendBlockChange(location, material, (byte) 0); + } + } - @SuppressWarnings("deprecation") - public static void clear(Player player) { - Set locations = getPlayerLocations(player); - if (locations == null) { - return; - } - for (Location location : locations) { - Block block = location.getWorld().getBlockAt(location); - player.sendBlockChange(location, block.getType(), block.getData()); - } - locations.clear(); - } + @SuppressWarnings("deprecation") + public static void clear(Player player) { + Set locations = getPlayerLocations(player); + if (locations == null) { + return; + } + for (Location location : locations) { + Block block = location.getWorld().getBlockAt(location); + player.sendBlockChange(location, block.getType(), block.getData()); + } + locations.clear(); + } } diff --git a/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java b/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java index 8de53dff..bfd08ef6 100644 --- a/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java +++ b/src/main/java/com/massivecraft/factions/util/WarmUpUtil.java @@ -6,37 +6,37 @@ import com.massivecraft.factions.zcore.util.TL; public class WarmUpUtil { - /** - * @param player The player to notify. - * @param translationKey The translation key used for notifying. - * @param action The action, inserted into the notification message. - * @param runnable The task to run after the delay. If the delay is 0, the task is instantly ran. - * @param delay The time used, in seconds, for the delay. - *

- * note: for translations: %s = action, %d = delay - */ - public static void process(final FPlayer player, Warmup warmup, TL translationKey, String action, final Runnable runnable, long delay) { - if (delay > 0) { - if (player.isWarmingUp()) { - player.msg(TL.WARMUPS_ALREADY); - } else { - player.msg(translationKey.format(action, delay)); - int id = SavageFactions.plugin.getServer().getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - player.stopWarmup(); - runnable.run(); - } - }, delay * 20).getTaskId(); - player.addWarmup(warmup, id); - } - } else { - runnable.run(); - } - } + /** + * @param player The player to notify. + * @param translationKey The translation key used for notifying. + * @param action The action, inserted into the notification message. + * @param runnable The task to run after the delay. If the delay is 0, the task is instantly ran. + * @param delay The time used, in seconds, for the delay. + *

+ * note: for translations: %s = action, %d = delay + */ + public static void process(final FPlayer player, Warmup warmup, TL translationKey, String action, final Runnable runnable, long delay) { + if (delay > 0) { + if (player.isWarmingUp()) { + player.msg(TL.WARMUPS_ALREADY); + } else { + player.msg(translationKey.format(action, delay)); + int id = SavageFactions.plugin.getServer().getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + player.stopWarmup(); + runnable.run(); + } + }, delay * 20).getTaskId(); + player.addWarmup(warmup, id); + } + } else { + runnable.run(); + } + } - public enum Warmup { - HOME, WARP, FLIGHT, BANNER, CHECKPOINT - } + public enum Warmup { + HOME, WARP, FLIGHT, BANNER, CHECKPOINT + } } diff --git a/src/main/java/com/massivecraft/factions/util/WarpGUI.java b/src/main/java/com/massivecraft/factions/util/WarpGUI.java index 7936ffe1..702c7a6f 100644 --- a/src/main/java/com/massivecraft/factions/util/WarpGUI.java +++ b/src/main/java/com/massivecraft/factions/util/WarpGUI.java @@ -24,241 +24,241 @@ import java.util.logging.Level; public class WarpGUI implements InventoryHolder, FactionGUI { - private final ConfigurationSection section; - int guiSize; - private Inventory warpGUI; - private FPlayer fme; - private HashMap warpSlots = new HashMap<>(); - private int maxWarps; - private List dummySlots = new ArrayList<>(); + private final ConfigurationSection section; + int guiSize; + private Inventory warpGUI; + private FPlayer fme; + private HashMap warpSlots = new HashMap<>(); + private int maxWarps; + private List dummySlots = new ArrayList<>(); - public WarpGUI(FPlayer fme) { - this.fme = fme; - this.section = SavageFactions.plugin.getConfig().getConfigurationSection("fwarp-gui"); - } + public WarpGUI(FPlayer fme) { + this.fme = fme; + this.section = SavageFactions.plugin.getConfig().getConfigurationSection("fwarp-gui"); + } - @Override - public void build() { - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f warp GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return; - } + @Override + public void build() { + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f warp GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return; + } - // Build basic Inventory info - guiSize = section.getInt("rows", 3); - if (guiSize > 6) { - guiSize = 6; - SavageFactions.plugin.log(Level.INFO, "Warp GUI size out of bounds, defaulting to 6"); - } + // Build basic Inventory info + guiSize = section.getInt("rows", 3); + if (guiSize > 6) { + guiSize = 6; + SavageFactions.plugin.log(Level.INFO, "Warp GUI size out of bounds, defaulting to 6"); + } - guiSize *= 9; - String guiName = ChatColor.translateAlternateColorCodes('&', section.getString("name", "FactionPermissions")); - warpGUI = Bukkit.createInventory(this, guiSize, guiName); + guiSize *= 9; + String guiName = ChatColor.translateAlternateColorCodes('&', section.getString("name", "FactionPermissions")); + warpGUI = Bukkit.createInventory(this, guiSize, guiName); - maxWarps = SavageFactions.plugin.getConfig().getInt("max-warps", 5); + maxWarps = SavageFactions.plugin.getConfig().getInt("max-warps", 5); - Set factionWarps = fme.getFaction().getWarps().keySet(); - List warpOpenSlots = section.getIntegerList("warp-slots"); + Set factionWarps = fme.getFaction().getWarps().keySet(); + List warpOpenSlots = section.getIntegerList("warp-slots"); - buildDummyItems(); + buildDummyItems(); - if (maxWarps != warpOpenSlots.size()) { - SavageFactions.plugin.log(Level.SEVERE, "Invalid warp slots for GUI, Please use same value as max warps"); - return; - } + if (maxWarps != warpOpenSlots.size()) { + SavageFactions.plugin.log(Level.SEVERE, "Invalid warp slots for GUI, Please use same value as max warps"); + return; + } - int warpSlotIndex = 0; - for (String warp : factionWarps) { - warpSlots.put(warpOpenSlots.get(warpSlotIndex), warp); - warpSlotIndex++; - } + int warpSlotIndex = 0; + for (String warp : factionWarps) { + warpSlots.put(warpOpenSlots.get(warpSlotIndex), warp); + warpSlotIndex++; + } - buildItems(); - } + buildItems(); + } - @Override - public Inventory getInventory() { - return warpGUI; - } + @Override + public Inventory getInventory() { + return warpGUI; + } - private void buildItems() { - for (Map.Entry entry : warpSlots.entrySet()) { - warpGUI.setItem(entry.getKey(), buildItem(entry.getValue())); - } - } + private void buildItems() { + for (Map.Entry entry : warpSlots.entrySet()) { + warpGUI.setItem(entry.getKey(), buildItem(entry.getValue())); + } + } - @Override - public void onClick(int slot, ClickType action) { - if (warpSlots.containsKey(slot)) { - fme.getPlayer().closeInventory(); + @Override + public void onClick(int slot, ClickType action) { + if (warpSlots.containsKey(slot)) { + fme.getPlayer().closeInventory(); - // All clear lets TP them or ask for password - String warp = warpSlots.get(slot); - if (!fme.getFaction().hasWarpPassword(warp)) { - if (transact(fme)) { - doWarmup(warp); - } - } else { - fme.setEnteringPassword(true, warp); - fme.msg(TL.COMMAND_FWARP_PASSWORD_REQUIRED); - Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - if (fme.isEnteringPassword()) { - fme.msg(TL.COMMAND_FWARP_PASSWORD_TIMEOUT); - fme.setEnteringPassword(false, ""); - } - } - }, SavageFactions.plugin.getConfig().getInt("fwarp-gui.password-timeout", 5) * 20); - } - } - } + // All clear lets TP them or ask for password + String warp = warpSlots.get(slot); + if (!fme.getFaction().hasWarpPassword(warp)) { + if (transact(fme)) { + doWarmup(warp); + } + } else { + fme.setEnteringPassword(true, warp); + fme.msg(TL.COMMAND_FWARP_PASSWORD_REQUIRED); + Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + if (fme.isEnteringPassword()) { + fme.msg(TL.COMMAND_FWARP_PASSWORD_TIMEOUT); + fme.setEnteringPassword(false, ""); + } + } + }, SavageFactions.plugin.getConfig().getInt("fwarp-gui.password-timeout", 5) * 20); + } + } + } - private void doWarmup(final String warp) { - WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, new Runnable() { - @Override - public void run() { - Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); - if (player != null) { - player.teleport(fme.getFaction().getWarp(warp).getLocation()); - fme.msg(TL.COMMAND_FWARP_WARPED, warp); - } - } - }, SavageFactions.plugin.getConfig().getLong("warmups.f-warp", 0)); - } + private void doWarmup(final String warp) { + WarmUpUtil.process(fme, WarmUpUtil.Warmup.WARP, TL.WARMUPS_NOTIFY_TELEPORT, warp, new Runnable() { + @Override + public void run() { + Player player = Bukkit.getPlayer(fme.getPlayer().getUniqueId()); + if (player != null) { + player.teleport(fme.getFaction().getWarp(warp).getLocation()); + fme.msg(TL.COMMAND_FWARP_WARPED, warp); + } + } + }, SavageFactions.plugin.getConfig().getLong("warmups.f-warp", 0)); + } - private boolean transact(FPlayer player) { - if (!SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing()) { - return true; - } + private boolean transact(FPlayer player) { + if (!SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) || player.isAdminBypassing()) { + return true; + } - double cost = SavageFactions.plugin.getConfig().getDouble("warp-cost.warp", 5); + double cost = SavageFactions.plugin.getConfig().getDouble("warp-cost.warp", 5); - if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) { - return true; - } + if (!Econ.shouldBeUsed() || this.fme == null || cost == 0.0 || fme.isAdminBypassing()) { + return true; + } - if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { - return Econ.modifyMoney(fme.getFaction(), -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); - } else { - return Econ.modifyMoney(fme, -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); - } - } + if (Conf.bankEnabled && Conf.bankFactionPaysCosts && fme.hasFaction()) { + return Econ.modifyMoney(fme.getFaction(), -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } else { + return Econ.modifyMoney(fme, -cost, TL.COMMAND_FWARP_TOWARP.toString(), TL.COMMAND_FWARP_FORWARPING.toString()); + } + } - private ItemStack buildItem(String warp) { - ConfigurationSection warpItemSection = section.getConfigurationSection("warp-item"); - if (warpItemSection == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f warp GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return new ItemStack(Material.AIR); - } + private ItemStack buildItem(String warp) { + ConfigurationSection warpItemSection = section.getConfigurationSection("warp-item"); + if (warpItemSection == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f warp GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return new ItemStack(Material.AIR); + } - String displayName = replacePlaceholers(warpItemSection.getString("name"), warp, fme.getFaction()); - List lore = new ArrayList<>(); + String displayName = replacePlaceholers(warpItemSection.getString("name"), warp, fme.getFaction()); + List lore = new ArrayList<>(); - if (warpItemSection.getString("material") == null) { - return null; - } - Material material = Material.matchMaterial(warpItemSection.getString("material")); - if (material == null) { - material = Material.STONE; - } + if (warpItemSection.getString("material") == null) { + return null; + } + Material material = Material.matchMaterial(warpItemSection.getString("material")); + if (material == null) { + material = Material.STONE; + } - ItemStack item = new ItemStack(material); - ItemMeta itemMeta = item.getItemMeta(); + ItemStack item = new ItemStack(material); + ItemMeta itemMeta = item.getItemMeta(); - for (String loreLine : warpItemSection.getStringList("lore")) { - lore.add(replacePlaceholers(loreLine, warp, fme.getFaction())); - } + for (String loreLine : warpItemSection.getStringList("lore")) { + lore.add(replacePlaceholers(loreLine, warp, fme.getFaction())); + } - itemMeta.setDisplayName(displayName); - itemMeta.setLore(lore); - item.setItemMeta(itemMeta); + itemMeta.setDisplayName(displayName); + itemMeta.setLore(lore); + item.setItemMeta(itemMeta); - return item; - } + return item; + } - private String replacePlaceholers(String string, String warp, Faction faction) { - string = ChatColor.translateAlternateColorCodes('&', string); - string = string.replace("{warp}", warp); - string = string.replace("{warp-protected}", faction.hasWarpPassword(warp) ? "Enabled" : "Disabled"); - string = string.replace("{warp-cost}", !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) ? "Disabled" : Integer.toString(SavageFactions.plugin.getConfig().getInt("warp-cost.warp", 5))); - return string; - } + private String replacePlaceholers(String string, String warp, Faction faction) { + string = ChatColor.translateAlternateColorCodes('&', string); + string = string.replace("{warp}", warp); + string = string.replace("{warp-protected}", faction.hasWarpPassword(warp) ? "Enabled" : "Disabled"); + string = string.replace("{warp-cost}", !SavageFactions.plugin.getConfig().getBoolean("warp-cost.enabled", false) ? "Disabled" : Integer.toString(SavageFactions.plugin.getConfig().getInt("warp-cost.warp", 5))); + return string; + } - private void buildDummyItems() { - for (String key : section.getConfigurationSection("dummy-slots").getKeys(false)) { - int dummyId; - try { - dummyId = Integer.parseInt(key); - } catch (NumberFormatException exception) { - SavageFactions.plugin.log(Level.WARNING, "Invalid dummy item id: " + key.toUpperCase()); - continue; - } + private void buildDummyItems() { + for (String key : section.getConfigurationSection("dummy-slots").getKeys(false)) { + int dummyId; + try { + dummyId = Integer.parseInt(key); + } catch (NumberFormatException exception) { + SavageFactions.plugin.log(Level.WARNING, "Invalid dummy item id: " + key.toUpperCase()); + continue; + } - ItemStack dummyItem = buildDummyItem(dummyId); - if (dummyItem == null) { - continue; - } + ItemStack dummyItem = buildDummyItem(dummyId); + if (dummyItem == null) { + continue; + } - List dummyIdSlots = section.getIntegerList("dummy-slots." + key); - for (Integer slot : dummyIdSlots) { - if (slot + 1 > guiSize || slot < 0) { - SavageFactions.plugin.log(Level.WARNING, "Invalid slot: " + slot + " for dummy item: " + key); - continue; - } - dummySlots.add(slot); - warpGUI.setItem(slot, dummyItem); - } - } - } + List dummyIdSlots = section.getIntegerList("dummy-slots." + key); + for (Integer slot : dummyIdSlots) { + if (slot + 1 > guiSize || slot < 0) { + SavageFactions.plugin.log(Level.WARNING, "Invalid slot: " + slot + " for dummy item: " + key); + continue; + } + dummySlots.add(slot); + warpGUI.setItem(slot, dummyItem); + } + } + } - private ItemStack buildDummyItem(int id) { - final ConfigurationSection dummySection = section.getConfigurationSection("dummy-items." + id); + private ItemStack buildDummyItem(int id) { + final ConfigurationSection dummySection = section.getConfigurationSection("dummy-items." + id); - if (dummySection == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f warp GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return new ItemStack(Material.AIR); - } + if (dummySection == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f warp GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return new ItemStack(Material.AIR); + } - Material material = Material.matchMaterial(dummySection.getString("material", "")); - if (material == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid material for dummy item: " + id); - return null; - } + Material material = Material.matchMaterial(dummySection.getString("material", "")); + if (material == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid material for dummy item: " + id); + return null; + } - ItemStack itemStack = new ItemStack(material); + ItemStack itemStack = new ItemStack(material); - DyeColor color; - try { - color = DyeColor.valueOf(dummySection.getString("color", "")); - } catch (Exception exception) { - color = null; - } - if (color != null) { - itemStack.setDurability(color.getWoolData()); - } + DyeColor color; + try { + color = DyeColor.valueOf(dummySection.getString("color", "")); + } catch (Exception exception) { + color = null; + } + if (color != null) { + itemStack.setDurability(color.getWoolData()); + } - ItemMeta itemMeta = itemStack.getItemMeta(); + ItemMeta itemMeta = itemStack.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', dummySection.getString("name", " "))); + itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', dummySection.getString("name", " "))); - List lore = new ArrayList<>(); - for (String loreLine : dummySection.getStringList("lore")) { - lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); - } - itemMeta.setLore(lore); + List lore = new ArrayList<>(); + for (String loreLine : dummySection.getStringList("lore")) { + lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); + } + itemMeta.setLore(lore); - itemStack.setItemMeta(itemMeta); + itemStack.setItemMeta(itemMeta); - return itemStack; - } + return itemStack; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java b/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java index bed3cb90..2bc4a19d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java +++ b/src/main/java/com/massivecraft/factions/zcore/CommandVisibility.java @@ -1,7 +1,7 @@ -package com.massivecraft.factions.zcore; - -public enum CommandVisibility { - VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type. - SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands. - INVISIBLE // Invisible commands are invisible to everyone, even those who can use the command. -} +package com.massivecraft.factions.zcore; + +public enum CommandVisibility { + VISIBLE, // Visible commands are visible to anyone. Even those who don't have permission to use it or is of invalid sender type. + SECRET, // Secret commands are visible only to those who can use the command. These commands are usually some kind of admin commands. + INVISIBLE // Invisible commands are invisible to everyone, even those who can use the command. +} diff --git a/src/main/java/com/massivecraft/factions/zcore/MCommand.java b/src/main/java/com/massivecraft/factions/zcore/MCommand.java index 94919da4..013e3ae9 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MCommand.java +++ b/src/main/java/com/massivecraft/factions/zcore/MCommand.java @@ -23,463 +23,463 @@ import java.util.UUID; public abstract class MCommand { - public T p; - - // The sub-commands to this command - public List> subCommands; - // The different names this commands will react to - public List aliases; - public boolean allowNoSlashAccess; - // Information on the args - public List requiredArgs; - public LinkedHashMap optionalArgs; - public boolean errorOnToManyArgs = true; - public List helpLong; - public CommandVisibility visibility; - // Some information on permissions - public boolean senderMustBePlayer; - public boolean senderMustHaveFaction; - public String permission; - // Information available on execution of the command - public CommandSender sender; // Will always be set - public Player me; // Will only be set when the sender is a player - public boolean senderIsConsole; - public List args; // Will contain the arguments, or and empty list if there are none. - public List> commandChain = new ArrayList<>(); // The command chain used to execute this command - // FIELD: Help Short - // This field may be left blank and will in such case be loaded from the permissions node instead. - // Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff". - private String helpShort; - - public MCommand(T p) { - this.p = p; - - this.permission = null; - - this.allowNoSlashAccess = false; - - this.subCommands = new ArrayList<>(); - this.aliases = new ArrayList<>(); - - this.requiredArgs = new ArrayList<>(); - this.optionalArgs = new LinkedHashMap<>(); - - this.helpShort = null; - this.helpLong = new ArrayList<>(); - this.visibility = CommandVisibility.VISIBLE; - } - - public void addSubCommand(MCommand subCommand) { - subCommand.commandChain.addAll(this.commandChain); - subCommand.commandChain.add(this); - this.subCommands.add(subCommand); - } - - public String getHelpShort() { - return this.helpShort != null ? this.helpShort : getUsageTranslation().toString(); - } - - public void setHelpShort(String val) { - this.helpShort = val; - } - - public abstract TL getUsageTranslation(); - - public void setCommandSender(CommandSender sender) { - this.sender = sender; - if (sender instanceof Player) { - this.me = (Player) sender; - this.senderIsConsole = false; - } else { - this.me = null; - this.senderIsConsole = true; - } - } - - // The commandChain is a list of the parent command chain used to get to this command. - public void execute(CommandSender sender, List args, List> commandChain) { - // Set the execution-time specific variables - setCommandSender(sender); - this.args = args; - this.commandChain = commandChain; - - // Is there a matching sub command? - if (args.size() > 0) { - for (MCommand subCommand : this.subCommands) { - if (subCommand.aliases.contains(args.get(0).toLowerCase())) { - args.remove(0); - commandChain.add(this); - subCommand.execute(sender, args, commandChain); - return; - } - } - } - - if (!validCall(this.sender, this.args)) { - return; - } - - if (!this.isEnabled()) { - return; - } - - perform(); - } - - public void execute(CommandSender sender, List args) { - execute(sender, args, new ArrayList>()); - } - - // This is where the command action is performed. - public abstract void perform(); - - - // -------------------------------------------- // - // Call Validation - // -------------------------------------------- // - - /** - * In this method we validate that all prerequisites to perform this command has been met. - * - * @param sender of the command - * @param args of the command - * @return true if valid, false if not. - */ - // TODO: There should be a boolean for silence - public boolean validCall(CommandSender sender, List args) { - return validSenderType(sender, true) && validSenderPermissions(sender, true) && validArgs(args, sender); - } - - public boolean isEnabled() { - return true; - } - - - public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { - if (this.senderMustBePlayer && !(sender instanceof Player)) { - if (informSenderIfNot) { - msg(TL.GENERIC_PLAYERONLY); - } - return false; - - } - return !this.senderMustHaveFaction || !FPlayers.getInstance().getByPlayer((Player) sender).hasFaction(); - } - - public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot) { - return this.permission == null || p.perm.has(sender, this.permission, informSenderIfNot); - } - - public boolean validArgs(List args, CommandSender sender) { - if (args.size() < this.requiredArgs.size()) { - if (sender != null) { - msg(TL.GENERIC_ARGS_TOOFEW); - sender.sendMessage(this.getUseageTemplate()); - } - return false; - } - - if (args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.errorOnToManyArgs) { - if (sender != null) { - // Get the to many string slice - List theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size()); - msg(TL.GENERIC_ARGS_TOOMANY, TextUtil.implode(theToMany, " ")); - sender.sendMessage(this.getUseageTemplate()); - } - return false; - } - return true; - } - - public boolean validArgs(List args) { - return this.validArgs(args, null); - } - - // -------------------------------------------- // - // Help and Usage information - // -------------------------------------------- // - - public String getUseageTemplate(List> commandChain, boolean addShortHelp) { - StringBuilder ret = new StringBuilder(); - ret.append(p.txt.parseTags("")); - ret.append('/'); - - for (MCommand mc : commandChain) { - ret.append(TextUtil.implode(mc.aliases, ",")); - ret.append(' '); - } - - ret.append(TextUtil.implode(this.aliases, ",")); - - List args = new ArrayList<>(); - - for (String requiredArg : this.requiredArgs) { - args.add("<" + requiredArg + ">"); - } - - for (Entry optionalArg : this.optionalArgs.entrySet()) { - String val = optionalArg.getValue(); - if (val == null) { - val = ""; - } else { - val = "=" + val; - } - args.add("[" + optionalArg.getKey() + val + "]"); - } - - if (args.size() > 0) { - ret.append(p.txt.parseTags(" ")); - ret.append(TextUtil.implode(args, " ")); - } - - if (addShortHelp) { - ret.append(p.txt.parseTags(" ")); - ret.append(this.getHelpShort()); - } - - return ret.toString(); - } - - public String getUseageTemplate(boolean addShortHelp) { - return getUseageTemplate(this.commandChain, addShortHelp); - } - - public String getUseageTemplate() { - return getUseageTemplate(false); - } - - // -------------------------------------------- // - // Message Sending Helpers - // -------------------------------------------- // - - public void msg(String str, Object... args) { - sender.sendMessage(p.txt.parse(str, args)); - } - - public void msg(TL translation, Object... args) { - sender.sendMessage(p.txt.parse(translation.toString(), args)); - } - - public void sendMessage(String msg) { - sender.sendMessage(msg); - } - - public void sendMessage(List msgs) { - for (String msg : msgs) { - this.sendMessage(msg); - } - } - - public void sendFancyMessage(FancyMessage message) { - message.send(sender); - } - - public void sendFancyMessage(List messages) { - for (FancyMessage m : messages) { - sendFancyMessage(m); - } - } - - public List getToolTips(FPlayer player) { - List lines = new ArrayList<>(); - for (String s : p.getConfig().getStringList("tooltips.show")) { - lines.add(ChatColor.translateAlternateColorCodes('&', replaceFPlayerTags(s, player))); - } - return lines; - } - - public List getToolTips(Faction faction) { - List lines = new ArrayList<>(); - for (String s : p.getConfig().getStringList("tooltips.list")) { - lines.add(ChatColor.translateAlternateColorCodes('&', replaceFactionTags(s, faction))); - } - return lines; - } - - public String replaceFPlayerTags(String s, FPlayer player) { - if (s.contains("{balance}")) { - String balance = Econ.isSetup() ? Econ.getFriendlyBalance(player) : "no balance"; - s = s.replace("{balance}", balance); - } - if (s.contains("{lastSeen}")) { - String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - player.getLastLoginTime(), true, true) + " ago"; - String lastSeen = player.isOnline() ? ChatColor.GREEN + "Online" : (System.currentTimeMillis() - player.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); - s = s.replace("{lastSeen}", lastSeen); - } - if (s.contains("{power}")) { - String power = player.getPowerRounded() + "/" + player.getPowerMaxRounded(); - s = s.replace("{power}", power); - } - if (s.contains("{group}")) { - String group = SavageFactions.plugin.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(player.getId()))); - s = s.replace("{group}", group); - } - return s; - } - - public String replaceFactionTags(String s, Faction faction) { - if (s.contains("{power}")) { - s = s.replace("{power}", String.valueOf(faction.getPowerRounded())); - } - if (s.contains("{maxPower}")) { - s = s.replace("{maxPower}", String.valueOf(faction.getPowerMaxRounded())); - } - if (s.contains("{leader}")) { - FPlayer fLeader = faction.getFPlayerAdmin(); - String leader = fLeader == null ? "Server" : fLeader.getName().substring(0, fLeader.getName().length() > 14 ? 13 : fLeader.getName().length()); - s = s.replace("{leader}", leader); - } - if (s.contains("{chunks}")) { - s = s.replace("{chunks}", String.valueOf(faction.getLandRounded())); - } - if (s.contains("{members}")) { - s = s.replace("{members}", String.valueOf(faction.getSize())); - - } - if (s.contains("{online}")) { - s = s.replace("{online}", String.valueOf(faction.getOnlinePlayers().size())); - } - return s; - } - - // -------------------------------------------- // - // Argument Readers - // -------------------------------------------- // - - // Is set? ====================== - public boolean argIsSet(int idx) { - return this.args.size() >= idx + 1; - } - - // STRING ====================== - public String argAsString(int idx, String def) { - if (this.args.size() < idx + 1) { - return def; - } - return this.args.get(idx); - } - - public String argAsString(int idx) { - return this.argAsString(idx, null); - } - - // INT ====================== - public Integer strAsInt(String str, Integer def) { - if (str == null) { - return def; - } - try { - return Integer.parseInt(str); - } catch (Exception e) { - return def; - } - } - - public Integer argAsInt(int idx, Integer def) { - return strAsInt(this.argAsString(idx), def); - } - - public Integer argAsInt(int idx) { - return this.argAsInt(idx, null); - } - - // Double ====================== - public Double strAsDouble(String str, Double def) { - if (str == null) { - return def; - } - try { - return Double.parseDouble(str); - } catch (Exception e) { - return def; - } - } - - public Double argAsDouble(int idx, Double def) { - return strAsDouble(this.argAsString(idx), def); - } - - public Double argAsDouble(int idx) { - return this.argAsDouble(idx, null); - } - - // TODO: Go through the str conversion for the other arg-readers as well. - // Boolean ====================== - public Boolean strAsBool(String str) { - str = str.toLowerCase(); - return str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1"); - } - - public Boolean argAsBool(int idx, boolean def) { - String str = this.argAsString(idx); - if (str == null) { - return def; - } - - return strAsBool(str); - } - - public Boolean argAsBool(int idx) { - return this.argAsBool(idx, false); - } - - // PLAYER ====================== - public Player strAsPlayer(String name, Player def, boolean msg) { - Player ret = def; - - if (name != null) { - Player player = Bukkit.getServer().getPlayer(name); - if (player != null) { - ret = player; - } - } - - if (msg && ret == null) { - this.msg(TL.GENERIC_NOPLAYERFOUND, name); - } - - return ret; - } - - public Player argAsPlayer(int idx, Player def, boolean msg) { - return this.strAsPlayer(this.argAsString(idx), def, msg); - } - - public Player argAsPlayer(int idx, Player def) { - return this.argAsPlayer(idx, def, true); - } - - public Player argAsPlayer(int idx) { - return this.argAsPlayer(idx, null); - } - - // BEST PLAYER MATCH ====================== - public Player strAsBestPlayerMatch(String name, Player def, boolean msg) { - Player ret = def; - - if (name != null) { - List players = Bukkit.getServer().matchPlayer(name); - if (players.size() > 0) { - ret = players.get(0); - } - } - - if (msg && ret == null) { - this.msg(TL.GENERIC_NOPLAYERMATCH, name); - } - - return ret; - } - - public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) { - return this.strAsBestPlayerMatch(this.argAsString(idx), def, msg); - } - - public Player argAsBestPlayerMatch(int idx, Player def) { - return this.argAsBestPlayerMatch(idx, def, true); - } - - public Player argAsBestPlayerMatch(int idx) { - return this.argAsPlayer(idx, null); - } + public T p; + + // The sub-commands to this command + public List> subCommands; + // The different names this commands will react to + public List aliases; + public boolean allowNoSlashAccess; + // Information on the args + public List requiredArgs; + public LinkedHashMap optionalArgs; + public boolean errorOnToManyArgs = true; + public List helpLong; + public CommandVisibility visibility; + // Some information on permissions + public boolean senderMustBePlayer; + public boolean senderMustHaveFaction; + public String permission; + // Information available on execution of the command + public CommandSender sender; // Will always be set + public Player me; // Will only be set when the sender is a player + public boolean senderIsConsole; + public List args; // Will contain the arguments, or and empty list if there are none. + public List> commandChain = new ArrayList<>(); // The command chain used to execute this command + // FIELD: Help Short + // This field may be left blank and will in such case be loaded from the permissions node instead. + // Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff". + private String helpShort; + + public MCommand(T p) { + this.p = p; + + this.permission = null; + + this.allowNoSlashAccess = false; + + this.subCommands = new ArrayList<>(); + this.aliases = new ArrayList<>(); + + this.requiredArgs = new ArrayList<>(); + this.optionalArgs = new LinkedHashMap<>(); + + this.helpShort = null; + this.helpLong = new ArrayList<>(); + this.visibility = CommandVisibility.VISIBLE; + } + + public void addSubCommand(MCommand subCommand) { + subCommand.commandChain.addAll(this.commandChain); + subCommand.commandChain.add(this); + this.subCommands.add(subCommand); + } + + public String getHelpShort() { + return this.helpShort != null ? this.helpShort : getUsageTranslation().toString(); + } + + public void setHelpShort(String val) { + this.helpShort = val; + } + + public abstract TL getUsageTranslation(); + + public void setCommandSender(CommandSender sender) { + this.sender = sender; + if (sender instanceof Player) { + this.me = (Player) sender; + this.senderIsConsole = false; + } else { + this.me = null; + this.senderIsConsole = true; + } + } + + // The commandChain is a list of the parent command chain used to get to this command. + public void execute(CommandSender sender, List args, List> commandChain) { + // Set the execution-time specific variables + setCommandSender(sender); + this.args = args; + this.commandChain = commandChain; + + // Is there a matching sub command? + if (args.size() > 0) { + for (MCommand subCommand : this.subCommands) { + if (subCommand.aliases.contains(args.get(0).toLowerCase())) { + args.remove(0); + commandChain.add(this); + subCommand.execute(sender, args, commandChain); + return; + } + } + } + + if (!validCall(this.sender, this.args)) { + return; + } + + if (!this.isEnabled()) { + return; + } + + perform(); + } + + public void execute(CommandSender sender, List args) { + execute(sender, args, new ArrayList>()); + } + + // This is where the command action is performed. + public abstract void perform(); + + + // -------------------------------------------- // + // Call Validation + // -------------------------------------------- // + + /** + * In this method we validate that all prerequisites to perform this command has been met. + * + * @param sender of the command + * @param args of the command + * @return true if valid, false if not. + */ + // TODO: There should be a boolean for silence + public boolean validCall(CommandSender sender, List args) { + return validSenderType(sender, true) && validSenderPermissions(sender, true) && validArgs(args, sender); + } + + public boolean isEnabled() { + return true; + } + + + public boolean validSenderType(CommandSender sender, boolean informSenderIfNot) { + if (this.senderMustBePlayer && !(sender instanceof Player)) { + if (informSenderIfNot) { + msg(TL.GENERIC_PLAYERONLY); + } + return false; + + } + return !this.senderMustHaveFaction || !FPlayers.getInstance().getByPlayer((Player) sender).hasFaction(); + } + + public boolean validSenderPermissions(CommandSender sender, boolean informSenderIfNot) { + return this.permission == null || p.perm.has(sender, this.permission, informSenderIfNot); + } + + public boolean validArgs(List args, CommandSender sender) { + if (args.size() < this.requiredArgs.size()) { + if (sender != null) { + msg(TL.GENERIC_ARGS_TOOFEW); + sender.sendMessage(this.getUseageTemplate()); + } + return false; + } + + if (args.size() > this.requiredArgs.size() + this.optionalArgs.size() && this.errorOnToManyArgs) { + if (sender != null) { + // Get the to many string slice + List theToMany = args.subList(this.requiredArgs.size() + this.optionalArgs.size(), args.size()); + msg(TL.GENERIC_ARGS_TOOMANY, TextUtil.implode(theToMany, " ")); + sender.sendMessage(this.getUseageTemplate()); + } + return false; + } + return true; + } + + public boolean validArgs(List args) { + return this.validArgs(args, null); + } + + // -------------------------------------------- // + // Help and Usage information + // -------------------------------------------- // + + public String getUseageTemplate(List> commandChain, boolean addShortHelp) { + StringBuilder ret = new StringBuilder(); + ret.append(p.txt.parseTags("")); + ret.append('/'); + + for (MCommand mc : commandChain) { + ret.append(TextUtil.implode(mc.aliases, ",")); + ret.append(' '); + } + + ret.append(TextUtil.implode(this.aliases, ",")); + + List args = new ArrayList<>(); + + for (String requiredArg : this.requiredArgs) { + args.add("<" + requiredArg + ">"); + } + + for (Entry optionalArg : this.optionalArgs.entrySet()) { + String val = optionalArg.getValue(); + if (val == null) { + val = ""; + } else { + val = "=" + val; + } + args.add("[" + optionalArg.getKey() + val + "]"); + } + + if (args.size() > 0) { + ret.append(p.txt.parseTags(" ")); + ret.append(TextUtil.implode(args, " ")); + } + + if (addShortHelp) { + ret.append(p.txt.parseTags(" ")); + ret.append(this.getHelpShort()); + } + + return ret.toString(); + } + + public String getUseageTemplate(boolean addShortHelp) { + return getUseageTemplate(this.commandChain, addShortHelp); + } + + public String getUseageTemplate() { + return getUseageTemplate(false); + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public void msg(String str, Object... args) { + sender.sendMessage(p.txt.parse(str, args)); + } + + public void msg(TL translation, Object... args) { + sender.sendMessage(p.txt.parse(translation.toString(), args)); + } + + public void sendMessage(String msg) { + sender.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } + + public void sendFancyMessage(FancyMessage message) { + message.send(sender); + } + + public void sendFancyMessage(List messages) { + for (FancyMessage m : messages) { + sendFancyMessage(m); + } + } + + public List getToolTips(FPlayer player) { + List lines = new ArrayList<>(); + for (String s : p.getConfig().getStringList("tooltips.show")) { + lines.add(ChatColor.translateAlternateColorCodes('&', replaceFPlayerTags(s, player))); + } + return lines; + } + + public List getToolTips(Faction faction) { + List lines = new ArrayList<>(); + for (String s : p.getConfig().getStringList("tooltips.list")) { + lines.add(ChatColor.translateAlternateColorCodes('&', replaceFactionTags(s, faction))); + } + return lines; + } + + public String replaceFPlayerTags(String s, FPlayer player) { + if (s.contains("{balance}")) { + String balance = Econ.isSetup() ? Econ.getFriendlyBalance(player) : "no balance"; + s = s.replace("{balance}", balance); + } + if (s.contains("{lastSeen}")) { + String humanized = DurationFormatUtils.formatDurationWords(System.currentTimeMillis() - player.getLastLoginTime(), true, true) + " ago"; + String lastSeen = player.isOnline() ? ChatColor.GREEN + "Online" : (System.currentTimeMillis() - player.getLastLoginTime() < 432000000 ? ChatColor.YELLOW + humanized : ChatColor.RED + humanized); + s = s.replace("{lastSeen}", lastSeen); + } + if (s.contains("{power}")) { + String power = player.getPowerRounded() + "/" + player.getPowerMaxRounded(); + s = s.replace("{power}", power); + } + if (s.contains("{group}")) { + String group = SavageFactions.plugin.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(player.getId()))); + s = s.replace("{group}", group); + } + return s; + } + + public String replaceFactionTags(String s, Faction faction) { + if (s.contains("{power}")) { + s = s.replace("{power}", String.valueOf(faction.getPowerRounded())); + } + if (s.contains("{maxPower}")) { + s = s.replace("{maxPower}", String.valueOf(faction.getPowerMaxRounded())); + } + if (s.contains("{leader}")) { + FPlayer fLeader = faction.getFPlayerAdmin(); + String leader = fLeader == null ? "Server" : fLeader.getName().substring(0, fLeader.getName().length() > 14 ? 13 : fLeader.getName().length()); + s = s.replace("{leader}", leader); + } + if (s.contains("{chunks}")) { + s = s.replace("{chunks}", String.valueOf(faction.getLandRounded())); + } + if (s.contains("{members}")) { + s = s.replace("{members}", String.valueOf(faction.getSize())); + + } + if (s.contains("{online}")) { + s = s.replace("{online}", String.valueOf(faction.getOnlinePlayers().size())); + } + return s; + } + + // -------------------------------------------- // + // Argument Readers + // -------------------------------------------- // + + // Is set? ====================== + public boolean argIsSet(int idx) { + return this.args.size() >= idx + 1; + } + + // STRING ====================== + public String argAsString(int idx, String def) { + if (this.args.size() < idx + 1) { + return def; + } + return this.args.get(idx); + } + + public String argAsString(int idx) { + return this.argAsString(idx, null); + } + + // INT ====================== + public Integer strAsInt(String str, Integer def) { + if (str == null) { + return def; + } + try { + return Integer.parseInt(str); + } catch (Exception e) { + return def; + } + } + + public Integer argAsInt(int idx, Integer def) { + return strAsInt(this.argAsString(idx), def); + } + + public Integer argAsInt(int idx) { + return this.argAsInt(idx, null); + } + + // Double ====================== + public Double strAsDouble(String str, Double def) { + if (str == null) { + return def; + } + try { + return Double.parseDouble(str); + } catch (Exception e) { + return def; + } + } + + public Double argAsDouble(int idx, Double def) { + return strAsDouble(this.argAsString(idx), def); + } + + public Double argAsDouble(int idx) { + return this.argAsDouble(idx, null); + } + + // TODO: Go through the str conversion for the other arg-readers as well. + // Boolean ====================== + public Boolean strAsBool(String str) { + str = str.toLowerCase(); + return str.startsWith("y") || str.startsWith("t") || str.startsWith("on") || str.startsWith("+") || str.startsWith("1"); + } + + public Boolean argAsBool(int idx, boolean def) { + String str = this.argAsString(idx); + if (str == null) { + return def; + } + + return strAsBool(str); + } + + public Boolean argAsBool(int idx) { + return this.argAsBool(idx, false); + } + + // PLAYER ====================== + public Player strAsPlayer(String name, Player def, boolean msg) { + Player ret = def; + + if (name != null) { + Player player = Bukkit.getServer().getPlayer(name); + if (player != null) { + ret = player; + } + } + + if (msg && ret == null) { + this.msg(TL.GENERIC_NOPLAYERFOUND, name); + } + + return ret; + } + + public Player argAsPlayer(int idx, Player def, boolean msg) { + return this.strAsPlayer(this.argAsString(idx), def, msg); + } + + public Player argAsPlayer(int idx, Player def) { + return this.argAsPlayer(idx, def, true); + } + + public Player argAsPlayer(int idx) { + return this.argAsPlayer(idx, null); + } + + // BEST PLAYER MATCH ====================== + public Player strAsBestPlayerMatch(String name, Player def, boolean msg) { + Player ret = def; + + if (name != null) { + List players = Bukkit.getServer().matchPlayer(name); + if (players.size() > 0) { + ret = players.get(0); + } + } + + if (msg && ret == null) { + this.msg(TL.GENERIC_NOPLAYERMATCH, name); + } + + return ret; + } + + public Player argAsBestPlayerMatch(int idx, Player def, boolean msg) { + return this.strAsBestPlayerMatch(this.argAsString(idx), def, msg); + } + + public Player argAsBestPlayerMatch(int idx, Player def) { + return this.argAsBestPlayerMatch(idx, def, true); + } + + public Player argAsBestPlayerMatch(int idx) { + return this.argAsPlayer(idx, null); + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java index 1b6bdac2..865a7a4d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPlugin.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPlugin.java @@ -27,313 +27,313 @@ import java.util.logging.Level; public abstract class MPlugin extends JavaPlugin { - // Persist related - public final Gson gson = this.getGsonBuilder().create(); - // Some utils - public Persist persist; - public TextUtil txt; - public PermUtil perm; - public String refCommand = ""; - //holds f stuck taskids - public Map stuckMap = new HashMap<>(); - // These are not supposed to be used directly. - // They are loaded and used through the TextUtil instance for the plugin. - public Map rawTags = new LinkedHashMap<>(); - protected boolean loadSuccessful = false; - private Integer saveTask = null; - private boolean autoSave = true; - // Listeners - private MPluginSecretPlayerListener mPluginSecretPlayerListener; + // Persist related + public final Gson gson = this.getGsonBuilder().create(); + // Some utils + public Persist persist; + public TextUtil txt; + public PermUtil perm; + public String refCommand = ""; + //holds f stuck taskids + public Map stuckMap = new HashMap<>(); + // These are not supposed to be used directly. + // They are loaded and used through the TextUtil instance for the plugin. + public Map rawTags = new LinkedHashMap<>(); + protected boolean loadSuccessful = false; + private Integer saveTask = null; + private boolean autoSave = true; + // Listeners + private MPluginSecretPlayerListener mPluginSecretPlayerListener; - // Our stored base commands - private List> baseCommands = new ArrayList<>(); - // holds f stuck start times - private Map timers = new HashMap<>(); - // -------------------------------------------- // - // ENABLE - // -------------------------------------------- // - private long timeEnableStart; + // Our stored base commands + private List> baseCommands = new ArrayList<>(); + // holds f stuck start times + private Map timers = new HashMap<>(); + // -------------------------------------------- // + // ENABLE + // -------------------------------------------- // + private long timeEnableStart; - public boolean getAutoSave() { - return this.autoSave; - } + public boolean getAutoSave() { + return this.autoSave; + } - public void setAutoSave(boolean val) { - this.autoSave = val; - } + public void setAutoSave(boolean val) { + this.autoSave = val; + } - public List> getBaseCommands() { - return this.baseCommands; - } + public List> getBaseCommands() { + return this.baseCommands; + } - public boolean preEnable() { - log("=== ENABLE START ==="); - timeEnableStart = System.currentTimeMillis(); + public boolean preEnable() { + log("=== ENABLE START ==="); + timeEnableStart = System.currentTimeMillis(); - // Ensure basefolder exists! - this.getDataFolder().mkdirs(); + // Ensure basefolder exists! + this.getDataFolder().mkdirs(); - // Create Utility Instances - this.perm = new PermUtil(this); - this.persist = new Persist(this); + // Create Utility Instances + this.perm = new PermUtil(this); + this.persist = new Persist(this); - this.txt = new TextUtil(); - initTXT(); + this.txt = new TextUtil(); + initTXT(); - // attempt to get first command defined in plugin.yml as reference command, if any commands are defined in there - // reference command will be used to prevent "unknown command" console messages - try { - Map> refCmd = this.getDescription().getCommands(); - if (refCmd != null && !refCmd.isEmpty()) { - this.refCommand = (String) (refCmd.keySet().toArray()[0]); - } - } catch (ClassCastException ex) { - } + // attempt to get first command defined in plugin.yml as reference command, if any commands are defined in there + // reference command will be used to prevent "unknown command" console messages + try { + Map> refCmd = this.getDescription().getCommands(); + if (refCmd != null && !refCmd.isEmpty()) { + this.refCommand = (String) (refCmd.keySet().toArray()[0]); + } + } catch (ClassCastException ex) { + } - // Create and register player command listener - this.mPluginSecretPlayerListener = new MPluginSecretPlayerListener(this); - getServer().getPluginManager().registerEvents(this.mPluginSecretPlayerListener, this); + // Create and register player command listener + this.mPluginSecretPlayerListener = new MPluginSecretPlayerListener(this); + getServer().getPluginManager().registerEvents(this.mPluginSecretPlayerListener, this); - // Register recurring tasks - if (saveTask == null && Conf.saveToFileEveryXMinutes > 0.0) { - long saveTicks = (long) (20 * 60 * Conf.saveToFileEveryXMinutes); // Approximately every 30 min by default - saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks); - } + // Register recurring tasks + if (saveTask == null && Conf.saveToFileEveryXMinutes > 0.0) { + long saveTicks = (long) (20 * 60 * Conf.saveToFileEveryXMinutes); // Approximately every 30 min by default + saveTask = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new SaveTask(this), saveTicks, saveTicks); + } - loadLang(); + loadLang(); - loadSuccessful = true; - return true; - } + loadSuccessful = true; + return true; + } - public void postEnable() { - log("=== ENABLE DONE (Took " + (System.currentTimeMillis() - timeEnableStart) + "ms) ==="); - } + public void postEnable() { + log("=== ENABLE DONE (Took " + (System.currentTimeMillis() - timeEnableStart) + "ms) ==="); + } - public void loadLang() { - File lang = new File(getDataFolder(), "lang.yml"); - OutputStream out = null; - InputStream defLangStream = this.getResource("lang.yml"); - if (!lang.exists()) { - try { - getDataFolder().mkdir(); - lang.createNewFile(); - if (defLangStream != null) { - out = new FileOutputStream(lang); - int read; - byte[] bytes = new byte[1024]; + public void loadLang() { + File lang = new File(getDataFolder(), "lang.yml"); + OutputStream out = null; + InputStream defLangStream = this.getResource("lang.yml"); + if (!lang.exists()) { + try { + getDataFolder().mkdir(); + lang.createNewFile(); + if (defLangStream != null) { + out = new FileOutputStream(lang); + int read; + byte[] bytes = new byte[1024]; - while ((read = defLangStream.read(bytes)) != -1) { - out.write(bytes, 0, read); - } - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new BufferedReader(new InputStreamReader(defLangStream))); - TL.setFile(defConfig); - } - } catch (IOException e) { - e.printStackTrace(); // So they notice - getLogger().severe("[Factions] Couldn't create language file."); - getLogger().severe("[Factions] This is a fatal error. Now disabling"); - this.setEnabled(false); // Without it loaded, we can't send them messages - } finally { - if (defLangStream != null) { - try { - defLangStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - if (out != null) { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } + while ((read = defLangStream.read(bytes)) != -1) { + out.write(bytes, 0, read); + } + YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new BufferedReader(new InputStreamReader(defLangStream))); + TL.setFile(defConfig); + } + } catch (IOException e) { + e.printStackTrace(); // So they notice + getLogger().severe("[Factions] Couldn't create language file."); + getLogger().severe("[Factions] This is a fatal error. Now disabling"); + this.setEnabled(false); // Without it loaded, we can't send them messages + } finally { + if (defLangStream != null) { + try { + defLangStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } - } - } - } + } + } + } - YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); - for (TL item : TL.values()) { - if (conf.getString(item.getPath()) == null) { - conf.set(item.getPath(), item.getDefault()); - } - } + YamlConfiguration conf = YamlConfiguration.loadConfiguration(lang); + for (TL item : TL.values()) { + if (conf.getString(item.getPath()) == null) { + conf.set(item.getPath(), item.getDefault()); + } + } - // Remove this here because I'm sick of dealing with bug reports due to bad decisions on my part. - if (conf.getString(TL.COMMAND_SHOW_POWER.getPath(), "").contains("%5$s")) { - conf.set(TL.COMMAND_SHOW_POWER.getPath(), TL.COMMAND_SHOW_POWER.getDefault()); - log(Level.INFO, "Removed errant format specifier from f show power."); - } + // Remove this here because I'm sick of dealing with bug reports due to bad decisions on my part. + if (conf.getString(TL.COMMAND_SHOW_POWER.getPath(), "").contains("%5$s")) { + conf.set(TL.COMMAND_SHOW_POWER.getPath(), TL.COMMAND_SHOW_POWER.getDefault()); + log(Level.INFO, "Removed errant format specifier from f show power."); + } - TL.setFile(conf); - try { - conf.save(lang); - } catch (IOException e) { - getLogger().log(Level.WARNING, "Factions: Failed to save lang.yml."); - getLogger().log(Level.WARNING, "Factions: Report this stack trace to prosavage."); - e.printStackTrace(); - } - } + TL.setFile(conf); + try { + conf.save(lang); + } catch (IOException e) { + getLogger().log(Level.WARNING, "Factions: Failed to save lang.yml."); + getLogger().log(Level.WARNING, "Factions: Report this stack trace to prosavage."); + e.printStackTrace(); + } + } - public void onDisable() { - if (saveTask != null) { - this.getServer().getScheduler().cancelTask(saveTask); - saveTask = null; - } - // only save data if plugin actually loaded successfully - if (loadSuccessful) { - Factions.getInstance().forceSave(); - FPlayers.getInstance().forceSave(); - Board.getInstance().forceSave(); - } - log("Disabled"); - } + public void onDisable() { + if (saveTask != null) { + this.getServer().getScheduler().cancelTask(saveTask); + saveTask = null; + } + // only save data if plugin actually loaded successfully + if (loadSuccessful) { + Factions.getInstance().forceSave(); + FPlayers.getInstance().forceSave(); + Board.getInstance().forceSave(); + } + log("Disabled"); + } - // -------------------------------------------- // - // Some inits... - // You are supposed to override these in the plugin if you aren't satisfied with the defaults - // The goal is that you always will be satisfied though. - // -------------------------------------------- // + // -------------------------------------------- // + // Some inits... + // You are supposed to override these in the plugin if you aren't satisfied with the defaults + // The goal is that you always will be satisfied though. + // -------------------------------------------- // - public void suicide() { - log("Now I suicide!"); - this.getServer().getPluginManager().disablePlugin(this); - } + public void suicide() { + log("Now I suicide!"); + this.getServer().getPluginManager().disablePlugin(this); + } - // -------------------------------------------- // - // LANG AND TAGS - // -------------------------------------------- // + // -------------------------------------------- // + // LANG AND TAGS + // -------------------------------------------- // - public GsonBuilder getGsonBuilder() { - return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); - } + public GsonBuilder getGsonBuilder() { + return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); + } - public void addRawTags() { - this.rawTags.put("l", ""); // logo - this.rawTags.put("a", ""); // art - this.rawTags.put("n", ""); // notice - this.rawTags.put("i", ""); // info - this.rawTags.put("g", ""); // good - this.rawTags.put("b", ""); // bad - this.rawTags.put("h", ""); // highligh - this.rawTags.put("c", ""); // command - this.rawTags.put("plugin", ""); // parameter - } + public void addRawTags() { + this.rawTags.put("l", ""); // logo + this.rawTags.put("a", ""); // art + this.rawTags.put("n", ""); // notice + this.rawTags.put("i", ""); // info + this.rawTags.put("g", ""); // good + this.rawTags.put("b", ""); // bad + this.rawTags.put("h", ""); // highligh + this.rawTags.put("c", ""); // command + this.rawTags.put("plugin", ""); // parameter + } - public void initTXT() { - this.addRawTags(); + public void initTXT() { + this.addRawTags(); - Type type = new TypeToken>() { - }.getType(); + Type type = new TypeToken>() { + }.getType(); - Map tagsFromFile = this.persist.load(type, "tags"); - if (tagsFromFile != null) { - this.rawTags.putAll(tagsFromFile); - } - this.persist.save(this.rawTags, "tags"); + Map tagsFromFile = this.persist.load(type, "tags"); + if (tagsFromFile != null) { + this.rawTags.putAll(tagsFromFile); + } + this.persist.save(this.rawTags, "tags"); - for (Entry rawTag : this.rawTags.entrySet()) { - this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); - } - } + for (Entry rawTag : this.rawTags.entrySet()) { + this.txt.tags.put(rawTag.getKey(), TextUtil.parseColor(rawTag.getValue())); + } + } - // -------------------------------------------- // - // COMMAND HANDLING - // -------------------------------------------- // + // -------------------------------------------- // + // COMMAND HANDLING + // -------------------------------------------- // - // can be overridden by SavageFactions method, to provide option - public boolean logPlayerCommands() { - return true; - } + // can be overridden by SavageFactions method, to provide option + public boolean logPlayerCommands() { + return true; + } - public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { - return handleCommand(sender, commandString, testOnly, false); - } + public boolean handleCommand(CommandSender sender, String commandString, boolean testOnly) { + return handleCommand(sender, commandString, testOnly, false); + } - public boolean handleCommand(final CommandSender sender, String commandString, boolean testOnly, boolean async) { - boolean noSlash = true; - if (commandString.startsWith("/")) { - noSlash = false; - commandString = commandString.substring(1); - } + public boolean handleCommand(final CommandSender sender, String commandString, boolean testOnly, boolean async) { + boolean noSlash = true; + if (commandString.startsWith("/")) { + noSlash = false; + commandString = commandString.substring(1); + } - for (final MCommand command : this.getBaseCommands()) { - if (noSlash && !command.allowNoSlashAccess) { - continue; - } + for (final MCommand command : this.getBaseCommands()) { + if (noSlash && !command.allowNoSlashAccess) { + continue; + } - for (String alias : command.aliases) { - // disallow double-space after alias, so specific commands can be prevented (preventing "f home" won't prevent "f home") - if (commandString.startsWith(alias + " ")) { - return false; - } + for (String alias : command.aliases) { + // disallow double-space after alias, so specific commands can be prevented (preventing "f home" won't prevent "f home") + if (commandString.startsWith(alias + " ")) { + return false; + } - if (commandString.startsWith(alias + " ") || commandString.equals(alias)) { - final List args = new ArrayList<>(Arrays.asList(commandString.split("\\s+"))); - args.remove(0); + if (commandString.startsWith(alias + " ") || commandString.equals(alias)) { + final List args = new ArrayList<>(Arrays.asList(commandString.split("\\s+"))); + args.remove(0); - if (testOnly) { - return true; - } + if (testOnly) { + return true; + } - if (async) { - Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { - @Override - public void run() { - command.execute(sender, args); - } - }); - } else { - command.execute(sender, args); - } + if (async) { + Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { + @Override + public void run() { + command.execute(sender, args); + } + }); + } else { + command.execute(sender, args); + } - return true; - } - } - } - return false; - } + return true; + } + } + } + return false; + } - public boolean handleCommand(CommandSender sender, String commandString) { - return this.handleCommand(sender, commandString, false); - } + public boolean handleCommand(CommandSender sender, String commandString) { + return this.handleCommand(sender, commandString, false); + } - // -------------------------------------------- // - // HOOKS - // -------------------------------------------- // - public void preAutoSave() { + // -------------------------------------------- // + // HOOKS + // -------------------------------------------- // + public void preAutoSave() { - } + } - public void postAutoSave() { + public void postAutoSave() { - } + } - public Map getStuckMap() { - return this.stuckMap; - } + public Map getStuckMap() { + return this.stuckMap; + } - public Map getTimers() { - return this.timers; - } + public Map getTimers() { + return this.timers; + } - // -------------------------------------------- // - // LOGGING - // -------------------------------------------- // - public void log(Object msg) { - log(Level.INFO, msg); - } + // -------------------------------------------- // + // LOGGING + // -------------------------------------------- // + public void log(Object msg) { + log(Level.INFO, msg); + } - public void log(String str, Object... args) { - log(Level.INFO, this.txt.parse(str, args)); - } + public void log(String str, Object... args) { + log(Level.INFO, this.txt.parse(str, args)); + } - public void log(Level level, String str, Object... args) { - log(level, this.txt.parse(str, args)); - } + public void log(Level level, String str, Object... args) { + log(level, this.txt.parse(str, args)); + } - public void log(Level level, Object msg) { - getLogger().log(level, "[" + this.getDescription().getFullName() + "] " + msg); - } + public void log(Level level, Object msg) { + getLogger().log(level, "[" + this.getDescription().getFullName() + "] " + msg); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java index ea4474c9..e82bae1d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java +++ b/src/main/java/com/massivecraft/factions/zcore/MPluginSecretPlayerListener.java @@ -12,30 +12,30 @@ import org.bukkit.event.player.PlayerLoginEvent; public class MPluginSecretPlayerListener implements Listener { - private MPlugin p; + private MPlugin p; - public MPluginSecretPlayerListener(MPlugin p) { - this.p = p; - } + public MPluginSecretPlayerListener(MPlugin p) { + this.p = p; + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { - if (FactionsPlayerListener.preventCommand(event.getMessage(), event.getPlayer())) { - if (p.logPlayerCommands()) { - Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); - } - event.setCancelled(true); - } - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) { + if (FactionsPlayerListener.preventCommand(event.getMessage(), event.getPlayer())) { + if (p.logPlayerCommands()) { + Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); + } + event.setCancelled(true); + } + } - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onPlayerChat(AsyncPlayerChatEvent event) { - if (p.handleCommand(event.getPlayer(), event.getMessage(), false, true)) { - if (p.logPlayerCommands()) { - Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); - } - event.setCancelled(true); - } + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onPlayerChat(AsyncPlayerChatEvent event) { + if (p.handleCommand(event.getPlayer(), event.getMessage(), false, true)) { + if (p.logPlayerCommands()) { + Bukkit.getLogger().info("[PLAYER_COMMAND] " + event.getPlayer().getName() + ": " + event.getMessage()); + } + event.setCancelled(true); + } /* Should be handled by stuff in FactionsChatListener Player speaker = event.getPlayer(); @@ -43,10 +43,10 @@ public class MPluginSecretPlayerListener implements Listener { format = format.replace(Conf.chatTagReplaceString, SavageFactions.plugin.getPlayerFactionTag(speaker)).replace("[FACTION_TITLE]", SavageFactions.plugin.getPlayerTitle(speaker)); event.setFormat(format); */ - } + } - @EventHandler(priority = EventPriority.LOWEST) - public void onPlayerPreLogin(PlayerLoginEvent event) { - FPlayers.getInstance().getByPlayer(event.getPlayer()); - } + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerPreLogin(PlayerLoginEvent event) { + FPlayers.getInstance().getByPlayer(event.getPlayer()); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java b/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java index 87243fc2..ed6c607b 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/Access.java @@ -3,41 +3,41 @@ package com.massivecraft.factions.zcore.fperms; import org.bukkit.ChatColor; public enum Access { - ALLOW("Allow", ChatColor.GREEN), - DENY("Deny", ChatColor.DARK_RED), - UNDEFINED("Undefined", ChatColor.GRAY); + ALLOW("Allow", ChatColor.GREEN), + DENY("Deny", ChatColor.DARK_RED), + UNDEFINED("Undefined", ChatColor.GRAY); - private final String name; - private final ChatColor color; + private final String name; + private final ChatColor color; - Access(String name, ChatColor color) { - this.name = name; - this.color = color; - } + Access(String name, ChatColor color) { + this.name = name; + this.color = color; + } - /** - * Case insensitive check for access. - * - * @param check - * @return - */ - public static Access fromString(String check) { - for (Access access : values()) - if (access.name().equalsIgnoreCase(check)) - return access; - return null; - } + /** + * Case insensitive check for access. + * + * @param check + * @return + */ + public static Access fromString(String check) { + for (Access access : values()) + if (access.name().equalsIgnoreCase(check)) + return access; + return null; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public ChatColor getColor() { - return color; - } + public ChatColor getColor() { + return color; + } - @Override - public String toString() { - return name(); - } + @Override + public String toString() { + return name(); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java b/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java index be3f7f3c..b1d472b4 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/DefaultPermissions.java @@ -1,147 +1,152 @@ package com.massivecraft.factions.zcore.fperms; public class DefaultPermissions { - public DefaultPermissions() { } - public DefaultPermissions(boolean def) { - this.ban = def; - this.build = def; - this.destroy = def; - this.frostwalk = def; - this.painbuild = def; - this.door = def; - this.button = def; - this.lever = def; - this.container = def; - this.invite = def; - this.kick = def; - this.items = def; - this.sethome = def; - this.territory = def; - this.access = def; - this.home = def; - this.disband = def; - this.promote = def; - this.setwarp = def; - this.warp = def; - this.fly = def; - this.vault = def; - this.tntbank = def; - this.tntfill = def; - this.withdraw = def; - this.chest = def; - this.spawner = def; - } - public DefaultPermissions(boolean canBan, - boolean canBuild, - boolean canDestory, - boolean canFrostwalk, - boolean canPainbuild, - boolean canDoor, - boolean canButton, - boolean canLever, - boolean canContainer, - boolean canInvite, - boolean canKick, - boolean canItems, - boolean canSethome, - boolean canTerritory, - boolean canAccess, - boolean canHome, - boolean canDisband, - boolean canPromote, - boolean canSetwarp, - boolean canWarp, - boolean canFly, - boolean canVault, - boolean canTntbank, - boolean canTntfill, - boolean canWithdraw, - boolean canChest, - boolean canSpawners) { - this.ban = canBan; - this.build = canBuild; - this.destroy = canDestory; - this.frostwalk = canFrostwalk; - this.painbuild = canPainbuild; - this.door = canDoor; - this.button = canButton; - this.lever = canLever; - this.container = canContainer; - this.invite = canInvite; - this.kick = canKick; - this.items = canItems; - this.sethome = canSethome; - this.territory = canTerritory; - this.access = canAccess; - this.home = canHome; - this.disband = canDisband; - this.promote = canPromote; - this.setwarp = canSetwarp; - this.warp = canWarp; - this.fly = canFly; - this.vault = canVault; - this.tntbank = canTntbank; - this.tntfill = canTntfill; - this.withdraw = canWithdraw; - this.chest = canChest; - this.spawner = canSpawners; - } - public boolean ban; - public boolean build; - public boolean destroy; - public boolean frostwalk; - public boolean painbuild; - public boolean door; - public boolean button; - public boolean lever; - public boolean container; - public boolean invite; - public boolean kick; - public boolean items; - public boolean sethome; - public boolean territory; - public boolean access; - public boolean home; - public boolean disband; - public boolean promote; - public boolean setwarp; - public boolean warp; - public boolean fly; - public boolean vault; - public boolean tntbank; - public boolean tntfill; - public boolean withdraw; - public boolean chest; - public boolean spawner; - @Deprecated - public boolean getbyName(String name) { - if (name == "ban") return this.ban; - else if (name == "build") return this.build; - else if (name == "destroy") return this.destroy; - else if (name == "frostwalk") return this.frostwalk; - else if (name == "painbuild") return this.painbuild; - else if (name == "door") return this.door; - else if (name == "button") return this.button; - else if (name == "lever") return this.lever; - else if (name == "container") return this.container; - else if (name == "invite") return this.invite; - else if (name == "kick") return this.kick; - else if (name == "items") return this.items; - else if (name == "sethome") return this.sethome; - else if (name == "territory") return this.territory; - else if (name == "access") return this.access; - else if (name == "home") return this.disband; - else if (name == "disband") return this.disband; - else if (name == "promote") return this.promote; - else if (name == "setwarp") return this.setwarp; - else if (name == "warp") return this.warp; - else if (name == "fly") return this.fly; - else if (name == "vault") return this.vault; - else if (name == "tntbank") return this.tntbank; - else if (name == "tntfill") return this.tntfill; - else if (name == "withdraw") return this.withdraw; - else if (name == "chest") return this.chest; - else if (name == "spawner") return this.spawner; - else return false; - } + public DefaultPermissions() { + } + + public DefaultPermissions(boolean def) { + this.ban = def; + this.build = def; + this.destroy = def; + this.frostwalk = def; + this.painbuild = def; + this.door = def; + this.button = def; + this.lever = def; + this.container = def; + this.invite = def; + this.kick = def; + this.items = def; + this.sethome = def; + this.territory = def; + this.access = def; + this.home = def; + this.disband = def; + this.promote = def; + this.setwarp = def; + this.warp = def; + this.fly = def; + this.vault = def; + this.tntbank = def; + this.tntfill = def; + this.withdraw = def; + this.chest = def; + this.spawner = def; + } + + public DefaultPermissions(boolean canBan, + boolean canBuild, + boolean canDestory, + boolean canFrostwalk, + boolean canPainbuild, + boolean canDoor, + boolean canButton, + boolean canLever, + boolean canContainer, + boolean canInvite, + boolean canKick, + boolean canItems, + boolean canSethome, + boolean canTerritory, + boolean canAccess, + boolean canHome, + boolean canDisband, + boolean canPromote, + boolean canSetwarp, + boolean canWarp, + boolean canFly, + boolean canVault, + boolean canTntbank, + boolean canTntfill, + boolean canWithdraw, + boolean canChest, + boolean canSpawners) { + this.ban = canBan; + this.build = canBuild; + this.destroy = canDestory; + this.frostwalk = canFrostwalk; + this.painbuild = canPainbuild; + this.door = canDoor; + this.button = canButton; + this.lever = canLever; + this.container = canContainer; + this.invite = canInvite; + this.kick = canKick; + this.items = canItems; + this.sethome = canSethome; + this.territory = canTerritory; + this.access = canAccess; + this.home = canHome; + this.disband = canDisband; + this.promote = canPromote; + this.setwarp = canSetwarp; + this.warp = canWarp; + this.fly = canFly; + this.vault = canVault; + this.tntbank = canTntbank; + this.tntfill = canTntfill; + this.withdraw = canWithdraw; + this.chest = canChest; + this.spawner = canSpawners; + } + + public boolean ban; + public boolean build; + public boolean destroy; + public boolean frostwalk; + public boolean painbuild; + public boolean door; + public boolean button; + public boolean lever; + public boolean container; + public boolean invite; + public boolean kick; + public boolean items; + public boolean sethome; + public boolean territory; + public boolean access; + public boolean home; + public boolean disband; + public boolean promote; + public boolean setwarp; + public boolean warp; + public boolean fly; + public boolean vault; + public boolean tntbank; + public boolean tntfill; + public boolean withdraw; + public boolean chest; + public boolean spawner; + + @Deprecated + public boolean getbyName(String name) { + if (name == "ban") return this.ban; + else if (name == "build") return this.build; + else if (name == "destroy") return this.destroy; + else if (name == "frostwalk") return this.frostwalk; + else if (name == "painbuild") return this.painbuild; + else if (name == "door") return this.door; + else if (name == "button") return this.button; + else if (name == "lever") return this.lever; + else if (name == "container") return this.container; + else if (name == "invite") return this.invite; + else if (name == "kick") return this.kick; + else if (name == "items") return this.items; + else if (name == "sethome") return this.sethome; + else if (name == "territory") return this.territory; + else if (name == "access") return this.access; + else if (name == "home") return this.disband; + else if (name == "disband") return this.disband; + else if (name == "promote") return this.promote; + else if (name == "setwarp") return this.setwarp; + else if (name == "warp") return this.warp; + else if (name == "fly") return this.fly; + else if (name == "vault") return this.vault; + else if (name == "tntbank") return this.tntbank; + else if (name == "tntfill") return this.tntfill; + else if (name == "withdraw") return this.withdraw; + else if (name == "chest") return this.chest; + else if (name == "spawner") return this.spawner; + else return false; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java b/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java index 3441f9d3..3412581b 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/Permissable.java @@ -4,10 +4,10 @@ import org.bukkit.inventory.ItemStack; public interface Permissable { - ItemStack buildItem(); + ItemStack buildItem(); - String replacePlaceholders(String string); + String replacePlaceholders(String string); - String name(); + String name(); } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java b/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java index 3fc99e83..3c5c32e7 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/PermissableAction.java @@ -16,169 +16,169 @@ import java.util.Map; import java.util.logging.Level; public enum PermissableAction { - BAN("ban"), - BUILD("build"), - DESTROY("destroy"), - FROST_WALK("frostwalk"), - PAIN_BUILD("painbuild"), - DOOR("door"), - BUTTON("button"), - LEVER("lever"), - CONTAINER("container"), - INVITE("invite"), - KICK("kick"), - ITEM("items"), // generic for most items - SETHOME("sethome"), - TERRITORY("territory"), - ACCESS("access"), - HOME("home"), - DISBAND("disband"), - PROMOTE("promote"), - SETWARP("setwarp"), - WARP("warp"), - FLY("fly"), - VAULT("vault"), - TNTBANK("tntbank"), - TNTFILL("tntfill"), - WITHDRAW("withdraw"), - CHEST("chest"), - SPAWNER("spawner"); + BAN("ban"), + BUILD("build"), + DESTROY("destroy"), + FROST_WALK("frostwalk"), + PAIN_BUILD("painbuild"), + DOOR("door"), + BUTTON("button"), + LEVER("lever"), + CONTAINER("container"), + INVITE("invite"), + KICK("kick"), + ITEM("items"), // generic for most items + SETHOME("sethome"), + TERRITORY("territory"), + ACCESS("access"), + HOME("home"), + DISBAND("disband"), + PROMOTE("promote"), + SETWARP("setwarp"), + WARP("warp"), + FLY("fly"), + VAULT("vault"), + TNTBANK("tntbank"), + TNTFILL("tntfill"), + WITHDRAW("withdraw"), + CHEST("chest"), + SPAWNER("spawner"); - private String name; + private String name; - PermissableAction(String name) { - this.name = name; - } + PermissableAction(String name) { + this.name = name; + } - /** - * Case insensitive check for action. - * - * @param check - * @return - action - */ - public static PermissableAction fromString(String check) { - for (PermissableAction permissableAction : values()) { - if (permissableAction.name().equalsIgnoreCase(check)) { - return permissableAction; - } - } + /** + * Case insensitive check for action. + * + * @param check + * @return - action + */ + public static PermissableAction fromString(String check) { + for (PermissableAction permissableAction : values()) { + if (permissableAction.name().equalsIgnoreCase(check)) { + return permissableAction; + } + } - return null; - } + return null; + } - /** - * Get the friendly name of this action. Used for editing in commands. - * - * @return friendly name of the action as a String. - */ - public String getName() { - return this.name; - } + /** + * Get the friendly name of this action. Used for editing in commands. + * + * @return friendly name of the action as a String. + */ + public String getName() { + return this.name; + } - @Override - public String toString() { - return name; - } + @Override + public String toString() { + return name; + } - // Utility method to build items for F Perm GUI - public ItemStack buildItem(FPlayer fme, Permissable permissable) { - final ConfigurationSection section = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.action"); + // Utility method to build items for F Perm GUI + public ItemStack buildItem(FPlayer fme, Permissable permissable) { + final ConfigurationSection section = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.action"); - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return new ItemStack(Material.AIR); - } + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return new ItemStack(Material.AIR); + } - String displayName = replacePlaceholders(section.getString("placeholder-item.name"), fme, permissable); - List lore = new ArrayList<>(); + String displayName = replacePlaceholders(section.getString("placeholder-item.name"), fme, permissable); + List lore = new ArrayList<>(); - if (section.getString("materials." + name().toLowerCase().replace('_', '-')) == null) { - return null; - } - Material material = Material.matchMaterial(section.getString("materials." + name().toLowerCase().replace('_', '-'))); - if (material == null) { - material = SavageFactions.plugin.STAINED_CLAY; - } + if (section.getString("materials." + name().toLowerCase().replace('_', '-')) == null) { + return null; + } + Material material = Material.matchMaterial(section.getString("materials." + name().toLowerCase().replace('_', '-'))); + if (material == null) { + material = SavageFactions.plugin.STAINED_CLAY; + } - Access access = fme.getFaction().getAccess(permissable, this); - if (access == null) { - access = Access.UNDEFINED; - } + Access access = fme.getFaction().getAccess(permissable, this); + if (access == null) { + access = Access.UNDEFINED; + } - ItemStack item = new ItemStack(material); - ItemMeta itemMeta = item.getItemMeta(); + ItemStack item = new ItemStack(material); + ItemMeta itemMeta = item.getItemMeta(); - String accessValue = null; + String accessValue = null; - switch (access) { - case ALLOW: - accessValue = "allow"; - break; - case DENY: - accessValue = "deny"; - break; - case UNDEFINED: - accessValue = "undefined"; - break; - } + switch (access) { + case ALLOW: + accessValue = "allow"; + break; + case DENY: + accessValue = "deny"; + break; + case UNDEFINED: + accessValue = "undefined"; + break; + } - // If under the 1.13 version we will use the colorable option. - if (!SavageFactions.plugin.mc113) { - DyeColor dyeColor = null; + // If under the 1.13 version we will use the colorable option. + if (!SavageFactions.plugin.mc113) { + DyeColor dyeColor = null; - try { - dyeColor = DyeColor.valueOf(section.getString("access." + access.name().toLowerCase())); - } catch (Exception exception) { - } + try { + dyeColor = DyeColor.valueOf(section.getString("access." + access.name().toLowerCase())); + } catch (Exception exception) { + } - if (dyeColor != null) { - item.setDurability(dyeColor.getWoolData()); - } - } else { - // so this is in 1.13 mode, our config will automatically be updated to a material instead of color because of it being removed in the new api - item.setType(Material.valueOf(SavageFactions.plugin.getConfig().getString("fperm-gui.action.access." + accessValue))); - } + if (dyeColor != null) { + item.setDurability(dyeColor.getWoolData()); + } + } else { + // so this is in 1.13 mode, our config will automatically be updated to a material instead of color because of it being removed in the new api + item.setType(Material.valueOf(SavageFactions.plugin.getConfig().getString("fperm-gui.action.access." + accessValue))); + } - for (String loreLine : section.getStringList("placeholder-item.lore")) { - lore.add(replacePlaceholders(loreLine, fme, permissable)); - } + for (String loreLine : section.getStringList("placeholder-item.lore")) { + lore.add(replacePlaceholders(loreLine, fme, permissable)); + } - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - itemMeta.setDisplayName(displayName); - itemMeta.setLore(lore); - item.setItemMeta(itemMeta); + itemMeta.setDisplayName(displayName); + itemMeta.setLore(lore); + item.setItemMeta(itemMeta); - return item; - } + return item; + } - public String replacePlaceholders(String string, FPlayer fme, Permissable permissable) { - // Run Permissable placeholders - string = permissable.replacePlaceholders(string); + public String replacePlaceholders(String string, FPlayer fme, Permissable permissable) { + // Run Permissable placeholders + string = permissable.replacePlaceholders(string); - String actionName = name.substring(0, 1).toUpperCase() + name.substring(1); - string = string.replace("{action}", actionName); + String actionName = name.substring(0, 1).toUpperCase() + name.substring(1); + string = string.replace("{action}", actionName); - Access access = fme.getFaction().getAccess(permissable, this); - if (access == null) { - access = Access.UNDEFINED; - } - String actionAccess = access.getName(); - string = string.replace("{action-access}", actionAccess); - string = string.replace("{action-access-color}", access.getColor().toString()); + Access access = fme.getFaction().getAccess(permissable, this); + if (access == null) { + access = Access.UNDEFINED; + } + String actionAccess = access.getName(); + string = string.replace("{action-access}", actionAccess); + string = string.replace("{action-access-color}", access.getColor().toString()); - return string; - } + return string; + } - public static Map fromDefaults(DefaultPermissions defaultPermissions) { - Map defaultMap = new HashMap<>(); - for (PermissableAction permissableAction : PermissableAction.values()) { - defaultMap.put(permissableAction, defaultPermissions.getbyName(permissableAction.name) ? Access.ALLOW : Access.DENY); - } - return defaultMap; - } + public static Map fromDefaults(DefaultPermissions defaultPermissions) { + Map defaultMap = new HashMap<>(); + for (PermissableAction permissableAction : PermissableAction.values()) { + defaultMap.put(permissableAction, defaultPermissions.getbyName(permissableAction.name) ? Access.ALLOW : Access.DENY); + } + return defaultMap; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionGUI.java b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionGUI.java index c26ad9a4..5608e972 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionGUI.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableActionGUI.java @@ -24,291 +24,291 @@ import java.util.logging.Level; public class PermissableActionGUI implements InventoryHolder, FactionGUI { - private final ConfigurationSection section; - private Inventory actionGUI; - private FPlayer fme; - private int guiSize; - private Permissable permissable; - private HashMap actionSlots = new HashMap<>(); - private HashMap specialSlots = new HashMap<>(); - private ArrayList usedDummySlots = new ArrayList<>(); + private final ConfigurationSection section; + private Inventory actionGUI; + private FPlayer fme; + private int guiSize; + private Permissable permissable; + private HashMap actionSlots = new HashMap<>(); + private HashMap specialSlots = new HashMap<>(); + private ArrayList usedDummySlots = new ArrayList<>(); - public PermissableActionGUI(FPlayer fme, Permissable permissable) { - this.fme = fme; - this.permissable = permissable; - this.section = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.action"); - } + public PermissableActionGUI(FPlayer fme, Permissable permissable) { + this.fme = fme; + this.permissable = permissable; + this.section = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.action"); + } - public void build() { - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return; - } + public void build() { + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return; + } - guiSize = section.getInt("rows", 3); - if (guiSize > 6) { - guiSize = 6; - SavageFactions.plugin.log(Level.INFO, "Action GUI size out of bounds, defaulting to 6"); - } + guiSize = section.getInt("rows", 3); + if (guiSize > 6) { + guiSize = 6; + SavageFactions.plugin.log(Level.INFO, "Action GUI size out of bounds, defaulting to 6"); + } - guiSize *= 9; - String guiName = ChatColor.translateAlternateColorCodes('&', section.getString("name", "FactionPerms")); - actionGUI = Bukkit.createInventory(this, guiSize, guiName); - boolean disabled = false; - for (String key : section.getConfigurationSection("slots").getKeys(false)) { - int slot = section.getInt("slots." + key); - if (slot == -1) { - disabled = true; - continue; - } - if (slot + 1 > guiSize || slot < 0) { - SavageFactions.plugin.log(Level.WARNING, "Invalid slot for: " + key.toUpperCase()); - continue; - } + guiSize *= 9; + String guiName = ChatColor.translateAlternateColorCodes('&', section.getString("name", "FactionPerms")); + actionGUI = Bukkit.createInventory(this, guiSize, guiName); + boolean disabled = false; + for (String key : section.getConfigurationSection("slots").getKeys(false)) { + int slot = section.getInt("slots." + key); + if (slot == -1) { + disabled = true; + continue; + } + if (slot + 1 > guiSize || slot < 0) { + SavageFactions.plugin.log(Level.WARNING, "Invalid slot for: " + key.toUpperCase()); + continue; + } - if (SpecialItem.isSpecial(key)) { - specialSlots.put(slot, SpecialItem.fromString(key)); - continue; - } + if (SpecialItem.isSpecial(key)) { + specialSlots.put(slot, SpecialItem.fromString(key)); + continue; + } - PermissableAction permissableAction = PermissableAction.fromString(key.toUpperCase().replace('-', '_')); - if (permissableAction == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid permissable action: " + key.toUpperCase()); - continue; - } + PermissableAction permissableAction = PermissableAction.fromString(key.toUpperCase().replace('-', '_')); + if (permissableAction == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid permissable action: " + key.toUpperCase()); + continue; + } - actionSlots.put(section.getInt("slots." + key), permissableAction); - } + actionSlots.put(section.getInt("slots." + key), permissableAction); + } - buildDummyItems(); + buildDummyItems(); - if (actionSlots.values().toArray().length != PermissableAction.values().length) { - // Missing actions add them forcefully to the GUI and log error - Set missingActions = new HashSet<>(Arrays.asList(PermissableAction.values())); - missingActions.removeAll(actionSlots.values()); + if (actionSlots.values().toArray().length != PermissableAction.values().length) { + // Missing actions add them forcefully to the GUI and log error + Set missingActions = new HashSet<>(Arrays.asList(PermissableAction.values())); + missingActions.removeAll(actionSlots.values()); - for (PermissableAction action : missingActions) { - if (disabled) { - break; - } - if (!usedDummySlots.isEmpty()) { - int slot = usedDummySlots.get(0); - actionSlots.put(slot, action); - } else { - int slot = actionGUI.firstEmpty(); - if (slot != -1) { - actionSlots.put(slot, action); - } - } - SavageFactions.plugin.log(Level.WARNING, "Missing action: " + action.name()); - } + for (PermissableAction action : missingActions) { + if (disabled) { + break; + } + if (!usedDummySlots.isEmpty()) { + int slot = usedDummySlots.get(0); + actionSlots.put(slot, action); + } else { + int slot = actionGUI.firstEmpty(); + if (slot != -1) { + actionSlots.put(slot, action); + } + } + SavageFactions.plugin.log(Level.WARNING, "Missing action: " + action.name()); + } - } + } - buildSpecialItems(); - buildItems(); - } + buildSpecialItems(); + buildItems(); + } - @Override - public Inventory getInventory() { - return actionGUI; - } + @Override + public Inventory getInventory() { + return actionGUI; + } - @Override - public void onClick(int slot, ClickType click) { - if (specialSlots.containsKey(slot)) { - if (specialSlots.get(slot) == SpecialItem.BACK) { - PermissableRelationGUI relationGUI = new PermissableRelationGUI(fme); - relationGUI.build(); + @Override + public void onClick(int slot, ClickType click) { + if (specialSlots.containsKey(slot)) { + if (specialSlots.get(slot) == SpecialItem.BACK) { + PermissableRelationGUI relationGUI = new PermissableRelationGUI(fme); + relationGUI.build(); - fme.getPlayer().openInventory(relationGUI.getInventory()); - } - return; - } - if (!actionSlots.containsKey(slot)) { - return; - } + fme.getPlayer().openInventory(relationGUI.getInventory()); + } + return; + } + if (!actionSlots.containsKey(slot)) { + return; + } - PermissableAction action = actionSlots.get(slot); - Access access; - if (click == ClickType.LEFT) { - access = Access.ALLOW; - fme.getFaction().setPermission(permissable, action, access); - } else if (click == ClickType.RIGHT) { - access = Access.DENY; - fme.getFaction().setPermission(permissable, action, access); - } else if (click == ClickType.MIDDLE) { - access = Access.UNDEFINED; - fme.getFaction().setPermission(permissable, action, access); - } else { - return; - } + PermissableAction action = actionSlots.get(slot); + Access access; + if (click == ClickType.LEFT) { + access = Access.ALLOW; + fme.getFaction().setPermission(permissable, action, access); + } else if (click == ClickType.RIGHT) { + access = Access.DENY; + fme.getFaction().setPermission(permissable, action, access); + } else if (click == ClickType.MIDDLE) { + access = Access.UNDEFINED; + fme.getFaction().setPermission(permissable, action, access); + } else { + return; + } - actionGUI.setItem(slot, action.buildItem(fme, permissable)); - fme.msg(TL.COMMAND_PERM_SET, action.name(), access.name(), permissable.name()); - SavageFactions.plugin.log(String.format(TL.COMMAND_PERM_SET.toString(), action.name(), access.name(), permissable.name()) + " for faction " + fme.getTag()); - } + actionGUI.setItem(slot, action.buildItem(fme, permissable)); + fme.msg(TL.COMMAND_PERM_SET, action.name(), access.name(), permissable.name()); + SavageFactions.plugin.log(String.format(TL.COMMAND_PERM_SET.toString(), action.name(), access.name(), permissable.name()) + " for faction " + fme.getTag()); + } - private void buildItems() { - for (Map.Entry entry : actionSlots.entrySet()) { - PermissableAction permissableAction = entry.getValue(); + private void buildItems() { + for (Map.Entry entry : actionSlots.entrySet()) { + PermissableAction permissableAction = entry.getValue(); - ItemStack item = permissableAction.buildItem(fme, permissable); + ItemStack item = permissableAction.buildItem(fme, permissable); - if (item == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid item for: " + permissableAction.toString().toUpperCase()); - continue; - } + if (item == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid item for: " + permissableAction.toString().toUpperCase()); + continue; + } - actionGUI.setItem(entry.getKey(), item); - } - } + actionGUI.setItem(entry.getKey(), item); + } + } - private void buildSpecialItems() { - for (Map.Entry entry : specialSlots.entrySet()) { - actionGUI.setItem(entry.getKey(), getSpecialItem(entry.getValue())); - } - } + private void buildSpecialItems() { + for (Map.Entry entry : specialSlots.entrySet()) { + actionGUI.setItem(entry.getKey(), getSpecialItem(entry.getValue())); + } + } - private ItemStack getSpecialItem(SpecialItem specialItem) { - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return new ItemStack(Material.AIR); - } + private ItemStack getSpecialItem(SpecialItem specialItem) { + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return new ItemStack(Material.AIR); + } - switch (specialItem) { - case RELATION: - return permissable.buildItem(); - case BACK: - ConfigurationSection backButtonConfig = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.back-item"); + switch (specialItem) { + case RELATION: + return permissable.buildItem(); + case BACK: + ConfigurationSection backButtonConfig = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.back-item"); - ItemStack backButton = new ItemStack(Material.matchMaterial(backButtonConfig.getString("material"))); - ItemMeta backButtonMeta = backButton.getItemMeta(); + ItemStack backButton = new ItemStack(Material.matchMaterial(backButtonConfig.getString("material"))); + ItemMeta backButtonMeta = backButton.getItemMeta(); - backButtonMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', backButtonConfig.getString("name"))); - List lore = new ArrayList<>(); - for (String loreLine : backButtonConfig.getStringList("lore")) { - lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); - } + backButtonMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', backButtonConfig.getString("name"))); + List lore = new ArrayList<>(); + for (String loreLine : backButtonConfig.getStringList("lore")) { + lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); + } - backButtonMeta.setLore(lore); - if (!SavageFactions.plugin.mc17) { - backButtonMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + backButtonMeta.setLore(lore); + if (!SavageFactions.plugin.mc17) { + backButtonMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - backButton.setItemMeta(backButtonMeta); + backButton.setItemMeta(backButtonMeta); - return backButton; - default: - return null; - } - } + return backButton; + default: + return null; + } + } - private void buildDummyItems() { - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return; - } + private void buildDummyItems() { + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return; + } - for (String key : section.getConfigurationSection("dummy-items").getKeys(false)) { - int dummyId; - try { - dummyId = Integer.parseInt(key); - } catch (NumberFormatException exception) { - SavageFactions.plugin.log(Level.WARNING, "Invalid dummy item id: " + key.toUpperCase()); - continue; - } + for (String key : section.getConfigurationSection("dummy-items").getKeys(false)) { + int dummyId; + try { + dummyId = Integer.parseInt(key); + } catch (NumberFormatException exception) { + SavageFactions.plugin.log(Level.WARNING, "Invalid dummy item id: " + key.toUpperCase()); + continue; + } - ItemStack dummyItem = buildDummyItem(dummyId); - if (dummyItem == null) { - continue; - } + ItemStack dummyItem = buildDummyItem(dummyId); + if (dummyItem == null) { + continue; + } - ItemMeta meta = dummyItem.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + ItemMeta meta = dummyItem.getItemMeta(); + if (!SavageFactions.plugin.mc17) { + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - dummyItem.setItemMeta(meta); + dummyItem.setItemMeta(meta); - List dummySlots = section.getIntegerList("dummy-items." + key); - for (Integer slot : dummySlots) { - if (slot + 1 > guiSize || slot < 0) { - SavageFactions.plugin.log(Level.WARNING, "Invalid slot: " + slot + " for dummy item: " + key); - continue; - } - usedDummySlots.add(slot); - actionGUI.setItem(slot, dummyItem); - } - } - } + List dummySlots = section.getIntegerList("dummy-items." + key); + for (Integer slot : dummySlots) { + if (slot + 1 > guiSize || slot < 0) { + SavageFactions.plugin.log(Level.WARNING, "Invalid slot: " + slot + " for dummy item: " + key); + continue; + } + usedDummySlots.add(slot); + actionGUI.setItem(slot, dummyItem); + } + } + } - private ItemStack buildDummyItem(int id) { - final ConfigurationSection dummySection = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.dummy-items." + id); + private ItemStack buildDummyItem(int id) { + final ConfigurationSection dummySection = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.dummy-items." + id); - if (dummySection == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build dummy items for F PERM GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return new ItemStack(Material.AIR); - } + if (dummySection == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build dummy items for F PERM GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return new ItemStack(Material.AIR); + } - Material material = Material.matchMaterial(dummySection.getString("material", "")); - if (material == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid material for dummy item: " + id); - return null; - } + Material material = Material.matchMaterial(dummySection.getString("material", "")); + if (material == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid material for dummy item: " + id); + return null; + } - ItemStack itemStack = new ItemStack(material); + ItemStack itemStack = new ItemStack(material); - DyeColor color; - try { - color = DyeColor.valueOf(dummySection.getString("color", "")); - } catch (Exception exception) { - color = null; - } - if (color != null) { - itemStack.setDurability(color.getWoolData()); - } + DyeColor color; + try { + color = DyeColor.valueOf(dummySection.getString("color", "")); + } catch (Exception exception) { + color = null; + } + if (color != null) { + itemStack.setDurability(color.getWoolData()); + } - ItemMeta itemMeta = itemStack.getItemMeta(); + ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', dummySection.getString("name", " "))); + itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', dummySection.getString("name", " "))); - List lore = new ArrayList<>(); - for (String loreLine : dummySection.getStringList("lore")) { - lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); - } + List lore = new ArrayList<>(); + for (String loreLine : dummySection.getStringList("lore")) { + lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); + } - itemMeta.setLore(lore); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + itemMeta.setLore(lore); + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - itemStack.setItemMeta(itemMeta); + itemStack.setItemMeta(itemMeta); - return itemStack; - } + return itemStack; + } - public enum SpecialItem { - BACK, - RELATION; + public enum SpecialItem { + BACK, + RELATION; - static boolean isSpecial(String string) { - return fromString(string) != null; - } + static boolean isSpecial(String string) { + return fromString(string) != null; + } - static SpecialItem fromString(String string) { - for (SpecialItem specialItem : SpecialItem.values()) { - if (string.equalsIgnoreCase(specialItem.name())) { - return specialItem; - } - } - return null; - } - } + static SpecialItem fromString(String string) { + for (SpecialItem specialItem : SpecialItem.values()) { + if (string.equalsIgnoreCase(specialItem.name())) { + return specialItem; + } + } + return null; + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationGUI.java b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationGUI.java index 871ee281..200af74d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationGUI.java +++ b/src/main/java/com/massivecraft/factions/zcore/fperms/gui/PermissableRelationGUI.java @@ -26,184 +26,184 @@ import java.util.logging.Level; public class PermissableRelationGUI implements InventoryHolder, FactionGUI { - private final ConfigurationSection section; - private Inventory relationGUI; - private FPlayer fme; - private int guiSize; - private HashMap relationSlots = new HashMap<>(); + private final ConfigurationSection section; + private Inventory relationGUI; + private FPlayer fme; + private int guiSize; + private HashMap relationSlots = new HashMap<>(); - public PermissableRelationGUI(FPlayer fme) { - this.fme = fme; - this.section = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.relation"); - } + public PermissableRelationGUI(FPlayer fme) { + this.fme = fme; + this.section = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.relation"); + } - public void build() { - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return; - } + public void build() { + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return; + } - // Build basic Inventory info - guiSize = section.getInt("rows", 3); - if (guiSize > 5) { - guiSize = 5; - SavageFactions.plugin.log(Level.INFO, "Relation GUI size out of bounds, defaulting to 5"); - } + // Build basic Inventory info + guiSize = section.getInt("rows", 3); + if (guiSize > 5) { + guiSize = 5; + SavageFactions.plugin.log(Level.INFO, "Relation GUI size out of bounds, defaulting to 5"); + } - guiSize *= 9; - String guiName = ChatColor.translateAlternateColorCodes('&', section.getString("name", "FactionPermissions")); - relationGUI = Bukkit.createInventory(this, guiSize, guiName); + guiSize *= 9; + String guiName = ChatColor.translateAlternateColorCodes('&', section.getString("name", "FactionPermissions")); + relationGUI = Bukkit.createInventory(this, guiSize, guiName); - for (String key : section.getConfigurationSection("slots").getKeys(false)) { - int slot = section.getInt("slots." + key); - if (slot == -1) { - continue; - } - if (slot + 1 > guiSize && slot > 0) { - SavageFactions.plugin.log(Level.WARNING, "Invalid slot of " + key.toUpperCase() + " in relation GUI skipping it"); - continue; - } + for (String key : section.getConfigurationSection("slots").getKeys(false)) { + int slot = section.getInt("slots." + key); + if (slot == -1) { + continue; + } + if (slot + 1 > guiSize && slot > 0) { + SavageFactions.plugin.log(Level.WARNING, "Invalid slot of " + key.toUpperCase() + " in relation GUI skipping it"); + continue; + } - if (getPermissable(key) == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid permissable " + key.toUpperCase() + " skipping it"); - continue; - } + if (getPermissable(key) == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid permissable " + key.toUpperCase() + " skipping it"); + continue; + } - relationSlots.put(slot, getPermissable(key)); - } + relationSlots.put(slot, getPermissable(key)); + } - buildDummyItems(); - buildItems(); - } + buildDummyItems(); + buildItems(); + } - @Override - public Inventory getInventory() { - return relationGUI; - } + @Override + public Inventory getInventory() { + return relationGUI; + } - @Override - public void onClick(int slot, ClickType clickType) { - if (!relationSlots.containsKey(slot)) { - return; - } + @Override + public void onClick(int slot, ClickType clickType) { + if (!relationSlots.containsKey(slot)) { + return; + } - PermissableActionGUI actionGUI = new PermissableActionGUI(fme, relationSlots.get(slot)); - actionGUI.build(); + PermissableActionGUI actionGUI = new PermissableActionGUI(fme, relationSlots.get(slot)); + actionGUI.build(); - fme.getPlayer().openInventory(actionGUI.getInventory()); - } + fme.getPlayer().openInventory(actionGUI.getInventory()); + } - private Permissable getPermissable(String name) { - if (Role.fromString(name.toUpperCase()) != null) { - return Role.fromString(name.toUpperCase()); - } else if (Relation.fromString(name.toUpperCase()) != null) { - return Relation.fromString(name.toUpperCase()); - } else { - return null; - } - } + private Permissable getPermissable(String name) { + if (Role.fromString(name.toUpperCase()) != null) { + return Role.fromString(name.toUpperCase()); + } else if (Relation.fromString(name.toUpperCase()) != null) { + return Relation.fromString(name.toUpperCase()); + } else { + return null; + } + } - private void buildItems() { - for (Map.Entry entry : relationSlots.entrySet()) { - Permissable permissable = entry.getValue(); + private void buildItems() { + for (Map.Entry entry : relationSlots.entrySet()) { + Permissable permissable = entry.getValue(); - ItemStack item = permissable.buildItem(); + ItemStack item = permissable.buildItem(); - if (item == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid material for " + permissable.toString().toUpperCase() + " skipping it"); - continue; - } + if (item == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid material for " + permissable.toString().toUpperCase() + " skipping it"); + continue; + } - relationGUI.setItem(entry.getKey(), item); - } - } + relationGUI.setItem(entry.getKey(), item); + } + } - private void buildDummyItems() { - if (section == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return; - } + private void buildDummyItems() { + if (section == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return; + } - for (String key : section.getConfigurationSection("dummy-items").getKeys(false)) { - int dummyId; - try { - dummyId = Integer.parseInt(key); - } catch (NumberFormatException exception) { - SavageFactions.plugin.log(Level.WARNING, "Invalid dummy item id: " + key.toUpperCase()); - continue; - } + for (String key : section.getConfigurationSection("dummy-items").getKeys(false)) { + int dummyId; + try { + dummyId = Integer.parseInt(key); + } catch (NumberFormatException exception) { + SavageFactions.plugin.log(Level.WARNING, "Invalid dummy item id: " + key.toUpperCase()); + continue; + } - ItemStack dummyItem = buildDummyItem(dummyId); - if (dummyItem == null) { - continue; - } + ItemStack dummyItem = buildDummyItem(dummyId); + if (dummyItem == null) { + continue; + } - ItemMeta meta = dummyItem.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + ItemMeta meta = dummyItem.getItemMeta(); + if (!SavageFactions.plugin.mc17) { + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - dummyItem.setItemMeta(meta); + dummyItem.setItemMeta(meta); - List dummySlots = section.getIntegerList("dummy-items." + key); - for (Integer slot : dummySlots) { - if (slot + 1 > guiSize || slot < 0) { - SavageFactions.plugin.log(Level.WARNING, "Invalid slot: " + slot + " for dummy item: " + key); - continue; - } - relationGUI.setItem(slot, dummyItem); - } - } - } + List dummySlots = section.getIntegerList("dummy-items." + key); + for (Integer slot : dummySlots) { + if (slot + 1 > guiSize || slot < 0) { + SavageFactions.plugin.log(Level.WARNING, "Invalid slot: " + slot + " for dummy item: " + key); + continue; + } + relationGUI.setItem(slot, dummyItem); + } + } + } - private ItemStack buildDummyItem(int id) { - final ConfigurationSection dummySection = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.dummy-items." + id); + private ItemStack buildDummyItem(int id) { + final ConfigurationSection dummySection = SavageFactions.plugin.getConfig().getConfigurationSection("fperm-gui.dummy-items." + id); - if (dummySection == null) { - SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); - SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); - return new ItemStack(Material.AIR); - } + if (dummySection == null) { + SavageFactions.plugin.log(Level.WARNING, "Attempted to build f perm GUI but config section not present."); + SavageFactions.plugin.log(Level.WARNING, "Copy your config, allow the section to generate, then copy it back to your old config."); + return new ItemStack(Material.AIR); + } - Material material = Material.matchMaterial(dummySection.getString("material", "")); - if (material == null) { - SavageFactions.plugin.log(Level.WARNING, "Invalid material for dummy item: " + id); - return null; - } + Material material = Material.matchMaterial(dummySection.getString("material", "")); + if (material == null) { + SavageFactions.plugin.log(Level.WARNING, "Invalid material for dummy item: " + id); + return null; + } - ItemStack itemStack = new ItemStack(material); + ItemStack itemStack = new ItemStack(material); - DyeColor color; - try { - color = DyeColor.valueOf(dummySection.getString("color", "")); - } catch (Exception exception) { - color = null; - } - if (color != null) { - itemStack.setDurability(color.getWoolData()); - } + DyeColor color; + try { + color = DyeColor.valueOf(dummySection.getString("color", "")); + } catch (Exception exception) { + color = null; + } + if (color != null) { + itemStack.setDurability(color.getWoolData()); + } - ItemMeta itemMeta = itemStack.getItemMeta(); + ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', dummySection.getString("name", " "))); + itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', dummySection.getString("name", " "))); - List lore = new ArrayList<>(); - for (String loreLine : dummySection.getStringList("lore")) { - lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); - } - itemMeta.setLore(lore); + List lore = new ArrayList<>(); + for (String loreLine : dummySection.getStringList("lore")) { + lore.add(ChatColor.translateAlternateColorCodes('&', loreLine)); + } + itemMeta.setLore(lore); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); - } + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); + } - itemStack.setItemMeta(itemMeta); + itemStack.setItemMeta(itemMeta); - return itemStack; - } + return itemStack; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java index a12f496d..a98490ac 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/CropUpgrades.java @@ -17,62 +17,62 @@ import java.util.concurrent.ThreadLocalRandom; public class CropUpgrades implements Listener { - @EventHandler - public void onCropGrow(BlockGrowEvent e) { - FLocation floc = new FLocation(e.getBlock().getLocation()); - Faction factionAtLoc = Board.getInstance().getFactionAt(floc); + @EventHandler + public void onCropGrow(BlockGrowEvent e) { + FLocation floc = new FLocation(e.getBlock().getLocation()); + Faction factionAtLoc = Board.getInstance().getFactionAt(floc); - if (!factionAtLoc.isWilderness()) { - int level = factionAtLoc.getUpgrade(Upgrade.CROP); - if (level != 0) { - int chance = -1; + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(Upgrade.CROP); + if (level != 0) { + int chance = -1; - switch (level) { - case 1: - chance = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); - break; - case 2: - chance = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); - break; - case 3: - chance = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3"); - break; - } + switch (level) { + case 1: + chance = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-1"); + break; + case 2: + chance = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-2"); + break; + case 3: + chance = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Crop-Boost.level-3"); + break; + } - if (chance >= 0) { - int randomNum = ThreadLocalRandom.current().nextInt(1, 100 + 1); - if (randomNum <= chance) - growCrop(e); - } - } - } - } + if (chance >= 0) { + int randomNum = ThreadLocalRandom.current().nextInt(1, 100 + 1); + if (randomNum <= chance) + growCrop(e); + } + } + } + } - private void growCrop(BlockGrowEvent e) { + private void growCrop(BlockGrowEvent e) { - if (e.getBlock().getType().equals(SavageFactions.plugin.CROPS)) { - e.setCancelled(true); - Crops c = new Crops(CropState.RIPE); - BlockState bs = e.getBlock().getState(); - bs.setData(c); - bs.update(); - } + if (e.getBlock().getType().equals(SavageFactions.plugin.CROPS)) { + e.setCancelled(true); + Crops c = new Crops(CropState.RIPE); + BlockState bs = e.getBlock().getState(); + bs.setData(c); + bs.update(); + } - Block below = e.getBlock().getLocation().subtract(0, 1, 0).getBlock(); + Block below = e.getBlock().getLocation().subtract(0, 1, 0).getBlock(); - if (below.getType() == SavageFactions.plugin.SUGAR_CANE_BLOCK) { - Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); + if (below.getType() == SavageFactions.plugin.SUGAR_CANE_BLOCK) { + Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); - if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { - above.setType(SavageFactions.plugin.SUGAR_CANE_BLOCK); - } + if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { + above.setType(SavageFactions.plugin.SUGAR_CANE_BLOCK); + } - } else if (below.getType() == Material.CACTUS) { - Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); + } else if (below.getType() == Material.CACTUS) { + Block above = e.getBlock().getLocation().add(0, 1, 0).getBlock(); - if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { - above.setType(Material.CACTUS); - } - } - } + if (above.getType() == Material.AIR && above.getLocation().add(0, -2, 0).getBlock().getType() != Material.AIR) { + above.setType(Material.CACTUS); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java index 473f70f0..a5a13594 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/EXPUpgrade.java @@ -12,42 +12,42 @@ import org.bukkit.event.entity.EntityDeathEvent; public class EXPUpgrade implements Listener { - @EventHandler - public void onDeath(EntityDeathEvent e) { - Entity killer = e.getEntity().getKiller(); + @EventHandler + public void onDeath(EntityDeathEvent e) { + Entity killer = e.getEntity().getKiller(); - if (killer == null || !(killer instanceof Player)) - return; + if (killer == null || !(killer instanceof Player)) + return; - FLocation floc = new FLocation(e.getEntity().getLocation()); - Faction faction = Board.getInstance().getFactionAt(floc); + FLocation floc = new FLocation(e.getEntity().getLocation()); + Faction faction = Board.getInstance().getFactionAt(floc); - if (!faction.isWilderness()) { - int level = faction.getUpgrade(Upgrade.EXP); - if (level != 0) { + if (!faction.isWilderness()) { + int level = faction.getUpgrade(Upgrade.EXP); + if (level != 0) { - double multiplier = -1; + double multiplier = -1; - switch (level) { - case 1: - multiplier = SavageFactions.plugin.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); - break; - case 2: - multiplier = SavageFactions.plugin.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); - break; - case 3: - multiplier = SavageFactions.plugin.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3"); - break; - } + switch (level) { + case 1: + multiplier = SavageFactions.plugin.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-1"); + break; + case 2: + multiplier = SavageFactions.plugin.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-2"); + break; + case 3: + multiplier = SavageFactions.plugin.getConfig().getDouble("fupgrades.MainMenu.EXP.EXP-Boost.level-3"); + break; + } - if (multiplier >= 0) - spawnMoreExp(e, multiplier); - } - } - } + if (multiplier >= 0) + spawnMoreExp(e, multiplier); + } + } + } - private void spawnMoreExp(EntityDeathEvent e, double multiplier) { - double newExp = e.getDroppedExp() * multiplier; - e.setDroppedExp((int) newExp); - } + private void spawnMoreExp(EntityDeathEvent e, double multiplier) { + double newExp = e.getDroppedExp() * multiplier; + e.setDroppedExp((int) newExp); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java index 0e14eb6e..b98b8d93 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/FUpgradesGUI.java @@ -20,278 +20,278 @@ import java.util.List; public class FUpgradesGUI implements Listener { - public void openMainMenu(FPlayer fme) { - Inventory inventory = Bukkit.createInventory(null, 27, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Title").replace("{faction}", fme.getFaction().getTag()))); - List dummySlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.DummyItem.slots"); - Material dummyMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.DummyItem.Type")); - int dummyAmount = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.DummyItem.Amount"); - short dummyData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.DummyItem.Damage") + ""); - ItemStack dummyItem = SavageFactions.plugin.createItem(dummyMaterial, - dummyAmount, - dummyData, - SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.DummyItem.Name")), - SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.DummyItem.Lore"))); + public void openMainMenu(FPlayer fme) { + Inventory inventory = Bukkit.createInventory(null, 27, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Title").replace("{faction}", fme.getFaction().getTag()))); + List dummySlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.DummyItem.slots"); + Material dummyMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.DummyItem.Type")); + int dummyAmount = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.DummyItem.Amount"); + short dummyData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.DummyItem.Damage") + ""); + ItemStack dummyItem = SavageFactions.plugin.createItem(dummyMaterial, + dummyAmount, + dummyData, + SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.DummyItem.Name")), + SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.DummyItem.Lore"))); - for (int i = 0; i <= dummySlots.size() - 1; i++) { - inventory.setItem(dummySlots.get(i), dummyItem); - } + for (int i = 0; i <= dummySlots.size() - 1; i++) { + inventory.setItem(dummySlots.get(i), dummyItem); + } - ItemStack[] items = buildItems(fme); - List cropSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Crops.CropItem.slots"); - List spawnerSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Spawners.SpawnerItem.slots"); - List expSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.EXP.EXPItem.slots"); - List chestSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Chest.ChestItem.slots"); + ItemStack[] items = buildItems(fme); + List cropSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Crops.CropItem.slots"); + List spawnerSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Spawners.SpawnerItem.slots"); + List expSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.EXP.EXPItem.slots"); + List chestSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Chest.ChestItem.slots"); - for (int i = 0; i < cropSlots.size(); i++) - inventory.setItem(cropSlots.get(i), items[2]); + for (int i = 0; i < cropSlots.size(); i++) + inventory.setItem(cropSlots.get(i), items[2]); - for (int i = 0; i < spawnerSlots.size(); i++) - inventory.setItem(spawnerSlots.get(i), items[1]); + for (int i = 0; i < spawnerSlots.size(); i++) + inventory.setItem(spawnerSlots.get(i), items[1]); - for (int i = 0; i < expSlots.size(); i++) - inventory.setItem(expSlots.get(i), items[0]); + for (int i = 0; i < expSlots.size(); i++) + inventory.setItem(expSlots.get(i), items[0]); - for (int i = 0; i < chestSlots.size(); i++) - inventory.setItem(chestSlots.get(i), items[3]); + for (int i = 0; i < chestSlots.size(); i++) + inventory.setItem(chestSlots.get(i), items[3]); - fme.getPlayer().openInventory(inventory); - } + fme.getPlayer().openInventory(inventory); + } - @EventHandler - public void onClick(InventoryClickEvent e) { - if (e.getClickedInventory() == null || e.getCurrentItem() == null || e.getCurrentItem().getItemMeta() == null || e.getCursor() == null) - return; + @EventHandler + public void onClick(InventoryClickEvent e) { + if (e.getClickedInventory() == null || e.getCurrentItem() == null || e.getCurrentItem().getItemMeta() == null || e.getCursor() == null) + return; - FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); - if (e.getClickedInventory().getTitle().equalsIgnoreCase(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Title").replace("{faction}", fme.getFaction().getTag())))) { - e.setCancelled(true); - ItemStack[] items = buildItems(fme); - ItemStack cropItem = items[2]; - ItemStack expItem = items[0]; - ItemStack chestitem = items[3]; - ItemStack spawnerItem = items[1]; + FPlayer fme = FPlayers.getInstance().getByPlayer((Player) e.getWhoClicked()); + if (e.getClickedInventory().getTitle().equalsIgnoreCase(SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Title").replace("{faction}", fme.getFaction().getTag())))) { + e.setCancelled(true); + ItemStack[] items = buildItems(fme); + ItemStack cropItem = items[2]; + ItemStack expItem = items[0]; + ItemStack chestitem = items[3]; + ItemStack spawnerItem = items[1]; - if (e.getCurrentItem().equals(cropItem)) { - int cropLevel = fme.getFaction().getUpgrade(Upgrade.CROP); + if (e.getCurrentItem().equals(cropItem)) { + int cropLevel = fme.getFaction().getUpgrade(Upgrade.CROP); - switch (cropLevel) { - case 3: - return; - case 2: - upgradeItem(fme, Upgrade.CROP, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-3")); - break; - case 1: - upgradeItem(fme, Upgrade.CROP, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-2")); - break; - case 0: - upgradeItem(fme, Upgrade.CROP, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-1")); - break; - } - } else if (e.getCurrentItem().equals(spawnerItem)) { - int spawnerLevel = fme.getFaction().getUpgrade(Upgrade.SPAWNER); + switch (cropLevel) { + case 3: + return; + case 2: + upgradeItem(fme, Upgrade.CROP, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-3")); + break; + case 1: + upgradeItem(fme, Upgrade.CROP, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-2")); + break; + case 0: + upgradeItem(fme, Upgrade.CROP, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.Cost.level-1")); + break; + } + } else if (e.getCurrentItem().equals(spawnerItem)) { + int spawnerLevel = fme.getFaction().getUpgrade(Upgrade.SPAWNER); - switch (spawnerLevel) { - case 3: - return; - case 2: - upgradeItem(fme, Upgrade.SPAWNER, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-3")); - break; - case 1: - upgradeItem(fme, Upgrade.SPAWNER, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-2")); - break; - case 0: - upgradeItem(fme, Upgrade.SPAWNER, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-1")); - break; - } - } else if (e.getCurrentItem().equals(expItem)) { - int expLevel = fme.getFaction().getUpgrade(Upgrade.EXP); + switch (spawnerLevel) { + case 3: + return; + case 2: + upgradeItem(fme, Upgrade.SPAWNER, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-3")); + break; + case 1: + upgradeItem(fme, Upgrade.SPAWNER, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-2")); + break; + case 0: + upgradeItem(fme, Upgrade.SPAWNER, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Cost.level-1")); + break; + } + } else if (e.getCurrentItem().equals(expItem)) { + int expLevel = fme.getFaction().getUpgrade(Upgrade.EXP); - switch (expLevel) { - case 3: - return; - case 2: - upgradeItem(fme, Upgrade.EXP, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-3")); - break; - case 1: - upgradeItem(fme, Upgrade.EXP, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-2")); - break; - case 0: - upgradeItem(fme, Upgrade.EXP, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-1")); - break; - } - } else if (e.getCurrentItem().equals(chestitem)) { - int chestLevel = fme.getFaction().getUpgrade(Upgrade.CHEST); + switch (expLevel) { + case 3: + return; + case 2: + upgradeItem(fme, Upgrade.EXP, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-3")); + break; + case 1: + upgradeItem(fme, Upgrade.EXP, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-2")); + break; + case 0: + upgradeItem(fme, Upgrade.EXP, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.Cost.level-1")); + break; + } + } else if (e.getCurrentItem().equals(chestitem)) { + int chestLevel = fme.getFaction().getUpgrade(Upgrade.CHEST); - switch (chestLevel) { - case 3: - return; - case 2: { - if (upgradeItem(fme, Upgrade.CHEST, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-3"))) - updateChests(fme.getFaction()); - break; - } - case 1: { - if (upgradeItem(fme, Upgrade.CHEST, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-2"))) - updateChests(fme.getFaction()); - break; - } - case 0: { - if (upgradeItem(fme, Upgrade.CHEST, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-1"))) - updateChests(fme.getFaction()); - break; - } - } - } - } - } + switch (chestLevel) { + case 3: + return; + case 2: { + if (upgradeItem(fme, Upgrade.CHEST, 3, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-3"))) + updateChests(fme.getFaction()); + break; + } + case 1: { + if (upgradeItem(fme, Upgrade.CHEST, 2, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-2"))) + updateChests(fme.getFaction()); + break; + } + case 0: { + if (upgradeItem(fme, Upgrade.CHEST, 1, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Cost.level-1"))) + updateChests(fme.getFaction()); + break; + } + } + } + } + } - private void updateChests(Faction faction) { - String invName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fchest.Inventory-Title")); + private void updateChests(Faction faction) { + String invName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fchest.Inventory-Title")); - for (Player player : faction.getOnlinePlayers()) { - if (player.getInventory().getTitle() != null && player.getInventory().getTitle().equalsIgnoreCase(invName)) - player.closeInventory(); - } + for (Player player : faction.getOnlinePlayers()) { + if (player.getInventory().getTitle() != null && player.getInventory().getTitle().equalsIgnoreCase(invName)) + player.closeInventory(); + } - int level = faction.getUpgrade(Upgrade.CHEST); - int size = 1; + int level = faction.getUpgrade(Upgrade.CHEST); + int size = 1; - switch (level) { - case 1: - size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1"); - break; - case 2: - size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2"); - break; - case 3: - size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3"); - break; - } - faction.setChestSize(size * 9); - } + switch (level) { + case 1: + size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1"); + break; + case 2: + size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2"); + break; + case 3: + size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3"); + break; + } + faction.setChestSize(size * 9); + } - private ItemStack[] buildItems(FPlayer fme) { - Material expMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Type")); - int expAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Amount"); - short expData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Damage") + ""); - String expName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Name")); - List expLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.EXP.EXPItem.Lore")); - int expLevel = fme.getFaction().getUpgrade(Upgrade.EXP); + private ItemStack[] buildItems(FPlayer fme) { + Material expMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Type")); + int expAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Amount"); + short expData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.EXP.EXPItem.Damage") + ""); + String expName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.EXP.EXPItem.Name")); + List expLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.EXP.EXPItem.Lore")); + int expLevel = fme.getFaction().getUpgrade(Upgrade.EXP); - for (int i = 0; i <= expLore.size() - 1; i++) - expLore.set(i, expLore.get(i).replace("{level}", expLevel + "")); + for (int i = 0; i <= expLore.size() - 1; i++) + expLore.set(i, expLore.get(i).replace("{level}", expLevel + "")); - ItemStack expItem = SavageFactions.plugin.createItem(expMaterial, expAmt, expData, expName, expLore); + ItemStack expItem = SavageFactions.plugin.createItem(expMaterial, expAmt, expData, expName, expLore); - if (expLevel >= 1) { - ItemMeta itemMeta = expItem.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + if (expLevel >= 1) { + ItemMeta itemMeta = expItem.getItemMeta(); + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - expItem.setItemMeta(itemMeta); - expItem.setAmount(expLevel); - } + expItem.setItemMeta(itemMeta); + expItem.setAmount(expLevel); + } - Material spawnerMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Type")); - int spawnerAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Amount"); - short spawnerData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Damage") + ""); - String spawnerName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Name")); - List spawnerLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.Spawners.SpawnerItem.Lore")); + Material spawnerMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Type")); + int spawnerAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Amount"); + short spawnerData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.SpawnerItem.Damage") + ""); + String spawnerName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Spawners.SpawnerItem.Name")); + List spawnerLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.Spawners.SpawnerItem.Lore")); - List spawnerSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Spawners.SpawnerItem.slots"); - int spawnerLevel = fme.getFaction().getUpgrade(Upgrade.SPAWNER); + List spawnerSlots = SavageFactions.plugin.getConfig().getIntegerList("fupgrades.MainMenu.Spawners.SpawnerItem.slots"); + int spawnerLevel = fme.getFaction().getUpgrade(Upgrade.SPAWNER); - for (int i = 0; i <= spawnerLore.size() - 1; i++) { - spawnerLore.set(i, spawnerLore.get(i).replace("{level}", spawnerLevel + "")); - } + for (int i = 0; i <= spawnerLore.size() - 1; i++) { + spawnerLore.set(i, spawnerLore.get(i).replace("{level}", spawnerLevel + "")); + } - Material cropMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Type")); - int cropAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount"); - short cropData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + ""); - String cropName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Name")); - List cropLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.Crops.CropItem.Lore")); - int cropLevel = fme.getFaction().getUpgrade(Upgrade.CROP); + Material cropMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Type")); + int cropAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Amount"); + short cropData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Crops.CropItem.Damage") + ""); + String cropName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Crops.CropItem.Name")); + List cropLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.Crops.CropItem.Lore")); + int cropLevel = fme.getFaction().getUpgrade(Upgrade.CROP); - for (int i = 0; i <= cropLore.size() - 1; i++) { - String line = cropLore.get(i); - line = line.replace("{level}", cropLevel + ""); - cropLore.set(i, line); - } + for (int i = 0; i <= cropLore.size() - 1; i++) { + String line = cropLore.get(i); + line = line.replace("{level}", cropLevel + ""); + cropLore.set(i, line); + } - ItemStack cropItem = SavageFactions.plugin.createItem(cropMaterial, cropAmt, cropData, cropName, cropLore); - cropItem.getItemMeta().setLore(cropLore); + ItemStack cropItem = SavageFactions.plugin.createItem(cropMaterial, cropAmt, cropData, cropName, cropLore); + cropItem.getItemMeta().setLore(cropLore); - if (cropLevel >= 1) { - ItemMeta itemMeta = cropItem.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - cropItem.setItemMeta(itemMeta); + if (cropLevel >= 1) { + ItemMeta itemMeta = cropItem.getItemMeta(); + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + cropItem.setItemMeta(itemMeta); - cropItem.setAmount(cropLevel); - } + cropItem.setAmount(cropLevel); + } - ItemStack spawnerItem = SavageFactions.plugin.createItem(spawnerMaterial, spawnerAmt, spawnerData, spawnerName, spawnerLore); - spawnerItem.getItemMeta().setLore(spawnerLore); - if (spawnerLevel >= 1) { - ItemMeta itemMeta = spawnerItem.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + ItemStack spawnerItem = SavageFactions.plugin.createItem(spawnerMaterial, spawnerAmt, spawnerData, spawnerName, spawnerLore); + spawnerItem.getItemMeta().setLore(spawnerLore); + if (spawnerLevel >= 1) { + ItemMeta itemMeta = spawnerItem.getItemMeta(); + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - spawnerItem.setItemMeta(itemMeta); - spawnerItem.setAmount(spawnerLevel); - } + spawnerItem.setItemMeta(itemMeta); + spawnerItem.setAmount(spawnerLevel); + } - Material chestMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Type")); - int chesttAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Amount"); - short chestData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Damage") + ""); - String chestName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Name", "&e&lUpgrade Chest Size")); - List chestLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.Chest.ChestItem.Lore")); - int chestlevel = fme.getFaction().getUpgrade(Upgrade.CHEST); + Material chestMaterial = Material.getMaterial(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Type")); + int chesttAmt = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Amount"); + short chestData = Short.parseShort(SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.ChestItem.Damage") + ""); + String chestName = SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fupgrades.MainMenu.Chest.ChestItem.Name", "&e&lUpgrade Chest Size")); + List chestLore = SavageFactions.plugin.colorList(SavageFactions.plugin.getConfig().getStringList("fupgrades.MainMenu.Chest.ChestItem.Lore")); + int chestlevel = fme.getFaction().getUpgrade(Upgrade.CHEST); - for (int i = 0; i <= chestLore.size() - 1; i++) { - String line = chestLore.get(i); - line = line.replace("{level}", chestlevel + ""); - chestLore.set(i, line); - } + for (int i = 0; i <= chestLore.size() - 1; i++) { + String line = chestLore.get(i); + line = line.replace("{level}", chestlevel + ""); + chestLore.set(i, line); + } - ItemStack chestItem = SavageFactions.plugin.createItem(chestMaterial, chesttAmt, chestData, chestName, chestLore); + ItemStack chestItem = SavageFactions.plugin.createItem(chestMaterial, chesttAmt, chestData, chestName, chestLore); - if (chestlevel >= 1) { - ItemMeta itemMeta = chestItem.getItemMeta(); - if (!SavageFactions.plugin.mc17) { - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); + if (chestlevel >= 1) { + ItemMeta itemMeta = chestItem.getItemMeta(); + if (!SavageFactions.plugin.mc17) { + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + } + itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); - chestItem.setItemMeta(itemMeta); - chestItem.setAmount(chestlevel); - } + chestItem.setItemMeta(itemMeta); + chestItem.setAmount(chestlevel); + } - ItemStack[] items = {expItem, spawnerItem, cropItem, chestItem}; - return items; - } + ItemStack[] items = {expItem, spawnerItem, cropItem, chestItem}; + return items; + } - private boolean hasMoney(FPlayer fme, int amt) { - return fme.hasMoney(amt); - } + private boolean hasMoney(FPlayer fme, int amt) { + return fme.hasMoney(amt); + } - private void takeMoney(FPlayer fme, int amt) { - fme.takeMoney(amt); - } + private void takeMoney(FPlayer fme, int amt) { + fme.takeMoney(amt); + } - private boolean upgradeItem(FPlayer fme, Upgrade upgrade, int level, int cost) { - if (hasMoney(fme, cost)) { - takeMoney(fme, cost); - fme.getFaction().setUpgrade(upgrade, level); - fme.getPlayer().closeInventory(); - return true; - } - return false; - } + private boolean upgradeItem(FPlayer fme, Upgrade upgrade, int level, int cost) { + if (hasMoney(fme, cost)) { + takeMoney(fme, cost); + fme.getFaction().setUpgrade(upgrade, level); + fme.getPlayer().closeInventory(); + return true; + } + return false; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java index 209859f5..ad36505f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/SpawnerUpgrades.java @@ -10,32 +10,32 @@ import org.bukkit.event.entity.SpawnerSpawnEvent; public class SpawnerUpgrades implements Listener { - @EventHandler - public void onSpawn(SpawnerSpawnEvent e) { - FLocation floc = new FLocation(e.getLocation()); - Faction factionAtLoc = Board.getInstance().getFactionAt(floc); + @EventHandler + public void onSpawn(SpawnerSpawnEvent e) { + FLocation floc = new FLocation(e.getLocation()); + Faction factionAtLoc = Board.getInstance().getFactionAt(floc); - if (!factionAtLoc.isWilderness()) { - int level = factionAtLoc.getUpgrade(Upgrade.SPAWNER); - if (level != 0) { - switch (level) { - case 1: - lowerSpawnerDelay(e, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); - break; - case 2: - lowerSpawnerDelay(e, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); - break; - case 3: - lowerSpawnerDelay(e, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3")); - break; - } - } - } - } + if (!factionAtLoc.isWilderness()) { + int level = factionAtLoc.getUpgrade(Upgrade.SPAWNER); + if (level != 0) { + switch (level) { + case 1: + lowerSpawnerDelay(e, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-1")); + break; + case 2: + lowerSpawnerDelay(e, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-2")); + break; + case 3: + lowerSpawnerDelay(e, SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Spawners.Spawner-Boost.level-3")); + break; + } + } + } + } - private void lowerSpawnerDelay(SpawnerSpawnEvent e, double multiplier) { - int lowerby = (int) Math.round(e.getSpawner().getDelay() * multiplier); - e.getSpawner().setDelay(e.getSpawner().getDelay() - lowerby); - } + private void lowerSpawnerDelay(SpawnerSpawnEvent e, double multiplier) { + int lowerby = (int) Math.round(e.getSpawner().getDelay() * multiplier); + e.getSpawner().setDelay(e.getSpawner().getDelay() - lowerby); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/fupgrades/Upgrade.java b/src/main/java/com/massivecraft/factions/zcore/fupgrades/Upgrade.java index 98e02172..ef7aa8dc 100644 --- a/src/main/java/com/massivecraft/factions/zcore/fupgrades/Upgrade.java +++ b/src/main/java/com/massivecraft/factions/zcore/fupgrades/Upgrade.java @@ -2,17 +2,17 @@ package com.massivecraft.factions.zcore.fupgrades; public enum Upgrade { - CHEST("Chest"), SPAWNER("Spawner"), EXP("Exp"), CROP("Crop"); + CHEST("Chest"), SPAWNER("Spawner"), EXP("Exp"), CROP("Crop"); - private String id; + private String id; - Upgrade(String id) { - this.id = id; - } + Upgrade(String id) { + this.id = id; + } - @Override - public String toString() { - return this.id; - } + @Override + public String toString() { + return this.id; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java index 8cec2e41..70d4a387 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTCompound.java @@ -7,191 +7,191 @@ import java.util.Set; public class NBTCompound { - private String compundName; - private NBTCompound parent; + private String compundName; + private NBTCompound parent; - protected NBTCompound() { - } + protected NBTCompound() { + } - protected NBTCompound(NBTCompound owner, String name) { - this.compundName = name; - this.parent = owner; - } + protected NBTCompound(NBTCompound owner, String name) { + this.compundName = name; + this.parent = owner; + } - public String getName() { - return compundName; - } + public String getName() { + return compundName; + } - protected Object getCompound() { - return parent.getCompound(); - } + protected Object getCompound() { + return parent.getCompound(); + } - protected void setCompound(Object compound) { - parent.setCompound(compound); - } + protected void setCompound(Object compound) { + parent.setCompound(compound); + } - public NBTCompound getParent() { - return parent; - } + public NBTCompound getParent() { + return parent; + } - public void mergeCompound(NBTCompound comp) { - NBTReflectionUtil.addOtherNBTCompound(this, comp); - } + public void mergeCompound(NBTCompound comp) { + NBTReflectionUtil.addOtherNBTCompound(this, comp); + } - public void setString(String key, String value) { - NBTReflectionUtil.setString(this, key, value); - } + public void setString(String key, String value) { + NBTReflectionUtil.setString(this, key, value); + } - public String getString(String key) { - return NBTReflectionUtil.getString(this, key); - } + public String getString(String key) { + return NBTReflectionUtil.getString(this, key); + } - protected String getContent(String key) { - return NBTReflectionUtil.getContent(this, key); - } + protected String getContent(String key) { + return NBTReflectionUtil.getContent(this, key); + } - public void setInteger(String key, Integer value) { - NBTReflectionUtil.setInt(this, key, value); - } + public void setInteger(String key, Integer value) { + NBTReflectionUtil.setInt(this, key, value); + } - public Integer getInteger(String key) { - return NBTReflectionUtil.getInt(this, key); - } + public Integer getInteger(String key) { + return NBTReflectionUtil.getInt(this, key); + } - public void setDouble(String key, Double value) { - NBTReflectionUtil.setDouble(this, key, value); - } + public void setDouble(String key, Double value) { + NBTReflectionUtil.setDouble(this, key, value); + } - public Double getDouble(String key) { - return NBTReflectionUtil.getDouble(this, key); - } + public Double getDouble(String key) { + return NBTReflectionUtil.getDouble(this, key); + } - public void setByte(String key, Byte value) { - NBTReflectionUtil.setByte(this, key, value); - } + public void setByte(String key, Byte value) { + NBTReflectionUtil.setByte(this, key, value); + } - public Byte getByte(String key) { - return NBTReflectionUtil.getByte(this, key); - } + public Byte getByte(String key) { + return NBTReflectionUtil.getByte(this, key); + } - public void setShort(String key, Short value) { - NBTReflectionUtil.setShort(this, key, value); - } + public void setShort(String key, Short value) { + NBTReflectionUtil.setShort(this, key, value); + } - public Short getShort(String key) { - return NBTReflectionUtil.getShort(this, key); - } + public Short getShort(String key) { + return NBTReflectionUtil.getShort(this, key); + } - public void setLong(String key, Long value) { - NBTReflectionUtil.setLong(this, key, value); - } + public void setLong(String key, Long value) { + NBTReflectionUtil.setLong(this, key, value); + } - public Long getLong(String key) { - return NBTReflectionUtil.getLong(this, key); - } + public Long getLong(String key) { + return NBTReflectionUtil.getLong(this, key); + } - public void setFloat(String key, Float value) { - NBTReflectionUtil.setFloat(this, key, value); - } + public void setFloat(String key, Float value) { + NBTReflectionUtil.setFloat(this, key, value); + } - public Float getFloat(String key) { - return NBTReflectionUtil.getFloat(this, key); - } + public Float getFloat(String key) { + return NBTReflectionUtil.getFloat(this, key); + } - public void setByteArray(String key, byte[] value) { - NBTReflectionUtil.setByteArray(this, key, value); - } + public void setByteArray(String key, byte[] value) { + NBTReflectionUtil.setByteArray(this, key, value); + } - public byte[] getByteArray(String key) { - return NBTReflectionUtil.getByteArray(this, key); - } + public byte[] getByteArray(String key) { + return NBTReflectionUtil.getByteArray(this, key); + } - public void setIntArray(String key, int[] value) { - NBTReflectionUtil.setIntArray(this, key, value); - } + public void setIntArray(String key, int[] value) { + NBTReflectionUtil.setIntArray(this, key, value); + } - public int[] getIntArray(String key) { - return NBTReflectionUtil.getIntArray(this, key); - } + public int[] getIntArray(String key) { + return NBTReflectionUtil.getIntArray(this, key); + } - public void setBoolean(String key, Boolean value) { - NBTReflectionUtil.setBoolean(this, key, value); - } + public void setBoolean(String key, Boolean value) { + NBTReflectionUtil.setBoolean(this, key, value); + } - protected void set(String key, Object val) { - NBTReflectionUtil.set(this, key, val); - } + protected void set(String key, Object val) { + NBTReflectionUtil.set(this, key, val); + } - public Boolean getBoolean(String key) { - return NBTReflectionUtil.getBoolean(this, key); - } + public Boolean getBoolean(String key) { + return NBTReflectionUtil.getBoolean(this, key); + } - public void setObject(String key, Object value) { - NBTReflectionUtil.setObject(this, key, value); - } + public void setObject(String key, Object value) { + NBTReflectionUtil.setObject(this, key, value); + } - public T getObject(String key, Class type) { - return NBTReflectionUtil.getObject(this, key, type); - } + public T getObject(String key, Class type) { + return NBTReflectionUtil.getObject(this, key, type); + } - public Boolean hasKey(String key) { - return NBTReflectionUtil.hasKey(this, key); - } + public Boolean hasKey(String key) { + return NBTReflectionUtil.hasKey(this, key); + } - public void removeKey(String key) { - NBTReflectionUtil.remove(this, key); - } + public void removeKey(String key) { + NBTReflectionUtil.remove(this, key); + } - public Set getKeys() { - return NBTReflectionUtil.getKeys(this); - } + public Set getKeys() { + return NBTReflectionUtil.getKeys(this); + } - public NBTCompound addCompound(String name) { - NBTReflectionUtil.addNBTTagCompound(this, name); - return getCompound(name); - } + public NBTCompound addCompound(String name) { + NBTReflectionUtil.addNBTTagCompound(this, name); + return getCompound(name); + } - public NBTCompound getCompound(String name) { - NBTCompound next = new NBTCompound(this, name); - if (NBTReflectionUtil.valideCompound(next)) return next; - return null; - } + public NBTCompound getCompound(String name) { + NBTCompound next = new NBTCompound(this, name); + if (NBTReflectionUtil.valideCompound(next)) return next; + return null; + } - public NBTList getList(String name, NBTType type) { - return NBTReflectionUtil.getList(this, name, type); - } + public NBTList getList(String name, NBTType type) { + return NBTReflectionUtil.getList(this, name, type); + } - public NBTType getType(String name) { - if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) - return NBTType.NBTTagEnd; - return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); - } + public NBTType getType(String name) { + if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) + return NBTType.NBTTagEnd; + return NBTType.valueOf(NBTReflectionUtil.getType(this, name)); + } - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - for (String key : getKeys()) { - result.append(toString(key)); - } - return result.toString(); - } + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (String key : getKeys()) { + result.append(toString(key)); + } + return result.toString(); + } - public String toString(String key) { - StringBuilder result = new StringBuilder(); - NBTCompound compound = this; - while (compound.getParent() != null) { - result.append(" "); - compound = compound.getParent(); - } - if (this.getType(key) == NBTType.NBTTagCompound) { - return this.getCompound(key).toString(); - } else { - return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); - } - } + public String toString(String key) { + StringBuilder result = new StringBuilder(); + NBTCompound compound = this; + while (compound.getParent() != null) { + result.append(" "); + compound = compound.getParent(); + } + if (this.getType(key) == NBTType.NBTTagCompound) { + return this.getCompound(key).toString(); + } else { + return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); + } + } - public String asNBTString() { - return NBTReflectionUtil.gettoCompount(getCompound(), this).toString(); - } + public String asNBTString() { + return NBTReflectionUtil.gettoCompount(getCompound(), this).toString(); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java index 4652dbc4..6d79ad01 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTContainer.java @@ -2,31 +2,31 @@ package com.massivecraft.factions.zcore.nbtapi; public class NBTContainer extends NBTCompound { - private Object nbt; + private Object nbt; - public NBTContainer() { - this(NBTReflectionUtil.getNewNBTTag()); - } + public NBTContainer() { + this(NBTReflectionUtil.getNewNBTTag()); + } - protected NBTContainer(Object nbt) { - this.nbt = nbt; - } + protected NBTContainer(Object nbt) { + this.nbt = nbt; + } - public NBTContainer(String nbtString) throws IllegalArgumentException { - try { - nbt = NBTReflectionUtil.parseNBT(nbtString); - } catch (Exception ex) { - ex.printStackTrace(); - throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); - } - } + public NBTContainer(String nbtString) throws IllegalArgumentException { + try { + nbt = NBTReflectionUtil.parseNBT(nbtString); + } catch (Exception ex) { + ex.printStackTrace(); + throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); + } + } - protected Object getCompound() { - return nbt; - } + protected Object getCompound() { + return nbt; + } - protected void setCompound(Object tag) { - nbt = tag; - } + protected void setCompound(Object tag) { + nbt = tag; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java index 2417393c..4176dfdc 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTEntity.java @@ -4,18 +4,18 @@ import org.bukkit.entity.Entity; public class NBTEntity extends NBTCompound { - private final Entity ent; + private final Entity ent; - public NBTEntity(Entity entity) { - ent = entity; - } + public NBTEntity(Entity entity) { + ent = entity; + } - protected Object getCompound() { - return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); - } + protected Object getCompound() { + return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent)); + } - protected void setCompound(Object compound) { - NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); - } + protected void setCompound(Object compound) { + NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent)); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java index 20ecd57f..26da8dc0 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTFile.java @@ -7,39 +7,39 @@ import java.io.IOException; public class NBTFile extends NBTCompound { - private final File file; - private Object nbt; + private final File file; + private Object nbt; - public NBTFile(File file) throws IOException { - this.file = file; - if (file.exists()) { - FileInputStream inputsteam = new FileInputStream(file); - nbt = NBTReflectionUtil.readNBTFile(inputsteam); - } else { - nbt = NBTReflectionUtil.getNewNBTTag(); - save(); - } - } + public NBTFile(File file) throws IOException { + this.file = file; + if (file.exists()) { + FileInputStream inputsteam = new FileInputStream(file); + nbt = NBTReflectionUtil.readNBTFile(inputsteam); + } else { + nbt = NBTReflectionUtil.getNewNBTTag(); + save(); + } + } - public void save() throws IOException { - if (!file.exists()) { - file.getParentFile().mkdirs(); - file.createNewFile(); - } - FileOutputStream outStream = new FileOutputStream(file); - NBTReflectionUtil.saveNBTFile(nbt, outStream); - } + public void save() throws IOException { + if (!file.exists()) { + file.getParentFile().mkdirs(); + file.createNewFile(); + } + FileOutputStream outStream = new FileOutputStream(file); + NBTReflectionUtil.saveNBTFile(nbt, outStream); + } - public File getFile() { - return file; - } + public File getFile() { + return file; + } - protected Object getCompound() { - return nbt; - } + protected Object getCompound() { + return nbt; + } - protected void setCompound(Object compound) { - nbt = compound; - } + protected void setCompound(Object compound) { + nbt = compound; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java index 1bd3528c..86d49245 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTItem.java @@ -4,34 +4,34 @@ import org.bukkit.inventory.ItemStack; public class NBTItem extends NBTCompound { - private ItemStack bukkitItem; + private ItemStack bukkitItem; - public NBTItem(ItemStack item) { - bukkitItem = item.clone(); - } + public NBTItem(ItemStack item) { + bukkitItem = item.clone(); + } - public static NBTContainer convertItemtoNBT(ItemStack item) { - return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); - } + public static NBTContainer convertItemtoNBT(ItemStack item) { + return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item)); + } - public static ItemStack convertNBTtoItem(NBTCompound comp) { - return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); - } + public static ItemStack convertNBTtoItem(NBTCompound comp) { + return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp)); + } - protected Object getCompound() { - return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); - } + protected Object getCompound() { + return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); + } - protected void setCompound(Object compound) { - bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); - } + protected void setCompound(Object compound) { + bukkitItem = NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.setNBTTag(compound, NBTReflectionUtil.getNMSItemStack(bukkitItem))); + } - public ItemStack getItem() { - return bukkitItem; - } + public ItemStack getItem() { + return bukkitItem; + } - protected void setItem(ItemStack item) { - bukkitItem = item; - } + protected void setItem(ItemStack item) { + bukkitItem = item; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java index a3d5a985..91726778 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTList.java @@ -6,120 +6,120 @@ import java.lang.reflect.Method; public class NBTList { - private String listName; - private NBTCompound parent; - private NBTType type; - private Object listObject; + private String listName; + private NBTCompound parent; + private NBTType type; + private Object listObject; - protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { - parent = owner; - listName = name; - this.type = type; - this.listObject = list; - if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { - System.err.println("List types != String/Compound are currently not implemented!"); - } - } + protected NBTList(NBTCompound owner, String name, NBTType type, Object list) { + parent = owner; + listName = name; + this.type = type; + this.listObject = list; + if (!(type == NBTType.NBTTagString || type == NBTType.NBTTagCompound)) { + System.err.println("List types != String/Compound are currently not implemented!"); + } + } - protected void save() { - parent.set(listName, listObject); - } + protected void save() { + parent.set(listName, listObject); + } - public NBTListCompound addCompound() { - if (type != NBTType.NBTTagCompound) { - new Throwable("Using Compound method on a non Compound list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); - Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance(); - method.invoke(listObject, compound); - return new NBTListCompound(this, compound); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + public NBTListCompound addCompound() { + if (type != NBTType.NBTTagCompound) { + new Throwable("Using Compound method on a non Compound list!").printStackTrace(); + return null; + } + try { + Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); + Object compound = NBTReflectionUtil.getNBTTagCompound().newInstance(); + method.invoke(listObject, compound); + return new NBTListCompound(this, compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } - public NBTListCompound getCompound(int id) { - if (type != NBTType.NBTTagCompound) { - new Throwable("Using Compound method on a non Compound list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("get", int.class); - Object compound = method.invoke(listObject, id); - return new NBTListCompound(this, compound); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + public NBTListCompound getCompound(int id) { + if (type != NBTType.NBTTagCompound) { + new Throwable("Using Compound method on a non Compound list!").printStackTrace(); + return null; + } + try { + Method method = listObject.getClass().getMethod("get", int.class); + Object compound = method.invoke(listObject, id); + return new NBTListCompound(this, compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } - public String getString(int i) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return null; - } - try { - Method method = listObject.getClass().getMethod("getString", int.class); - return (String) method.invoke(listObject, i); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + public String getString(int i) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return null; + } + try { + Method method = listObject.getClass().getMethod("getString", int.class); + return (String) method.invoke(listObject, i); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } - public void addString(String s) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return; - } - try { - Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); - method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); - save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void addString(String s) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return; + } + try { + Method method = listObject.getClass().getMethod("add", NBTReflectionUtil.getNBTBase()); + method.invoke(listObject, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public void setString(int i, String s) { - if (type != NBTType.NBTTagString) { - new Throwable("Using String method on a non String list!").printStackTrace(); - return; - } - try { - Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase()); - method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); - save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setString(int i, String s) { + if (type != NBTType.NBTTagString) { + new Throwable("Using String method on a non String list!").printStackTrace(); + return; + } + try { + Method method = listObject.getClass().getMethod("a", int.class, NBTReflectionUtil.getNBTBase()); + method.invoke(listObject, i, NBTReflectionUtil.getNBTTagString().getConstructor(String.class).newInstance(s)); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public void remove(int i) { - try { - Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class); - method.invoke(listObject, i); - save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void remove(int i) { + try { + Method method = listObject.getClass().getMethod(MethodNames.getRemoveMethodName(), int.class); + method.invoke(listObject, i); + save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public int size() { - try { - Method method = listObject.getClass().getMethod("size"); - return (int) method.invoke(listObject); - } catch (Exception ex) { - ex.printStackTrace(); - } - return -1; - } + public int size() { + try { + Method method = listObject.getClass().getMethod("size"); + return (int) method.invoke(listObject); + } catch (Exception ex) { + ex.printStackTrace(); + } + return -1; + } - public NBTType getType() { - return type; - } + public NBTType getType() { + return type; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java index e3d92716..59a1ce5f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTListCompound.java @@ -5,98 +5,98 @@ import java.util.Set; public class NBTListCompound { - private NBTList owner; - private Object compound; + private NBTList owner; + private Object compound; - protected NBTListCompound(NBTList parent, Object obj) { - owner = parent; - compound = obj; - } + protected NBTListCompound(NBTList parent, Object obj) { + owner = parent; + compound = obj; + } - public void setString(String key, String value) { - if (value == null) { - remove(key); - return; - } - try { - compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setString(String key, String value) { + if (value == null) { + remove(key); + return; + } + try { + compound.getClass().getMethod("setString", String.class, String.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public void setInteger(String key, int value) { - try { - compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setInteger(String key, int value) { + try { + compound.getClass().getMethod("setInt", String.class, int.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public int getInteger(String value) { - try { - return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); - } catch (Exception ex) { - ex.printStackTrace(); - } - return 0; - } + public int getInteger(String value) { + try { + return (int) compound.getClass().getMethod("getInt", String.class).invoke(compound, value); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } - public void setDouble(String key, double value) { - try { - compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); - owner.save(); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void setDouble(String key, double value) { + try { + compound.getClass().getMethod("setDouble", String.class, double.class).invoke(compound, key, value); + owner.save(); + } catch (Exception ex) { + ex.printStackTrace(); + } + } - public double getDouble(String key) { - try { - return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return 0; - } + public double getDouble(String key) { + try { + return (double) compound.getClass().getMethod("getDouble", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } - public String getString(String key) { - try { - return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return ""; - } + public String getString(String key) { + try { + return (String) compound.getClass().getMethod("getString", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return ""; + } - public boolean hasKey(String key) { - try { - return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return false; - } + public boolean hasKey(String key) { + try { + return (boolean) compound.getClass().getMethod("hasKey", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } - @SuppressWarnings("unchecked") - public Set getKeys() { - try { - return (Set) compound.getClass().getMethod("c").invoke(compound); - } catch (Exception ex) { - ex.printStackTrace(); - } - return new HashSet<>(); - } + @SuppressWarnings("unchecked") + public Set getKeys() { + try { + return (Set) compound.getClass().getMethod("c").invoke(compound); + } catch (Exception ex) { + ex.printStackTrace(); + } + return new HashSet<>(); + } - public void remove(String key) { - try { - compound.getClass().getMethod("remove", String.class).invoke(compound, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - } + public void remove(String key) { + try { + compound.getClass().getMethod("remove", String.class).invoke(compound, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java index a35684ef..5df3308e 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTReflectionUtil.java @@ -19,904 +19,904 @@ import java.util.Stack; // TODO: finish codestyle cleanup -sgdc3 public class NBTReflectionUtil { - private static final String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - - private static Class getCraftItemStack() { - - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - private static Class getCraftEntity() { - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTBase() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTBase"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTTagString() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTTagString"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNMSItemStack() { - try { - return Class.forName("net.minecraft.server." + version + ".ItemStack"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTTagCompound() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getNBTCompressedStreamTools() { - try { - return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getMojangsonParser() { - try { - return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getTileEntity() { - try { - return Class.forName("net.minecraft.server." + version + ".TileEntity"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - protected static Class getCraftWorld() { - try { - return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - public static Object getNewNBTTag() { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - try { - Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); - return c.newInstance(); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - private static Object getNewBlockPosition(int x, int y, int z) { - String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - try { - Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition"); - return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); - } catch (Exception ex) { - System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); - ex.printStackTrace(); - return null; - } - } - - public static Object setNBTTag(Object NBTTag, Object NMSItem) { - try { - Method method = NMSItem.getClass().getMethod("setTag", NBTTag.getClass()); - method.invoke(NMSItem, NBTTag); - return NMSItem; - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Object getNMSItemStack(ItemStack item) { - Class clazz = getCraftItemStack(); - - try { - Method method = clazz.getMethod("asNMSCopy", ItemStack.class); - return method.invoke(clazz, item); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getNMSEntity(Entity entity) { - Class clazz = getCraftEntity(); - - try { - Method method = clazz.getMethod("getHandle"); - return method.invoke(getCraftEntity().cast(entity)); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object parseNBT(String json) { - Class cis = getMojangsonParser(); - - try { - Method method = cis.getMethod("parse", String.class); - return method.invoke(null, json); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object readNBTFile(FileInputStream stream) { - Class clazz = getNBTCompressedStreamTools(); - - try { - Method method = clazz.getMethod("a", InputStream.class); - return method.invoke(clazz, stream); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object saveNBTFile(Object nbt, FileOutputStream stream) { - Class clazz = getNBTCompressedStreamTools(); - - try { - Method method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); - return method.invoke(clazz, nbt, stream); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static ItemStack getBukkitItemStack(Object item) { - Class clazz = getCraftItemStack(); - - try { - Method method = clazz.getMethod("asCraftMirror", item.getClass()); - return (ItemStack) method.invoke(clazz, item); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getItemRootNBTTagCompound(Object nmsitem) { - Class clazz = nmsitem.getClass(); - - try { - Method method = clazz.getMethod("getTag"); - return method.invoke(nmsitem); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { - Class clazz = getNMSItemStack(); - try { - return clazz.getConstructor(getNBTTagCompound()).newInstance(gettoCompount(nbtcompound.getCompound(), nbtcompound)); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { - Class clazz = nmsitem.getClass(); - - try { - Method method = clazz.getMethod("save", getNBTTagCompound()); - Object answer = method.invoke(nmsitem, getNewNBTTag()); - return new NBTContainer(answer); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object getEntityNBTTagCompound(Object nmsitem) { - Class c = nmsitem.getClass(); - - try { - Method method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound()); - Object nbt = getNBTTagCompound().newInstance(); - Object answer = method.invoke(nmsitem, nbt); - return answer != null ? answer : nbt; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Object setEntityNBTTag(Object NBTTag, Object NMSItem) { - try { - Method method; - method = NMSItem.getClass().getMethod(MethodNames.getEntityNbtSetterMethodName(), getNBTTagCompound()); - method.invoke(NMSItem, NBTTag); - return NMSItem; - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static Object getTileEntityNBTTagCompound(BlockState tile) { - try { - Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); - Object cworld = getCraftWorld().cast(tile.getWorld()); - Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); - Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); - Method method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound()); - Object tag = getNBTTagCompound().newInstance(); - Object answer = method.invoke(o, tag); - - return answer != null ? answer : tag; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) { - try { - Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); - Object cworld = getCraftWorld().cast(tile.getWorld()); - Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); - Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); - Method method = getTileEntity().getMethod("a", getNBTTagCompound()); - method.invoke(o, comp); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static Object getSubNBTTagCompound(Object compound, String name) { - Class c = compound.getClass(); - - try { - Method method = c.getMethod("getCompound", String.class); - return method.invoke(compound, name); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static void addNBTTagCompound(NBTCompound comp, String name) { - if (name == null) { - remove(comp, name); - return; - } - Object nbttag = comp.getCompound(); - if (nbttag == null) { - nbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(nbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); - method.invoke(workingtag, name, getNBTTagCompound().newInstance()); - comp.setCompound(nbttag); - return; - } catch (Exception ex) { - ex.printStackTrace(); - } - return; - } - - public static Boolean valideCompound(NBTCompound comp) { - Object root = comp.getCompound(); - if (root == null) { - root = getNewNBTTag(); - } - return gettoCompount(root, comp) != null; - } - - public static Object gettoCompount(Object nbttag, NBTCompound comp) { - Stack structure = new Stack<>(); - while (comp.getParent() != null) { - structure.add(comp.getName()); - comp = comp.getParent(); - } - while (!structure.isEmpty()) { - nbttag = getSubNBTTagCompound(nbttag, structure.pop()); - if (nbttag == null) { - return null; - } - } - return nbttag; - } - - public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("a", getNBTTagCompound()); - method.invoke(workingtag, nbtcompound.getCompound()); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static void setString(NBTCompound comp, String key, String text) { - if (text == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setString", String.class, String.class); - method.invoke(workingtag, key, text); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static String getString(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getString", String.class); - return (String) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static String getContent(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("get", String.class); - return method.invoke(workingtag, key).toString(); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setInt(NBTCompound comp, String key, Integer i) { - if (i == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setInt", String.class, int.class); - method.invoke(workingtag, key, i); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Integer getInt(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getInt", String.class); - return (Integer) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setByteArray(NBTCompound comp, String key, byte[] b) { - if (b == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setByteArray", String.class, byte[].class); - method.invoke(workingtag, key, b); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - return; - } - - public static byte[] getByteArray(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getByteArray", String.class); - return (byte[]) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setIntArray(NBTCompound comp, String key, int[] i) { - if (i == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setIntArray", String.class, int[].class); - method.invoke(workingtag, key, i); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static int[] getIntArray(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getIntArray", String.class); - return (int[]) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setFloat(NBTCompound comp, String key, Float f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setFloat", String.class, float.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Float getFloat(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getFloat", String.class); - return (Float) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setLong(NBTCompound comp, String key, Long f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setLong", String.class, long.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Long getLong(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getLong", String.class); - return (Long) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setShort(NBTCompound comp, String key, Short f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setShort", String.class, short.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Short getShort(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getShort", String.class); - return (Short) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setByte(NBTCompound comp, String key, Byte f) { - if (f == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setByte", String.class, byte.class); - method.invoke(workingtag, key, f); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Byte getByte(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getByte", String.class); - return (Byte) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setDouble(NBTCompound comp, String key, Double d) { - if (d == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setDouble", String.class, double.class); - method.invoke(workingtag, key, d); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Double getDouble(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getDouble", String.class); - return (Double) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static byte getType(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return 0; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); - return (byte) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return 0; - } - - public static void setBoolean(NBTCompound comp, String key, Boolean d) { - if (d == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("setBoolean", String.class, boolean.class); - method.invoke(workingtag, key, d); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Boolean getBoolean(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getBoolean", String.class); - return (Boolean) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void set(NBTCompound comp, String key, Object val) { - if (val == null) { - remove(comp, key); - return; - } - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) { - new Throwable("InvalideCompound").printStackTrace(); - return; - } - Object workingtag = gettoCompount(rootnbttag, comp); - try { - Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); - method.invoke(workingtag, key, val); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static NBTList getList(NBTCompound comp, String key, NBTType type) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("getList", String.class, int.class); - return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - public static void setObject(NBTCompound comp, String key, Object value) { - if (!MinecraftVersion.hasGsonSupport()) return; - try { - String json = GsonWrapper.getString(value); - setString(comp, key, json); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static T getObject(NBTCompound comp, String key, Class type) { - if (!MinecraftVersion.hasGsonSupport()) return null; - String json = getString(comp, key); - - return json != null ? GsonWrapper.deserializeJson(json, type) : null; - } - - public static void remove(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("remove", String.class); - method.invoke(workingtag, key); - comp.setCompound(rootnbttag); - } catch (Exception ex) { - ex.printStackTrace(); - } - } - - public static Boolean hasKey(NBTCompound comp, String key) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - - try { - Method method = workingtag.getClass().getMethod("hasKey", String.class); - return (Boolean) method.invoke(workingtag, key); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } - - @SuppressWarnings("unchecked") - public static Set getKeys(NBTCompound comp) { - Object rootnbttag = comp.getCompound(); - if (rootnbttag == null) { - rootnbttag = getNewNBTTag(); - } - if (!valideCompound(comp)) return null; - Object workingtag = gettoCompount(rootnbttag, comp); - Method method; - try { - method = workingtag.getClass().getMethod("c"); - return (Set) method.invoke(workingtag); - } catch (Exception ex) { - ex.printStackTrace(); - } - return null; - } + private static final String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + + private static Class getCraftItemStack() { + + try { + return Class.forName("org.bukkit.craftbukkit." + version + ".inventory.CraftItemStack"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + private static Class getCraftEntity() { + try { + return Class.forName("org.bukkit.craftbukkit." + version + ".entity.CraftEntity"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTBase() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTBase"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTTagString() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTTagString"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNMSItemStack() { + try { + return Class.forName("net.minecraft.server." + version + ".ItemStack"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTTagCompound() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getNBTCompressedStreamTools() { + try { + return Class.forName("net.minecraft.server." + version + ".NBTCompressedStreamTools"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getMojangsonParser() { + try { + return Class.forName("net.minecraft.server." + version + ".MojangsonParser"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getTileEntity() { + try { + return Class.forName("net.minecraft.server." + version + ".TileEntity"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + protected static Class getCraftWorld() { + try { + return Class.forName("org.bukkit.craftbukkit." + version + ".CraftWorld"); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + public static Object getNewNBTTag() { + String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + try { + Class c = Class.forName("net.minecraft.server." + version + ".NBTTagCompound"); + return c.newInstance(); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + private static Object getNewBlockPosition(int x, int y, int z) { + String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + try { + Class clazz = Class.forName("net.minecraft.server." + version + ".BlockPosition"); + return clazz.getConstructor(int.class, int.class, int.class).newInstance(x, y, z); + } catch (Exception ex) { + System.out.println("Error in ItemNBTAPI!(Outdated plugin?)"); + ex.printStackTrace(); + return null; + } + } + + public static Object setNBTTag(Object NBTTag, Object NMSItem) { + try { + Method method = NMSItem.getClass().getMethod("setTag", NBTTag.getClass()); + method.invoke(NMSItem, NBTTag); + return NMSItem; + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static Object getNMSItemStack(ItemStack item) { + Class clazz = getCraftItemStack(); + + try { + Method method = clazz.getMethod("asNMSCopy", ItemStack.class); + return method.invoke(clazz, item); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getNMSEntity(Entity entity) { + Class clazz = getCraftEntity(); + + try { + Method method = clazz.getMethod("getHandle"); + return method.invoke(getCraftEntity().cast(entity)); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object parseNBT(String json) { + Class cis = getMojangsonParser(); + + try { + Method method = cis.getMethod("parse", String.class); + return method.invoke(null, json); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object readNBTFile(FileInputStream stream) { + Class clazz = getNBTCompressedStreamTools(); + + try { + Method method = clazz.getMethod("a", InputStream.class); + return method.invoke(clazz, stream); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object saveNBTFile(Object nbt, FileOutputStream stream) { + Class clazz = getNBTCompressedStreamTools(); + + try { + Method method = clazz.getMethod("a", getNBTTagCompound(), OutputStream.class); + return method.invoke(clazz, nbt, stream); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static ItemStack getBukkitItemStack(Object item) { + Class clazz = getCraftItemStack(); + + try { + Method method = clazz.getMethod("asCraftMirror", item.getClass()); + return (ItemStack) method.invoke(clazz, item); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getItemRootNBTTagCompound(Object nmsitem) { + Class clazz = nmsitem.getClass(); + + try { + Method method = clazz.getMethod("getTag"); + return method.invoke(nmsitem); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { + Class clazz = getNMSItemStack(); + try { + return clazz.getConstructor(getNBTTagCompound()).newInstance(gettoCompount(nbtcompound.getCompound(), nbtcompound)); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { + Class clazz = nmsitem.getClass(); + + try { + Method method = clazz.getMethod("save", getNBTTagCompound()); + Object answer = method.invoke(nmsitem, getNewNBTTag()); + return new NBTContainer(answer); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object getEntityNBTTagCompound(Object nmsitem) { + Class c = nmsitem.getClass(); + + try { + Method method = c.getMethod(MethodNames.getEntityNbtGetterMethodName(), getNBTTagCompound()); + Object nbt = getNBTTagCompound().newInstance(); + Object answer = method.invoke(nmsitem, nbt); + return answer != null ? answer : nbt; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static Object setEntityNBTTag(Object NBTTag, Object NMSItem) { + try { + Method method; + method = NMSItem.getClass().getMethod(MethodNames.getEntityNbtSetterMethodName(), getNBTTagCompound()); + method.invoke(NMSItem, NBTTag); + return NMSItem; + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static Object getTileEntityNBTTagCompound(BlockState tile) { + try { + Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); + Object cworld = getCraftWorld().cast(tile.getWorld()); + Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); + Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); + Method method = getTileEntity().getMethod(MethodNames.getTileDataMethodName(), getNBTTagCompound()); + Object tag = getNBTTagCompound().newInstance(); + Object answer = method.invoke(o, tag); + + return answer != null ? answer : tag; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) { + try { + Object pos = getNewBlockPosition(tile.getX(), tile.getY(), tile.getZ()); + Object cworld = getCraftWorld().cast(tile.getWorld()); + Object nmsworld = cworld.getClass().getMethod("getHandle").invoke(cworld); + Object o = nmsworld.getClass().getMethod("getTileEntity", pos.getClass()).invoke(nmsworld, pos); + Method method = getTileEntity().getMethod("a", getNBTTagCompound()); + method.invoke(o, comp); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static Object getSubNBTTagCompound(Object compound, String name) { + Class c = compound.getClass(); + + try { + Method method = c.getMethod("getCompound", String.class); + return method.invoke(compound, name); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static void addNBTTagCompound(NBTCompound comp, String name) { + if (name == null) { + remove(comp, name); + return; + } + Object nbttag = comp.getCompound(); + if (nbttag == null) { + nbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(nbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); + method.invoke(workingtag, name, getNBTTagCompound().newInstance()); + comp.setCompound(nbttag); + return; + } catch (Exception ex) { + ex.printStackTrace(); + } + return; + } + + public static Boolean valideCompound(NBTCompound comp) { + Object root = comp.getCompound(); + if (root == null) { + root = getNewNBTTag(); + } + return gettoCompount(root, comp) != null; + } + + public static Object gettoCompount(Object nbttag, NBTCompound comp) { + Stack structure = new Stack<>(); + while (comp.getParent() != null) { + structure.add(comp.getName()); + comp = comp.getParent(); + } + while (!structure.isEmpty()) { + nbttag = getSubNBTTagCompound(nbttag, structure.pop()); + if (nbttag == null) { + return null; + } + } + return nbttag; + } + + public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("a", getNBTTagCompound()); + method.invoke(workingtag, nbtcompound.getCompound()); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static void setString(NBTCompound comp, String key, String text) { + if (text == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setString", String.class, String.class); + method.invoke(workingtag, key, text); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static String getString(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getString", String.class); + return (String) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static String getContent(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("get", String.class); + return method.invoke(workingtag, key).toString(); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setInt(NBTCompound comp, String key, Integer i) { + if (i == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setInt", String.class, int.class); + method.invoke(workingtag, key, i); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Integer getInt(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getInt", String.class); + return (Integer) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setByteArray(NBTCompound comp, String key, byte[] b) { + if (b == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setByteArray", String.class, byte[].class); + method.invoke(workingtag, key, b); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + return; + } + + public static byte[] getByteArray(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getByteArray", String.class); + return (byte[]) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setIntArray(NBTCompound comp, String key, int[] i) { + if (i == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setIntArray", String.class, int[].class); + method.invoke(workingtag, key, i); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static int[] getIntArray(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getIntArray", String.class); + return (int[]) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setFloat(NBTCompound comp, String key, Float f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setFloat", String.class, float.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Float getFloat(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getFloat", String.class); + return (Float) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setLong(NBTCompound comp, String key, Long f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setLong", String.class, long.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Long getLong(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getLong", String.class); + return (Long) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setShort(NBTCompound comp, String key, Short f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setShort", String.class, short.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Short getShort(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getShort", String.class); + return (Short) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setByte(NBTCompound comp, String key, Byte f) { + if (f == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setByte", String.class, byte.class); + method.invoke(workingtag, key, f); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Byte getByte(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getByte", String.class); + return (Byte) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setDouble(NBTCompound comp, String key, Double d) { + if (d == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setDouble", String.class, double.class); + method.invoke(workingtag, key, d); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Double getDouble(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getDouble", String.class); + return (Double) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static byte getType(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return 0; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod(MethodNames.getTypeMethodName(), String.class); + return (byte) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return 0; + } + + public static void setBoolean(NBTCompound comp, String key, Boolean d) { + if (d == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("setBoolean", String.class, boolean.class); + method.invoke(workingtag, key, d); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Boolean getBoolean(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getBoolean", String.class); + return (Boolean) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void set(NBTCompound comp, String key, Object val) { + if (val == null) { + remove(comp, key); + return; + } + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) { + new Throwable("InvalideCompound").printStackTrace(); + return; + } + Object workingtag = gettoCompount(rootnbttag, comp); + try { + Method method = workingtag.getClass().getMethod("set", String.class, getNBTBase()); + method.invoke(workingtag, key, val); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static NBTList getList(NBTCompound comp, String key, NBTType type) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("getList", String.class, int.class); + return new NBTList(comp, key, type, method.invoke(workingtag, key, type.getId())); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void setObject(NBTCompound comp, String key, Object value) { + if (!MinecraftVersion.hasGsonSupport()) return; + try { + String json = GsonWrapper.getString(value); + setString(comp, key, json); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static T getObject(NBTCompound comp, String key, Class type) { + if (!MinecraftVersion.hasGsonSupport()) return null; + String json = getString(comp, key); + + return json != null ? GsonWrapper.deserializeJson(json, type) : null; + } + + public static void remove(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("remove", String.class); + method.invoke(workingtag, key); + comp.setCompound(rootnbttag); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public static Boolean hasKey(NBTCompound comp, String key) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + + try { + Method method = workingtag.getClass().getMethod("hasKey", String.class); + return (Boolean) method.invoke(workingtag, key); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + @SuppressWarnings("unchecked") + public static Set getKeys(NBTCompound comp) { + Object rootnbttag = comp.getCompound(); + if (rootnbttag == null) { + rootnbttag = getNewNBTTag(); + } + if (!valideCompound(comp)) return null; + Object workingtag = gettoCompount(rootnbttag, comp); + Method method; + try { + method = workingtag.getClass().getMethod("c"); + return (Set) method.invoke(workingtag); + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java index dc78290e..cfc56e06 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTTileEntity.java @@ -4,18 +4,18 @@ import org.bukkit.block.BlockState; public class NBTTileEntity extends NBTCompound { - private final BlockState tile; + private final BlockState tile; - public NBTTileEntity(BlockState tile) { - this.tile = tile; - } + public NBTTileEntity(BlockState tile) { + this.tile = tile; + } - protected Object getCompound() { - return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); - } + protected Object getCompound() { + return NBTReflectionUtil.getTileEntityNBTTagCompound(tile); + } - protected void setCompound(Object compound) { - NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); - } + protected void setCompound(Object compound) { + NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java index afa9d60a..37d87ec6 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/NBTType.java @@ -1,34 +1,34 @@ package com.massivecraft.factions.zcore.nbtapi; public enum NBTType { - NBTTagEnd(0), - NBTTagByte(1), - NBTTagShort(2), - NBTTagInt(3), - NBTTagLong(4), - NBTTagFloat(5), - NBTTagDouble(6), - NBTTagByteArray(7), - NBTTagIntArray(11), - NBTTagString(8), - NBTTagList(9), - NBTTagCompound(10); + NBTTagEnd(0), + NBTTagByte(1), + NBTTagShort(2), + NBTTagInt(3), + NBTTagLong(4), + NBTTagFloat(5), + NBTTagDouble(6), + NBTTagByteArray(7), + NBTTagIntArray(11), + NBTTagString(8), + NBTTagList(9), + NBTTagCompound(10); - private final int id; + private final int id; - NBTType(int i) { - id = i; - } + NBTType(int i) { + id = i; + } - public static NBTType valueOf(int id) { - for (NBTType t : values()) - if (t.getId() == id) - return t; - return NBTType.NBTTagEnd; - } + public static NBTType valueOf(int id) { + for (NBTType t : values()) + if (t.getId() == id) + return t; + return NBTType.NBTTagEnd; + } - public int getId() { - return id; - } + public int getId() { + return id; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java index 77492633..4a8eaf55 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/GsonWrapper.java @@ -4,24 +4,24 @@ import com.google.gson.Gson; public class GsonWrapper { - private static final Gson gson = new Gson(); + private static final Gson gson = new Gson(); - public static String getString(Object obj) { - return gson.toJson(obj); - } + public static String getString(Object obj) { + return gson.toJson(obj); + } - public static T deserializeJson(String json, Class type) { - try { - if (json == null) { - return null; - } + public static T deserializeJson(String json, Class type) { + try { + if (json == null) { + return null; + } - T obj = gson.fromJson(json, type); - return type.cast(obj); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } + T obj = gson.fromJson(json, type); + return type.cast(obj); + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java index 126ad031..f45ba7f6 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MethodNames.java @@ -2,25 +2,25 @@ package com.massivecraft.factions.zcore.nbtapi.utils; public class MethodNames { - private final static MinecraftVersion MINECRAFT_VERSION = MinecraftVersion.getVersion(); + private final static MinecraftVersion MINECRAFT_VERSION = MinecraftVersion.getVersion(); - public static String getTileDataMethodName() { - return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "save"; - } + public static String getTileDataMethodName() { + return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "save"; + } - public static String getTypeMethodName() { - return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "d"; - } + public static String getTypeMethodName() { + return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "b" : "d"; + } - public static String getEntityNbtGetterMethodName() { - return "b"; - } + public static String getEntityNbtGetterMethodName() { + return "b"; + } - public static String getEntityNbtSetterMethodName() { - return "a"; - } + public static String getEntityNbtSetterMethodName() { + return "a"; + } - public static String getRemoveMethodName() { - return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "a" : "remove"; - } + public static String getRemoveMethodName() { + return MINECRAFT_VERSION == MinecraftVersion.MC1_8_R3 ? "a" : "remove"; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java index 372610c1..3b3ea260 100644 --- a/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java +++ b/src/main/java/com/massivecraft/factions/zcore/nbtapi/utils/MinecraftVersion.java @@ -3,58 +3,58 @@ package com.massivecraft.factions.zcore.nbtapi.utils; import org.bukkit.Bukkit; public enum MinecraftVersion { - Unknown(0), - MC1_7_R4(174), - MC1_8_R3(183), - MC1_9_R1(191), - MC1_9_R2(192), - MC1_10_R1(1101), - MC1_11_R1(1111), - MC1_12_R1(1121); + Unknown(0), + MC1_7_R4(174), + MC1_8_R3(183), + MC1_9_R1(191), + MC1_9_R2(192), + MC1_10_R1(1101), + MC1_11_R1(1111), + MC1_12_R1(1121); - private static MinecraftVersion version; - private static Boolean hasGsonSupport; + private static MinecraftVersion version; + private static Boolean hasGsonSupport; - private final int versionId; + private final int versionId; - MinecraftVersion(int versionId) { - this.versionId = versionId; - } + MinecraftVersion(int versionId) { + this.versionId = versionId; + } - public static MinecraftVersion getVersion() { - if (version == null) { - final String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - System.out.println("[NBTAPI] Found Spigot: " + ver + "!Trying to find NMS support"); + public static MinecraftVersion getVersion() { + if (version == null) { + final String ver = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; + System.out.println("[NBTAPI] Found Spigot: " + ver + "!Trying to find NMS support"); - try { - version = MinecraftVersion.valueOf(ver.replace("v", "MC")); - } catch (IllegalArgumentException ex) { - version = MinecraftVersion.Unknown; - } + try { + version = MinecraftVersion.valueOf(ver.replace("v", "MC")); + } catch (IllegalArgumentException ex) { + version = MinecraftVersion.Unknown; + } - if (version != Unknown) { - System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!"); - } else { - System.out.println("[NBTAPI] Wasn't able to find NMS Support!Some functions will not work!"); - } - } - return version; - } + if (version != Unknown) { + System.out.println("[NBTAPI] NMS support '" + version.name() + "' loaded!"); + } else { + System.out.println("[NBTAPI] Wasn't able to find NMS Support!Some functions will not work!"); + } + } + return version; + } - public static boolean hasGsonSupport() { - if (hasGsonSupport == null) { - try { - System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson")); - hasGsonSupport = true; - } catch (Exception ex) { - hasGsonSupport = false; - } - } - return hasGsonSupport; - } + public static boolean hasGsonSupport() { + if (hasGsonSupport == null) { + try { + System.out.println("Found Gson: " + Class.forName("com.google.gson.Gson")); + hasGsonSupport = true; + } catch (Exception ex) { + hasGsonSupport = false; + } + } + return hasGsonSupport; + } - public int getVersionId() { - return versionId; - } + public int getVersionId() { + return versionId; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java index 8dd916e6..c01d007d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryBoard.java @@ -20,372 +20,372 @@ import java.util.Map.Entry; public abstract class MemoryBoard extends Board { - public MemoryBoardMap flocationIds = new MemoryBoardMap(); + public MemoryBoardMap flocationIds = new MemoryBoardMap(); - //----------------------------------------------// - // Get and Set - //----------------------------------------------// - public String getIdAt(FLocation flocation) { - if (!flocationIds.containsKey(flocation)) { - return "0"; - } + //----------------------------------------------// + // Get and Set + //----------------------------------------------// + public String getIdAt(FLocation flocation) { + if (!flocationIds.containsKey(flocation)) { + return "0"; + } - return flocationIds.get(flocation); - } + return flocationIds.get(flocation); + } - public Faction getFactionAt(FLocation flocation) { - return Factions.getInstance().getFactionById(getIdAt(flocation)); - } + public Faction getFactionAt(FLocation flocation) { + return Factions.getInstance().getFactionById(getIdAt(flocation)); + } - public void setIdAt(String id, FLocation flocation) { - clearOwnershipAt(flocation); + public void setIdAt(String id, FLocation flocation) { + clearOwnershipAt(flocation); - if (id.equals("0")) { - removeAt(flocation); - } + if (id.equals("0")) { + removeAt(flocation); + } - flocationIds.put(flocation, id); - } + flocationIds.put(flocation, id); + } - public void setFactionAt(Faction faction, FLocation flocation) { - setIdAt(faction.getId(), flocation); - } + public void setFactionAt(Faction faction, FLocation flocation) { + setIdAt(faction.getId(), flocation); + } - public void removeAt(FLocation flocation) { - Faction faction = getFactionAt(flocation); - Iterator it = faction.getWarps().values().iterator(); - while (it.hasNext()) { - if (flocation.isInChunk(it.next().getLocation())) { - it.remove(); - } - } - clearOwnershipAt(flocation); - flocationIds.remove(flocation); - } + public void removeAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + Iterator it = faction.getWarps().values().iterator(); + while (it.hasNext()) { + if (flocation.isInChunk(it.next().getLocation())) { + it.remove(); + } + } + clearOwnershipAt(flocation); + flocationIds.remove(flocation); + } - public Set getAllClaims(String factionId) { - Set locs = new HashSet<>(); - for (Entry entry : flocationIds.entrySet()) { - if (entry.getValue().equals(factionId)) { - locs.add(entry.getKey()); - } - } - return locs; - } + public Set getAllClaims(String factionId) { + Set locs = new HashSet<>(); + for (Entry entry : flocationIds.entrySet()) { + if (entry.getValue().equals(factionId)) { + locs.add(entry.getKey()); + } + } + return locs; + } - public Set getAllClaims(Faction faction) { - return getAllClaims(faction.getId()); - } + public Set getAllClaims(Faction faction) { + return getAllClaims(faction.getId()); + } - // not to be confused with claims, ownership referring to further member-specific ownership of a claim - public void clearOwnershipAt(FLocation flocation) { - Faction faction = getFactionAt(flocation); - if (faction != null && faction.isNormal()) { - faction.clearClaimOwnership(flocation); - } - } + // not to be confused with claims, ownership referring to further member-specific ownership of a claim + public void clearOwnershipAt(FLocation flocation) { + Faction faction = getFactionAt(flocation); + if (faction != null && faction.isNormal()) { + faction.clearClaimOwnership(flocation); + } + } - public void unclaimAll(String factionId) { - Faction faction = Factions.getInstance().getFactionById(factionId); - if (faction != null && faction.isNormal()) { - faction.clearAllClaimOwnership(); - faction.clearWarps(); - } - clean(factionId); - } + public void unclaimAll(String factionId) { + Faction faction = Factions.getInstance().getFactionById(factionId); + if (faction != null && faction.isNormal()) { + faction.clearAllClaimOwnership(); + faction.clearWarps(); + } + clean(factionId); + } - public void unclaimAllInWorld(String factionId, World world) { - for (FLocation loc : getAllClaims(factionId)) { - if (loc.getWorldName().equals(world.getName())) { - removeAt(loc); - } - } - } + public void unclaimAllInWorld(String factionId, World world) { + for (FLocation loc : getAllClaims(factionId)) { + if (loc.getWorldName().equals(world.getName())) { + removeAt(loc); + } + } + } - public void clean(String factionId) { - flocationIds.removeFaction(factionId); - } + public void clean(String factionId) { + flocationIds.removeFaction(factionId); + } - // Is this coord NOT completely surrounded by coords claimed by the same faction? - // Simpler: Is there any nearby coord with a faction other than the faction here? - public boolean isBorderLocation(FLocation flocation) { - Faction faction = getFactionAt(flocation); - FLocation a = flocation.getRelative(1, 0); - FLocation b = flocation.getRelative(-1, 0); - FLocation c = flocation.getRelative(0, 1); - FLocation d = flocation.getRelative(0, -1); - return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); - } + // Is this coord NOT completely surrounded by coords claimed by the same faction? + // Simpler: Is there any nearby coord with a faction other than the faction here? + public boolean isBorderLocation(FLocation flocation) { + Faction faction = getFactionAt(flocation); + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction != getFactionAt(a) || faction != getFactionAt(b) || faction != getFactionAt(c) || faction != getFactionAt(d); + } - // Is this coord connected to any coord claimed by the specified faction? - public boolean isConnectedLocation(FLocation flocation, Faction faction) { - FLocation a = flocation.getRelative(1, 0); - FLocation b = flocation.getRelative(-1, 0); - FLocation c = flocation.getRelative(0, 1); - FLocation d = flocation.getRelative(0, -1); - return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); - } + // Is this coord connected to any coord claimed by the specified faction? + public boolean isConnectedLocation(FLocation flocation, Faction faction) { + FLocation a = flocation.getRelative(1, 0); + FLocation b = flocation.getRelative(-1, 0); + FLocation c = flocation.getRelative(0, 1); + FLocation d = flocation.getRelative(0, -1); + return faction == getFactionAt(a) || faction == getFactionAt(b) || faction == getFactionAt(c) || faction == getFactionAt(d); + } - /** - * Checks if there is another faction within a given radius other than Wilderness. Used for HCF feature that - * requires a 'buffer' between factions. - * - * @param flocation - center location. - * @param faction - faction checking for. - * @param radius - chunk radius to check. - * @return true if another Faction is within the radius, otherwise false. - */ - public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) { - for (int x = -radius; x <= radius; x++) { - for (int z = -radius; z <= radius; z++) { - if (x == 0 && z == 0) { - continue; - } + /** + * Checks if there is another faction within a given radius other than Wilderness. Used for HCF feature that + * requires a 'buffer' between factions. + * + * @param flocation - center location. + * @param faction - faction checking for. + * @param radius - chunk radius to check. + * @return true if another Faction is within the radius, otherwise false. + */ + public boolean hasFactionWithin(FLocation flocation, Faction faction, int radius) { + for (int x = -radius; x <= radius; x++) { + for (int z = -radius; z <= radius; z++) { + if (x == 0 && z == 0) { + continue; + } - FLocation relative = flocation.getRelative(x, z); - Faction other = getFactionAt(relative); + FLocation relative = flocation.getRelative(x, z); + Faction other = getFactionAt(relative); - if (other.isNormal() && other != faction) { - return true; - } - } - } - return false; - } + if (other.isNormal() && other != faction) { + return true; + } + } + } + return false; + } - public void clean() { - Iterator> iter = flocationIds.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (!Factions.getInstance().isValidFactionId(entry.getValue())) { - SavageFactions.plugin.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); - iter.remove(); - } - } - } + public void clean() { + Iterator> iter = flocationIds.entrySet().iterator(); + while (iter.hasNext()) { + Entry entry = iter.next(); + if (!Factions.getInstance().isValidFactionId(entry.getValue())) { + SavageFactions.plugin.log("Board cleaner removed " + entry.getValue() + " from " + entry.getKey()); + iter.remove(); + } + } + } - //----------------------------------------------// - // Cleaner. Remove orphaned foreign keys - //----------------------------------------------// + //----------------------------------------------// + // Cleaner. Remove orphaned foreign keys + //----------------------------------------------// - public int getFactionCoordCount(String factionId) { - return flocationIds.getOwnedLandCount(factionId); - } + public int getFactionCoordCount(String factionId) { + return flocationIds.getOwnedLandCount(factionId); + } - //----------------------------------------------// - // Coord count - //----------------------------------------------// + //----------------------------------------------// + // Coord count + //----------------------------------------------// - public int getFactionCoordCount(Faction faction) { - return getFactionCoordCount(faction.getId()); - } + public int getFactionCoordCount(Faction faction) { + return getFactionCoordCount(faction.getId()); + } - public int getFactionCoordCountInWorld(Faction faction, String worldName) { - String factionId = faction.getId(); - int ret = 0; - for (Entry entry : flocationIds.entrySet()) { - if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { - ret += 1; - } - } - return ret; - } + public int getFactionCoordCountInWorld(Faction faction, String worldName) { + String factionId = faction.getId(); + int ret = 0; + for (Entry entry : flocationIds.entrySet()) { + if (entry.getValue().equals(factionId) && entry.getKey().getWorldName().equals(worldName)) { + ret += 1; + } + } + return ret; + } - /** - * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction - * of decreasing z - */ - public ArrayList getMap(FPlayer fplayer, FLocation flocation, double inDegrees) { - Faction faction = fplayer.getFaction(); - ArrayList ret = new ArrayList<>(); - Faction factionLoc = getFactionAt(flocation); - ret.add(new FancyMessage(ChatColor.DARK_GRAY + SavageFactions.plugin.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); - int buffer = SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0); + /** + * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction + * of decreasing z + */ + public ArrayList getMap(FPlayer fplayer, FLocation flocation, double inDegrees) { + Faction faction = fplayer.getFaction(); + ArrayList ret = new ArrayList<>(); + Faction factionLoc = getFactionAt(flocation); + ret.add(new FancyMessage(ChatColor.DARK_GRAY + SavageFactions.plugin.txt.titleize("(" + flocation.getCoordString() + ") " + factionLoc.getTag(fplayer)))); + int buffer = SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0); - // Get the compass - ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, SavageFactions.plugin.txt.parse("")); + // Get the compass + ArrayList asciiCompass = AsciiCompass.getAsciiCompass(inDegrees, ChatColor.DARK_GREEN, SavageFactions.plugin.txt.parse("")); - int halfWidth = Conf.mapWidth / 2; - // Use player's value for height - int halfHeight = fplayer.getMapHeight() / 2; - FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); - int width = halfWidth * 2 + 1; - int height = halfHeight * 2 + 1; + int halfWidth = Conf.mapWidth / 2; + // Use player's value for height + int halfHeight = fplayer.getMapHeight() / 2; + FLocation topLeft = flocation.getRelative(-halfWidth, -halfHeight); + int width = halfWidth * 2 + 1; + int height = halfHeight * 2 + 1; - if (Conf.showMapFactionKey) { - height--; - } + if (Conf.showMapFactionKey) { + height--; + } - Map fList = new HashMap<>(); - int chrIdx = 0; + Map fList = new HashMap<>(); + int chrIdx = 0; - // For each row - for (int dz = 0; dz < height; dz++) { - // Draw and add that row - FancyMessage row = new FancyMessage(""); + // For each row + for (int dz = 0; dz < height; dz++) { + // Draw and add that row + FancyMessage row = new FancyMessage(""); - if (dz < 3) { - row.then(asciiCompass.get(dz)); - } - for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) { - if (dx == halfWidth && dz == halfHeight) { - row.then("+").color(ChatColor.AQUA).tooltip(TL.CLAIM_YOUAREHERE.toString()); - } else { - FLocation flocationHere = topLeft.getRelative(dx, dz); - Faction factionHere = getFactionAt(flocationHere); - Relation relation = fplayer.getRelationTo(factionHere); - if (flocationHere.isOutsideWorldBorder(buffer)) { - row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString()); - } else if (factionHere.isWilderness()) { - row.then("-").color(Conf.colorWilderness); - // Lol someone didnt add the x and z making it claim the wrong position Can i copyright this xD - if (fplayer.getPlayer().hasPermission(Permission.CLAIMAT.node)) { - row.tooltip(TL.CLAIM_CLICK_TO_CLAIM.format(dx + topLeft.getX(), dz + topLeft.getZ())) - .command(String.format("/f claimat %s %d %d", flocation.getWorldName(), dx + topLeft.getX(), dz + topLeft.getZ())); - } - } else if (factionHere.isSafeZone()) { - row.then("+").color(Conf.colorSafezone).tooltip(oneLineToolTip(factionHere, fplayer)); - } else if (factionHere.isWarZone()) { - row.then("+").color(Conf.colorWar).tooltip(oneLineToolTip(factionHere, fplayer)); - } else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) || - (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) || - (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) || - (Conf.showTrucesFactionsOnMap && relation.equals(Relation.TRUCE))) { - if (!fList.containsKey(factionHere.getTag())) { - fList.put(factionHere.getTag(), Conf.mapKeyChrs[Math.min(chrIdx++, Conf.mapKeyChrs.length - 1)]); - } - char tag = fList.get(factionHere.getTag()); + if (dz < 3) { + row.then(asciiCompass.get(dz)); + } + for (int dx = (dz < 3 ? 6 : 3); dx < width; dx++) { + if (dx == halfWidth && dz == halfHeight) { + row.then("+").color(ChatColor.AQUA).tooltip(TL.CLAIM_YOUAREHERE.toString()); + } else { + FLocation flocationHere = topLeft.getRelative(dx, dz); + Faction factionHere = getFactionAt(flocationHere); + Relation relation = fplayer.getRelationTo(factionHere); + if (flocationHere.isOutsideWorldBorder(buffer)) { + row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString()); + } else if (factionHere.isWilderness()) { + row.then("-").color(Conf.colorWilderness); + // Lol someone didnt add the x and z making it claim the wrong position Can i copyright this xD + if (fplayer.getPlayer().hasPermission(Permission.CLAIMAT.node)) { + row.tooltip(TL.CLAIM_CLICK_TO_CLAIM.format(dx + topLeft.getX(), dz + topLeft.getZ())) + .command(String.format("/f claimat %s %d %d", flocation.getWorldName(), dx + topLeft.getX(), dz + topLeft.getZ())); + } + } else if (factionHere.isSafeZone()) { + row.then("+").color(Conf.colorSafezone).tooltip(oneLineToolTip(factionHere, fplayer)); + } else if (factionHere.isWarZone()) { + row.then("+").color(Conf.colorWar).tooltip(oneLineToolTip(factionHere, fplayer)); + } else if (factionHere == faction || factionHere == factionLoc || relation.isAtLeast(Relation.ALLY) || + (Conf.showNeutralFactionsOnMap && relation.equals(Relation.NEUTRAL)) || + (Conf.showEnemyFactionsOnMap && relation.equals(Relation.ENEMY)) || + (Conf.showTrucesFactionsOnMap && relation.equals(Relation.TRUCE))) { + if (!fList.containsKey(factionHere.getTag())) { + fList.put(factionHere.getTag(), Conf.mapKeyChrs[Math.min(chrIdx++, Conf.mapKeyChrs.length - 1)]); + } + char tag = fList.get(factionHere.getTag()); - //row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(getToolTip(factionHere, fplayer)); - //changed out with a performance friendly one line tooltip :D - row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(oneLineToolTip(factionHere, fplayer)); - } else { - row.then("-").color(ChatColor.GRAY); - } - } - } - ret.add(row); - } + //row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(getToolTip(factionHere, fplayer)); + //changed out with a performance friendly one line tooltip :D + row.then(String.valueOf(tag)).color(factionHere.getColorTo(faction)).tooltip(oneLineToolTip(factionHere, fplayer)); + } else { + row.then("-").color(ChatColor.GRAY); + } + } + } + ret.add(row); + } - // Add the faction key - if (Conf.showMapFactionKey) { - FancyMessage fRow = new FancyMessage(""); - for (String key : fList.keySet()) { - fRow.then(String.format("%s: %s ", fList.get(key), key)).color(ChatColor.GRAY); - } - ret.add(fRow); - } + // Add the faction key + if (Conf.showMapFactionKey) { + FancyMessage fRow = new FancyMessage(""); + for (String key : fList.keySet()) { + fRow.then(String.format("%s: %s ", fList.get(key), key)).color(ChatColor.GRAY); + } + ret.add(fRow); + } - return ret; - } + return ret; + } - //----------------------------------------------// - // Map generation - //----------------------------------------------// + //----------------------------------------------// + // Map generation + //----------------------------------------------// - private List oneLineToolTip(Faction faction, FPlayer to) { - return Arrays.asList(faction.describeTo(to)); - } + private List oneLineToolTip(Faction faction, FPlayer to) { + return Arrays.asList(faction.describeTo(to)); + } - @SuppressWarnings("unused") - private List getToolTip(Faction faction, FPlayer to) { - List ret = new ArrayList<>(); - List show = SavageFactions.plugin.getConfig().getStringList("map"); + @SuppressWarnings("unused") + private List getToolTip(Faction faction, FPlayer to) { + List ret = new ArrayList<>(); + List show = SavageFactions.plugin.getConfig().getStringList("map"); - if (!faction.isNormal()) { - String tag = faction.getTag(to); - // send header and that's all - String header = show.get(0); - if (TagReplacer.HEADER.contains(header)) { - ret.add(SavageFactions.plugin.txt.titleize(tag)); - } else { - ret.add(SavageFactions.plugin.txt.parse(TagReplacer.FACTION.replace(header, tag))); - } - return ret; // we only show header for non-normal factions - } + if (!faction.isNormal()) { + String tag = faction.getTag(to); + // send header and that's all + String header = show.get(0); + if (TagReplacer.HEADER.contains(header)) { + ret.add(SavageFactions.plugin.txt.titleize(tag)); + } else { + ret.add(SavageFactions.plugin.txt.parse(TagReplacer.FACTION.replace(header, tag))); + } + return ret; // we only show header for non-normal factions + } - for (String raw : show) { - // Hack to get rid of the extra underscores in title normally used to center tag - if (raw.contains("{header}")) { - raw = raw.replace("{header}", faction.getTag(to)); - } + for (String raw : show) { + // Hack to get rid of the extra underscores in title normally used to center tag + if (raw.contains("{header}")) { + raw = raw.replace("{header}", faction.getTag(to)); + } - String parsed = TagUtil.parsePlain(faction, to, raw); // use relations - if (parsed == null) { - continue; // Due to minimal f show. - } + String parsed = TagUtil.parsePlain(faction, to, raw); // use relations + if (parsed == null) { + continue; // Due to minimal f show. + } - if (TagUtil.hasFancy(parsed)) { - List fancy = TagUtil.parseFancy(faction, to, parsed); - if (fancy != null) { - for (FancyMessage msg : fancy) { - ret.add((SavageFactions.plugin.txt.parse(msg.toOldMessageFormat()))); - } - } - continue; - } + if (TagUtil.hasFancy(parsed)) { + List fancy = TagUtil.parseFancy(faction, to, parsed); + if (fancy != null) { + for (FancyMessage msg : fancy) { + ret.add((SavageFactions.plugin.txt.parse(msg.toOldMessageFormat()))); + } + } + continue; + } - if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { - if (parsed.contains("{ig}")) { - // replaces all variables with no home TL - parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); - } - if (parsed.contains("%")) { - parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. - } - ret.add(SavageFactions.plugin.txt.parse(parsed)); - } - } + if (!parsed.contains("{notFrozen}") && !parsed.contains("{notPermanent}")) { + if (parsed.contains("{ig}")) { + // replaces all variables with no home TL + parsed = parsed.substring(0, parsed.indexOf("{ig}")) + TL.COMMAND_SHOW_NOHOME.toString(); + } + if (parsed.contains("%")) { + parsed = parsed.replaceAll("%", ""); // Just in case it got in there before we disallowed it. + } + ret.add(SavageFactions.plugin.txt.parse(parsed)); + } + } - return ret; - } + return ret; + } - public abstract void convertFrom(MemoryBoard old); + public abstract void convertFrom(MemoryBoard old); - public class MemoryBoardMap extends HashMap { - private static final long serialVersionUID = -6689617828610585368L; + public class MemoryBoardMap extends HashMap { + private static final long serialVersionUID = -6689617828610585368L; - Multimap factionToLandMap = HashMultimap.create(); + Multimap factionToLandMap = HashMultimap.create(); - @Override - public String put(FLocation floc, String factionId) { - String previousValue = super.put(floc, factionId); - if (previousValue != null) { - factionToLandMap.remove(previousValue, floc); - } + @Override + public String put(FLocation floc, String factionId) { + String previousValue = super.put(floc, factionId); + if (previousValue != null) { + factionToLandMap.remove(previousValue, floc); + } - factionToLandMap.put(factionId, floc); - return previousValue; - } + factionToLandMap.put(factionId, floc); + return previousValue; + } - @Override - public String remove(Object key) { - String result = super.remove(key); - if (result != null) { - FLocation floc = (FLocation) key; - factionToLandMap.remove(result, floc); - } + @Override + public String remove(Object key) { + String result = super.remove(key); + if (result != null) { + FLocation floc = (FLocation) key; + factionToLandMap.remove(result, floc); + } - return result; - } + return result; + } - @Override - public void clear() { - super.clear(); - factionToLandMap.clear(); - } + @Override + public void clear() { + super.clear(); + factionToLandMap.clear(); + } - public int getOwnedLandCount(String factionId) { - return factionToLandMap.get(factionId).size(); - } + public int getOwnedLandCount(String factionId) { + return factionToLandMap.get(factionId).size(); + } - public void removeFaction(String factionId) { - Collection flocations = factionToLandMap.removeAll(factionId); - for (FLocation floc : flocations) { - super.remove(floc); - } - } - } + public void removeFaction(String factionId) { + Collection flocations = factionToLandMap.removeAll(factionId); + for (FLocation floc : flocations) { + super.remove(floc); + } + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java index 380cd548..647f4395 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayer.java @@ -44,1187 +44,1187 @@ import java.util.UUID; public abstract class MemoryFPlayer implements FPlayer { - public boolean inVault = false; - protected String factionId; - protected Role role; - protected String title; - protected double power; - protected double powerBoost; - protected long lastPowerUpdateTime; - protected long lastLoginTime; - protected ChatMode chatMode; - protected boolean ignoreAllianceChat = false; - protected String id; - protected String name; - protected boolean monitorJoins; - protected boolean spyingChat = false; - protected boolean showScoreboard = true; - protected WarmUpUtil.Warmup warmup; - protected int warmupTask; - protected boolean isAdminBypassing = false; - protected int kills, deaths; - protected boolean willAutoLeave = true; - protected int mapHeight = 8; // default to old value - protected boolean isFlying = false; - protected boolean enteringPassword = false; - protected String enteringPasswordWarp = ""; - protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? - protected transient boolean mapAutoUpdating; - protected transient Faction autoClaimFor; - protected transient boolean autoSafeZoneEnabled; - protected transient boolean autoWarZoneEnabled; - protected transient boolean loginPvpDisabled; - protected transient long lastFrostwalkerMessage; - protected transient boolean shouldTakeFallDamage = true; - protected boolean isStealthEnabled = false; - boolean playerAlerts = false; - boolean inspectMode = false; - - public MemoryFPlayer() { - } - - public MemoryFPlayer(String id) { - this.id = id; - this.resetFactionData(false); - this.power = Conf.powerPlayerStarting; - this.lastPowerUpdateTime = System.currentTimeMillis(); - this.lastLoginTime = System.currentTimeMillis(); - this.mapAutoUpdating = false; - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0; - this.powerBoost = 0.0; - this.showScoreboard = SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-enabled", false); - this.kills = 0; - this.deaths = 0; - this.mapHeight = Conf.mapHeight; - - if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.getInstance().isValidFactionId(Conf.newPlayerStartingFactionID)) { - this.factionId = Conf.newPlayerStartingFactionID; - } - } - - public MemoryFPlayer(MemoryFPlayer other) { - this.factionId = other.factionId; - this.id = other.id; - this.power = other.power; - this.lastLoginTime = other.lastLoginTime; - this.mapAutoUpdating = other.mapAutoUpdating; - this.autoClaimFor = other.autoClaimFor; - this.autoSafeZoneEnabled = other.autoSafeZoneEnabled; - this.autoWarZoneEnabled = other.autoWarZoneEnabled; - this.loginPvpDisabled = other.loginPvpDisabled; - this.powerBoost = other.powerBoost; - this.role = other.role; - this.title = other.title; - this.chatMode = other.chatMode; - this.spyingChat = other.spyingChat; - this.lastStoodAt = other.lastStoodAt; - this.isAdminBypassing = other.isAdminBypassing; - this.showScoreboard = SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-enabled", true); - this.kills = other.kills; - this.deaths = other.deaths; - this.mapHeight = Conf.mapHeight; - } - - public boolean isStealthEnabled() { - return this.isStealthEnabled; - } - - public void setStealth(boolean stealth) { - this.isStealthEnabled = stealth; - } - - public void login() { - this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); - this.deaths = getPlayer().getStatistic(Statistic.DEATHS); - } - - public void logout() { - this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); - this.deaths = getPlayer().getStatistic(Statistic.DEATHS); - } - - public Faction getFaction() { - if (this.factionId == null) { - this.factionId = "0"; - } - return Factions.getInstance().getFactionById(this.factionId); - } - - public void setFaction(Faction faction) { - Faction oldFaction = this.getFaction(); - if (oldFaction != null) { - oldFaction.removeFPlayer(this); - } - faction.addFPlayer(this); - this.factionId = faction.getId(); - } - - public String getFactionId() { - return this.factionId; - } - - public boolean hasFaction() { - return !factionId.equals("0"); - } - - public void setMonitorJoins(boolean monitor) { - this.monitorJoins = monitor; - } - - public boolean isMonitoringJoins() { - return this.monitorJoins; - } - - public Role getRole() { - // Hack to fix null roles.. - if (role == null) { - this.role = Role.NORMAL; - } - - return this.role; - } - - public void setRole(Role role) { - this.role = role; - } - - public double getPowerBoost() { - return this.powerBoost; - } - - public void setPowerBoost(double powerBoost) { - this.powerBoost = powerBoost; - } - - public boolean willAutoLeave() { - return this.willAutoLeave; - } - - public void setAutoLeave(boolean willLeave) { - this.willAutoLeave = willLeave; - SavageFactions.plugin.debug(name + " set autoLeave to " + willLeave); - } - - public long getLastFrostwalkerMessage() { - return this.lastFrostwalkerMessage; - } - - public void setLastFrostwalkerMessage() { - this.lastFrostwalkerMessage = System.currentTimeMillis(); - } - - public Faction getAutoClaimFor() { - return autoClaimFor; - } - - public void setAutoClaimFor(Faction faction) { - this.autoClaimFor = faction; - if (this.autoClaimFor != null) { - // TODO: merge these into same autoclaim - this.autoSafeZoneEnabled = false; - this.autoWarZoneEnabled = false; - } - } - - public boolean isAutoSafeClaimEnabled() { - return autoSafeZoneEnabled; - } - - public void setIsAutoSafeClaimEnabled(boolean enabled) { - this.autoSafeZoneEnabled = enabled; - if (enabled) { - this.autoClaimFor = null; - this.autoWarZoneEnabled = false; - } - } - - public boolean isAutoWarClaimEnabled() { - return autoWarZoneEnabled; - } - - public void setIsAutoWarClaimEnabled(boolean enabled) { - this.autoWarZoneEnabled = enabled; - if (enabled) { - this.autoClaimFor = null; - this.autoSafeZoneEnabled = false; - } - } - - public boolean isAdminBypassing() { - return this.isAdminBypassing; - } - - public boolean isVanished() { - return Essentials.isVanished(getPlayer()); - } - - public void setIsAdminBypassing(boolean val) { - this.isAdminBypassing = val; - } - - public ChatMode getChatMode() { - if (this.factionId.equals("0") || !Conf.factionOnlyChat) { - this.chatMode = ChatMode.PUBLIC; - } - return chatMode; - } - - public void setChatMode(ChatMode chatMode) { - this.chatMode = chatMode; - } - - public boolean isIgnoreAllianceChat() { - return ignoreAllianceChat; - } - - public void setIgnoreAllianceChat(boolean ignore) { - this.ignoreAllianceChat = ignore; - } - - public boolean isSpyingChat() { - return spyingChat; - } - - public void setSpyingChat(boolean chatSpying) { - this.spyingChat = chatSpying; - } - - // -------------------------------------------- // - // Getters And Setters - // -------------------------------------------- // - - // FIELD: account - public String getAccountId() { - return this.getId(); - } - - public void resetFactionData(boolean doSpoutUpdate) { - // clean up any territory ownership in old faction, if there is one - if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) { - Faction currentFaction = this.getFaction(); - currentFaction.removeFPlayer(this); - if (currentFaction.isNormal()) { - currentFaction.clearClaimOwnership(this); - } - } - - this.factionId = "0"; // The default neutral faction - this.chatMode = ChatMode.PUBLIC; - this.role = Role.NORMAL; - this.title = ""; - this.autoClaimFor = null; - } - - public void resetFactionData() { - this.resetFactionData(true); - } - - public long getLastLoginTime() { - return lastLoginTime; - } - - public void setLastLoginTime(long lastLoginTime) { - losePowerFromBeingOffline(); - this.lastLoginTime = lastLoginTime; - this.lastPowerUpdateTime = lastLoginTime; - if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) { - this.loginPvpDisabled = true; - } - } - - public boolean isMapAutoUpdating() { - return mapAutoUpdating; - } - - public void setMapAutoUpdating(boolean mapAutoUpdating) { - this.mapAutoUpdating = mapAutoUpdating; - } - - //----------------------------------------------// - // Title, Name, Faction Tag and Chat - //----------------------------------------------// - - // Base: - - public boolean hasLoginPvpDisabled() { - if (!loginPvpDisabled) { - return false; - } - if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) { - this.loginPvpDisabled = false; - return false; - } - return true; - } - - public FLocation getLastStoodAt() { - return this.lastStoodAt; - } - - public void setLastStoodAt(FLocation flocation) { - this.lastStoodAt = flocation; - } - - public String getTitle() { - return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString(); - } - - public void setTitle(CommandSender sender, String title) { - // Check if the setter has it. - if (sender.hasPermission(Permission.TITLE_COLOR.node)) { - title = ChatColor.translateAlternateColorCodes('&', title); - } - - this.title = title; - } - - // Base concatenations: - - public String getName() { - if (this.name == null) { - // Older versions of FactionsUUID don't save the name, - // so `name` will be null the first time it's retrieved - // after updating - OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(getId())); - this.name = offline.getName() != null ? offline.getName() : getId(); - } - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getTag() { - return this.hasFaction() ? this.getFaction().getTag() : ""; - } - - // Colored concatenations: - // These are used in information messages - - public String getNameAndSomething(String something) { - String ret = this.role.getPrefix(); - if (something.length() > 0) { - ret += something + " "; - } - ret += this.getName(); - return ret; - } - - public String getNameAndTitle() { - return this.getNameAndSomething(this.getTitle()); - } - - // Chat Tag: - // These are injected into the format of global chat messages. - - public String getNameAndTag() { - return this.getNameAndSomething(this.getTag()); - } - - public String getNameAndTitle(Faction faction) { - return this.getColorTo(faction) + this.getNameAndTitle(); - } - - public String getNameAndTitle(MemoryFPlayer fplayer) { - return this.getColorTo(fplayer) + this.getNameAndTitle(); - } - - public String getChatTag() { - return this.hasFaction() ? String.format(Conf.chatTagFormat, this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString(); - } - - // Colored Chat Tag - public String getChatTag(Faction faction) { - return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : ""; - } - - // ------------------------------- - // Relation and relation colors - // ------------------------------- - - public String getChatTag(MemoryFPlayer fplayer) { - return this.hasFaction() ? this.getColorTo(fplayer) + getChatTag() : ""; - } - - public int getKills() { - return isOnline() ? getPlayer().getStatistic(Statistic.PLAYER_KILLS) : this.kills; - } - - public int getDeaths() { - return isOnline() ? getPlayer().getStatistic(Statistic.DEATHS) : this.deaths; - - } - - @Override - public String describeTo(RelationParticipator that, boolean ucfirst) { - return RelationUtil.describeThatToMe(this, that, ucfirst); - } - - @Override - public String describeTo(RelationParticipator that) { - return RelationUtil.describeThatToMe(this, that); - } - - @Override - public Relation getRelationTo(RelationParticipator rp) { - return RelationUtil.getRelationTo(this, rp); - } - - @Override - public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { - return RelationUtil.getRelationTo(this, rp, ignorePeaceful); - } - - public Relation getRelationToLocation() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this); - } - - @Override - public ChatColor getColorTo(RelationParticipator rp) { - return RelationUtil.getColorOfThatToMe(this, rp); - } - - //----------------------------------------------// - // Health - //----------------------------------------------// - public void heal(int amnt) { - Player player = this.getPlayer(); - if (player == null) { - return; - } - player.setHealth(player.getHealth() + amnt); - } - - //----------------------------------------------// - // Power - //----------------------------------------------// - public double getPower() { - this.updatePower(); - return this.power; - } - - public void alterPower(double delta) { - this.power += delta; - if (this.power > this.getPowerMax()) { - this.power = this.getPowerMax(); - } else if (this.power < this.getPowerMin()) { - this.power = this.getPowerMin(); - } - } - - public double getPowerMax() { - return Conf.powerPlayerMax + this.powerBoost; - } - - public double getPowerMin() { - return Conf.powerPlayerMin + this.powerBoost; - } - - public int getPowerRounded() { - return (int) Math.round(this.getPower()); - } - - public int getPowerMaxRounded() { - return (int) Math.round(this.getPowerMax()); - } - - public int getPowerMinRounded() { - return (int) Math.round(this.getPowerMin()); - } - - public void updatePower() { - if (this.isOffline()) { - losePowerFromBeingOffline(); - if (!Conf.powerRegenOffline) { - return; - } - } else if (hasFaction() && getFaction().isPowerFrozen()) { - return; // Don't let power regen if faction power is frozen. - } - - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; - this.lastPowerUpdateTime = now; - - Player thisPlayer = this.getPlayer(); - if (thisPlayer != null && thisPlayer.isDead()) { - return; // don't let dead players regain power until they respawn - } - - PowerRegenEvent powerRegenEvent = new PowerRegenEvent(getFaction(), this); - Bukkit.getServer().getPluginManager().callEvent(powerRegenEvent); - - if (!powerRegenEvent.isCancelled()) - this.alterPower(millisPassed * Conf.powerPerMinute / 60000); // millisPerMinute : 60 * 1000 - } - - public void losePowerFromBeingOffline() { - if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) { - long now = System.currentTimeMillis(); - long millisPassed = now - this.lastPowerUpdateTime; - this.lastPowerUpdateTime = now; - - double loss = millisPassed * Conf.powerOfflineLossPerDay / (24 * 60 * 60 * 1000); - if (this.power - loss < Conf.powerOfflineLossLimit) { - loss = this.power; - } - this.alterPower(-loss); - } - } - - public void onDeath() { - this.updatePower(); - this.alterPower(-Conf.powerPerDeath); - if (hasFaction()) { - getFaction().setLastDeath(System.currentTimeMillis()); - } - } - - //----------------------------------------------// - // Territory - //----------------------------------------------// - public boolean isInOwnTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)) == this.getFaction(); - } - - public boolean isInOthersTerritory() { - Faction factionHere = Board.getInstance().getFactionAt(new FLocation(this)); - return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); - } - - public boolean isInAllyTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); - } - - public boolean isInNeutralTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); - } - - public boolean isInEnemyTerritory() { - return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); - } - - public void sendFactionHereMessage(Faction from) { - Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); - boolean showChat = true; - if (showInfoBoard(toShow)) { - FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); - showChat = SavageFactions.plugin.getConfig().getBoolean("scoreboard.also-send-chat", true); - } - if (showChat) { - this.sendMessage(SavageFactions.plugin.txt.parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this)))); - } - } - - // ------------------------------- - // Actions - // ------------------------------- - - /** - * Check if the scoreboard should be shown. Simple method to be used by above method. - * - * @param toShow Faction to be shown. - * @return true if should show, otherwise false. - */ - public boolean showInfoBoard(Faction toShow) { - return showScoreboard && !toShow.isWarZone() && !toShow.isWilderness() && !toShow.isSafeZone() && SavageFactions.plugin.getConfig().contains("scoreboard.finfo") && SavageFactions.plugin.getConfig().getBoolean("scoreboard.finfo-enabled", false) && FScoreboard.get(this) != null; - } - - @Override - public boolean showScoreboard() { - return this.showScoreboard; - } - - @Override - public void setShowScoreboard(boolean show) { - this.showScoreboard = show; - } - - public void leave(boolean makePay) { - Faction myFaction = this.getFaction(); - makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); - - if (myFaction == null) { - resetFactionData(); - return; - } - - boolean perm = myFaction.isPermanent(); - - if (!perm && this.getRole() == Role.LEADER && myFaction.getFPlayers().size() > 1) { - msg(TL.LEAVE_PASSADMIN); - return; - } - - if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) { - msg(TL.LEAVE_NEGATIVEPOWER); - return; - } - - // if economy is enabled and they're not on the bypass list, make sure they can pay - if (makePay && !Econ.hasAtLeast(this, Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString())) { - return; - } - - FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); - Bukkit.getServer().getPluginManager().callEvent(leaveEvent); - if (leaveEvent.isCancelled()) { - return; - } - - // then make 'em pay (if applicable) - if (makePay && !Econ.modifyMoney(this, -Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString(), TL.LEAVE_FORLEAVE.toString())) { - return; - } - - // Am I the last one in the faction? - if (myFaction.getFPlayers().size() == 1) { - // Transfer all money - if (Econ.shouldBeUsed()) { - Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction.getAccountId())); - } - } - - if (myFaction.isNormal()) { - for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) { - fplayer.msg(TL.LEAVE_LEFT, this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); - } - - if (Conf.logFactionLeave) { - SavageFactions.plugin.log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); - } - } - - myFaction.removeAnnouncements(this); - this.resetFactionData(); - - if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) { - // Remove this faction - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg(TL.LEAVE_DISBANDED, myFaction.describeTo(fplayer, true)); - } - - FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), PlayerDisbandReason.LEAVE); - Bukkit.getPluginManager().callEvent(disbandEvent); - - Factions.getInstance().removeFaction(myFaction.getId()); - if (Conf.logFactionDisband) { - SavageFactions.plugin.log(TL.LEAVE_DISBANDEDLOG.format(myFaction.getTag(), myFaction.getId(), this.getName())); - } - } - } - - public boolean canClaimForFaction(Faction forFaction) { - return this.isAdminBypassing() || !forFaction.isWilderness() && (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())); - } - - public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { - return canClaimForFactionAtLocation(forFaction, new FLocation(location), notifyFailure); - } - - public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation flocation, boolean notifyFailure) { - String error = null; - Faction myFaction = getFaction(); - Faction currentFaction = Board.getInstance().getFactionAt(flocation); - int ownedLand = forFaction.getLandRounded(); - int factionBuffer = SavageFactions.plugin.getConfig().getInt("hcf.buffer-zone", 0); - int worldBuffer = SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0); - - if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { - // Checks for WorldGuard regions in the chunk attempting to be claimed - error = SavageFactions.plugin.txt.parse(TL.CLAIM_PROTECTED.toString()); - } else if (flocation.isOutsideWorldBorder(SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0))) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); - } else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_DISABLED.toString()); - } else if (this.isAdminBypassing()) { - return true; - } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { - return true; - } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { - return true; - } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW) { - return true; - } else if (myFaction != forFaction) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); - } else if (forFaction == currentFaction) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); - } else if (this.getRole().value < Role.MODERATOR.value) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_MUSTBE.toString(), Role.MODERATOR.getTranslation()); - } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); - } else if (currentFaction.isSafeZone()) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_SAFEZONE.toString()); - } else if (currentFaction.isWarZone()) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_WARZONE.toString()); - } else if (SavageFactions.plugin.getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_POWER.toString()); - } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_LIMIT.toString()); - } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_ALLY.toString()); - } else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { - if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_CONTIGIOUS.toString()); - } else { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); - } - } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); - } else if (flocation.isOutsideWorldBorder(worldBuffer)) { - if (worldBuffer > 0) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); - } else { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); - } - } else if (currentFaction.isNormal()) { - if (myFaction.isPeaceful()) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); - } else if (currentFaction.isPeaceful()) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); - } else if (!currentFaction.hasLandInflation()) { - // TODO more messages WARN current faction most importantly - error = SavageFactions.plugin.txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); - } else if (currentFaction.hasLandInflation() && !SavageFactions.plugin.getConfig().getBoolean("hcf.allow-overclaim", true)) { - // deny over claim when it normally would be allowed. - error = SavageFactions.plugin.txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); - } else if (!Board.getInstance().isBorderLocation(flocation)) { - error = SavageFactions.plugin.txt.parse(TL.CLAIM_BORDER.toString()); - } - } - // TODO: Add more else if statements. - - if (notifyFailure && error != null) { - msg(error); - } - return error == null; - } - - public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) { - return attemptClaim(forFaction, new FLocation(location), notifyFailure); - } - - public boolean shouldBeSaved() { - return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); - } - - public void msg(String str, Object... args) { - this.sendMessage(SavageFactions.plugin.txt.parse(str, args)); - } - - public void msg(TL translation, Object... args) { - this.msg(translation.toString(), args); - } - - public Player getPlayer() { - return Bukkit.getPlayer(UUID.fromString(this.getId())); - } - - public boolean isOnline() { - return this.getPlayer() != null; - } - - // make sure target player should be able to detect that this player is online - public boolean isOnlineAndVisibleTo(Player player) { - Player target = this.getPlayer(); - return target != null && player.canSee(target); - } - - public boolean isOffline() { - return !isOnline(); - } - - public boolean isFlying() { - return isFlying; - } - - public void setFlying(boolean fly) { - setFFlying(fly, false); - } - - public void setFFlying(boolean fly, boolean damage) { - Player player = getPlayer(); - if (player != null) { - player.setAllowFlight(fly); - player.setFlying(fly); - } - - if (!damage) { - msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); - if (!fly) { - sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3) + "")); - } - - } else { - msg(TL.COMMAND_FLY_DAMAGE); - } - - // If leaving fly mode, don't let them take fall damage for x seconds. - if (!fly) { - int cooldown = SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3); - CmdFly.flyMap.remove(player.getName()); - - // If the value is 0 or lower, make them take fall damage. - // Otherwise, start a timer and have this cancel after a few seconds. - // Short task so we're just doing it in method. Not clean but eh. - if (cooldown > 0) { - setTakeFallDamage(false); - Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - setTakeFallDamage(true); - } - }, 20L * cooldown); - } - } - - isFlying = fly; - } - - public boolean isInVault() { - return inVault; - } - - public void setInVault(boolean status) { - inVault = status; - } - - public boolean canFlyAtLocation() { - return canFlyAtLocation(lastStoodAt); - } - - public boolean canFlyAtLocation(FLocation location) { - Faction faction = Board.getInstance().getFactionAt(location); - if ((faction == getFaction() && getRole() == Role.LEADER) || isAdminBypassing) { - return true; - } - - Access access = faction.getAccess(this, PermissableAction.FLY); - return access == null || access == Access.UNDEFINED || access == Access.ALLOW; - } - - public boolean shouldTakeFallDamage() { - return this.shouldTakeFallDamage; - } - - public void setTakeFallDamage(boolean fallDamage) { - this.shouldTakeFallDamage = fallDamage; - } - - public boolean isEnteringPassword() { - return enteringPassword; - } - - public void setEnteringPassword(boolean toggle, String warp) { - enteringPassword = toggle; - enteringPasswordWarp = warp; - } - - // -------------------------------------------- // - // Message Sending Helpers - // -------------------------------------------- // - - public String getEnteringWarp() { - return enteringPasswordWarp; - } - - public void sendMessage(String msg) { - if (msg.contains("{null}")) { - return; // user wants this message to not send - } - if (msg.contains("/n/")) { - for (String s : msg.split("/n/")) { - sendMessage(s); - } - return; - } - Player player = this.getPlayer(); - if (player == null) { - return; - } - player.sendMessage(msg); - } - - public void sendMessage(List msgs) { - for (String msg : msgs) { - this.sendMessage(msg); - } - } - - public void sendFancyMessage(FancyMessage message) { - Player player = getPlayer(); - if (player == null || !player.isOnGround()) { - return; - } - - message.send(player); - } - - public void sendFancyMessage(List messages) { - Player player = getPlayer(); - if (player == null) { - return; - } - - for (FancyMessage msg : messages) { - msg.send(player); - } - } - - public int getMapHeight() { - if (this.mapHeight < 1) { - this.mapHeight = Conf.mapHeight; - } - - return this.mapHeight; - } - - public void setMapHeight(int height) { - this.mapHeight = height > (Conf.mapHeight * 2) ? (Conf.mapHeight * 2) : height; - } - - public String getNameAndTitle(FPlayer fplayer) { - return this.getColorTo(fplayer) + this.getNameAndTitle(); - } - - @Override - public String getChatTag(FPlayer fplayer) { - return this.hasFaction() ? this.getRelationTo(fplayer).getColor() + getChatTag() : ""; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - public abstract void remove(); - - @Override - public void clearWarmup() { - if (warmup != null) { - Bukkit.getScheduler().cancelTask(warmupTask); - this.stopWarmup(); - } - } - - @Override - public void stopWarmup() { - warmup = null; - } - - @Override - public boolean isWarmingUp() { - return warmup != null; - } - - @Override - public WarmUpUtil.Warmup getWarmupType() { - return warmup; - } - - @Override - public void addWarmup(WarmUpUtil.Warmup warmup, int taskId) { - if (this.warmup != null) { - this.clearWarmup(); - } - this.warmup = warmup; - this.warmupTask = taskId; - } - - @Override - public boolean checkIfNearbyEnemies() { - Player me = this.getPlayer(); - int radius = Conf.stealthFlyCheckRadius; - for (Entity e : me.getNearbyEntities(radius, 255, radius)) { - if (e == null) { - continue; - } - if (e instanceof Player) { - Player eplayer = (((Player) e).getPlayer()); - if (eplayer == null) { - continue; - } - FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); - if (efplayer == null) { - continue; - } - if (efplayer != null && this.getRelationTo(efplayer).equals(Relation.ENEMY) && !efplayer.isStealthEnabled()) { - setFlying(false); - msg(TL.COMMAND_FLY_ENEMY_NEAR); - Bukkit.getServer().getPluginManager().callEvent(new FPlayerStoppedFlying(this)); - return true; - } - } - } - return false; - } - - @Override - public Boolean canflyinWilderness() { - return getPlayer().hasPermission("factions.fly.wilderness"); - } - - @Override - public Boolean canflyinWarzone() { - return getPlayer().hasPermission("factions.fly.warzone"); - - } - - @Override - public Boolean canflyinSafezone() { - return getPlayer().hasPermission("factions.fly.safezone"); - - } - - @Override - public Boolean canflyinEnemy() { - return getPlayer().hasPermission("factions.fly.enemy"); - - } - - @Override - public Boolean canflyinAlly() { - return getPlayer().hasPermission("factions.fly.ally"); - - } - - @Override - public Boolean canflyinTruce() { - return getPlayer().hasPermission("factions.fly.truce"); - - } - - @Override - public Boolean canflyinNeutral() { - return getPlayer().hasPermission("factions.fly.neutral"); - - } - - @Override - public boolean isInspectMode() { - return inspectMode; - } - - @Override - public void setInspectMode(boolean status) { - inspectMode = status; - } - - public boolean attemptClaim(Faction forFaction, FLocation flocation, boolean notifyFailure) { - // notifyFailure is false if called by auto-claim; no need to notify on every failure for it - // return value is false on failure, true on success - - Faction currentFaction = Board.getInstance().getFactionAt(flocation); - int ownedLand = forFaction.getLandRounded(); - - if (!this.canClaimForFactionAtLocation(forFaction, flocation, notifyFailure)) { - return false; - } - - // if economy is enabled and they're not on the bypass list, make sure they can pay - boolean mustPay = Econ.shouldBeUsed() && !this.isAdminBypassing() && !forFaction.isSafeZone() && !forFaction.isWarZone(); - double cost = 0.0; - EconomyParticipator payee = null; - if (mustPay) { - cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); - - - if (Conf.econClaimUnconnectedFee != 0.0 && forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, forFaction)) { - cost += Conf.econClaimUnconnectedFee; - } - - if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) { - payee = this.getFaction(); - } else { - payee = this; - } - - if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { - return false; - } - } - - LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); - Bukkit.getPluginManager().callEvent(claimEvent); - if (claimEvent.isCancelled()) { - return false; - } - - // then make 'em pay (if applicable) - if (mustPay && !Econ.modifyMoney(payee, -cost, TL.CLAIM_TOCLAIM.toString(), TL.CLAIM_FORCLAIM.toString())) { - return false; - } - - // Was an over claim - if (currentFaction.isNormal() && currentFaction.hasLandInflation()) { - // Give them money for over claiming. - Econ.modifyMoney(payee, Conf.econOverclaimRewardMultiplier, TL.CLAIM_TOOVERCLAIM.toString(), TL.CLAIM_FOROVERCLAIM.toString()); - } - - // announce success - Set informTheseFPlayers = new HashSet<>(); - informTheseFPlayers.add(this); - informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); - for (FPlayer fp : informTheseFPlayers) { - fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); - } - - Board.getInstance().setFactionAt(forFaction, flocation); - - if (Conf.logLandClaims) { - SavageFactions.plugin.log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag()); - } - - return true; - } - - - @Override - public String getRolePrefix() { - - switch (getRole()) { - case RECRUIT: - return Conf.prefixRecruit; - case NORMAL: - return Conf.prefixNormal; - case MODERATOR: - return Conf.prefixMod; - case COLEADER: - return Conf.prefixCoLeader; - case LEADER: - return Conf.prefixLeader; - } - - return null; - } - - @Override - public boolean hasMoney(int amt) { - Economy econ = SavageFactions.plugin.getEcon(); - if (econ.getBalance(getPlayer()) >= amt) { - return true; - } else { - getPlayer().closeInventory(); - msg(TL.GENERIC_NOTENOUGHMONEY); - return false; - } - } - - @Override - public void takeMoney(int amt) { - if (hasMoney(amt)) { - Economy econ = SavageFactions.plugin.getEcon(); - econ.withdrawPlayer(getPlayer(), amt); - sendMessage(TL.GENERIC_MONEYTAKE.toString().replace("{amount}", amt + "")); - } - } + public boolean inVault = false; + protected String factionId; + protected Role role; + protected String title; + protected double power; + protected double powerBoost; + protected long lastPowerUpdateTime; + protected long lastLoginTime; + protected ChatMode chatMode; + protected boolean ignoreAllianceChat = false; + protected String id; + protected String name; + protected boolean monitorJoins; + protected boolean spyingChat = false; + protected boolean showScoreboard = true; + protected WarmUpUtil.Warmup warmup; + protected int warmupTask; + protected boolean isAdminBypassing = false; + protected int kills, deaths; + protected boolean willAutoLeave = true; + protected int mapHeight = 8; // default to old value + protected boolean isFlying = false; + protected boolean enteringPassword = false; + protected String enteringPasswordWarp = ""; + protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? + protected transient boolean mapAutoUpdating; + protected transient Faction autoClaimFor; + protected transient boolean autoSafeZoneEnabled; + protected transient boolean autoWarZoneEnabled; + protected transient boolean loginPvpDisabled; + protected transient long lastFrostwalkerMessage; + protected transient boolean shouldTakeFallDamage = true; + protected boolean isStealthEnabled = false; + boolean playerAlerts = false; + boolean inspectMode = false; + + public MemoryFPlayer() { + } + + public MemoryFPlayer(String id) { + this.id = id; + this.resetFactionData(false); + this.power = Conf.powerPlayerStarting; + this.lastPowerUpdateTime = System.currentTimeMillis(); + this.lastLoginTime = System.currentTimeMillis(); + this.mapAutoUpdating = false; + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0; + this.powerBoost = 0.0; + this.showScoreboard = SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-enabled", false); + this.kills = 0; + this.deaths = 0; + this.mapHeight = Conf.mapHeight; + + if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.getInstance().isValidFactionId(Conf.newPlayerStartingFactionID)) { + this.factionId = Conf.newPlayerStartingFactionID; + } + } + + public MemoryFPlayer(MemoryFPlayer other) { + this.factionId = other.factionId; + this.id = other.id; + this.power = other.power; + this.lastLoginTime = other.lastLoginTime; + this.mapAutoUpdating = other.mapAutoUpdating; + this.autoClaimFor = other.autoClaimFor; + this.autoSafeZoneEnabled = other.autoSafeZoneEnabled; + this.autoWarZoneEnabled = other.autoWarZoneEnabled; + this.loginPvpDisabled = other.loginPvpDisabled; + this.powerBoost = other.powerBoost; + this.role = other.role; + this.title = other.title; + this.chatMode = other.chatMode; + this.spyingChat = other.spyingChat; + this.lastStoodAt = other.lastStoodAt; + this.isAdminBypassing = other.isAdminBypassing; + this.showScoreboard = SavageFactions.plugin.getConfig().getBoolean("scoreboard.default-enabled", true); + this.kills = other.kills; + this.deaths = other.deaths; + this.mapHeight = Conf.mapHeight; + } + + public boolean isStealthEnabled() { + return this.isStealthEnabled; + } + + public void setStealth(boolean stealth) { + this.isStealthEnabled = stealth; + } + + public void login() { + this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); + this.deaths = getPlayer().getStatistic(Statistic.DEATHS); + } + + public void logout() { + this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); + this.deaths = getPlayer().getStatistic(Statistic.DEATHS); + } + + public Faction getFaction() { + if (this.factionId == null) { + this.factionId = "0"; + } + return Factions.getInstance().getFactionById(this.factionId); + } + + public void setFaction(Faction faction) { + Faction oldFaction = this.getFaction(); + if (oldFaction != null) { + oldFaction.removeFPlayer(this); + } + faction.addFPlayer(this); + this.factionId = faction.getId(); + } + + public String getFactionId() { + return this.factionId; + } + + public boolean hasFaction() { + return !factionId.equals("0"); + } + + public void setMonitorJoins(boolean monitor) { + this.monitorJoins = monitor; + } + + public boolean isMonitoringJoins() { + return this.monitorJoins; + } + + public Role getRole() { + // Hack to fix null roles.. + if (role == null) { + this.role = Role.NORMAL; + } + + return this.role; + } + + public void setRole(Role role) { + this.role = role; + } + + public double getPowerBoost() { + return this.powerBoost; + } + + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } + + public boolean willAutoLeave() { + return this.willAutoLeave; + } + + public void setAutoLeave(boolean willLeave) { + this.willAutoLeave = willLeave; + SavageFactions.plugin.debug(name + " set autoLeave to " + willLeave); + } + + public long getLastFrostwalkerMessage() { + return this.lastFrostwalkerMessage; + } + + public void setLastFrostwalkerMessage() { + this.lastFrostwalkerMessage = System.currentTimeMillis(); + } + + public Faction getAutoClaimFor() { + return autoClaimFor; + } + + public void setAutoClaimFor(Faction faction) { + this.autoClaimFor = faction; + if (this.autoClaimFor != null) { + // TODO: merge these into same autoclaim + this.autoSafeZoneEnabled = false; + this.autoWarZoneEnabled = false; + } + } + + public boolean isAutoSafeClaimEnabled() { + return autoSafeZoneEnabled; + } + + public void setIsAutoSafeClaimEnabled(boolean enabled) { + this.autoSafeZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoWarZoneEnabled = false; + } + } + + public boolean isAutoWarClaimEnabled() { + return autoWarZoneEnabled; + } + + public void setIsAutoWarClaimEnabled(boolean enabled) { + this.autoWarZoneEnabled = enabled; + if (enabled) { + this.autoClaimFor = null; + this.autoSafeZoneEnabled = false; + } + } + + public boolean isAdminBypassing() { + return this.isAdminBypassing; + } + + public boolean isVanished() { + return Essentials.isVanished(getPlayer()); + } + + public void setIsAdminBypassing(boolean val) { + this.isAdminBypassing = val; + } + + public ChatMode getChatMode() { + if (this.factionId.equals("0") || !Conf.factionOnlyChat) { + this.chatMode = ChatMode.PUBLIC; + } + return chatMode; + } + + public void setChatMode(ChatMode chatMode) { + this.chatMode = chatMode; + } + + public boolean isIgnoreAllianceChat() { + return ignoreAllianceChat; + } + + public void setIgnoreAllianceChat(boolean ignore) { + this.ignoreAllianceChat = ignore; + } + + public boolean isSpyingChat() { + return spyingChat; + } + + public void setSpyingChat(boolean chatSpying) { + this.spyingChat = chatSpying; + } + + // -------------------------------------------- // + // Getters And Setters + // -------------------------------------------- // + + // FIELD: account + public String getAccountId() { + return this.getId(); + } + + public void resetFactionData(boolean doSpoutUpdate) { + // clean up any territory ownership in old faction, if there is one + if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) { + Faction currentFaction = this.getFaction(); + currentFaction.removeFPlayer(this); + if (currentFaction.isNormal()) { + currentFaction.clearClaimOwnership(this); + } + } + + this.factionId = "0"; // The default neutral faction + this.chatMode = ChatMode.PUBLIC; + this.role = Role.NORMAL; + this.title = ""; + this.autoClaimFor = null; + } + + public void resetFactionData() { + this.resetFactionData(true); + } + + public long getLastLoginTime() { + return lastLoginTime; + } + + public void setLastLoginTime(long lastLoginTime) { + losePowerFromBeingOffline(); + this.lastLoginTime = lastLoginTime; + this.lastPowerUpdateTime = lastLoginTime; + if (Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0) { + this.loginPvpDisabled = true; + } + } + + public boolean isMapAutoUpdating() { + return mapAutoUpdating; + } + + public void setMapAutoUpdating(boolean mapAutoUpdating) { + this.mapAutoUpdating = mapAutoUpdating; + } + + //----------------------------------------------// + // Title, Name, Faction Tag and Chat + //----------------------------------------------// + + // Base: + + public boolean hasLoginPvpDisabled() { + if (!loginPvpDisabled) { + return false; + } + if (this.lastLoginTime + (Conf.noPVPDamageToOthersForXSecondsAfterLogin * 1000) < System.currentTimeMillis()) { + this.loginPvpDisabled = false; + return false; + } + return true; + } + + public FLocation getLastStoodAt() { + return this.lastStoodAt; + } + + public void setLastStoodAt(FLocation flocation) { + this.lastStoodAt = flocation; + } + + public String getTitle() { + return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString(); + } + + public void setTitle(CommandSender sender, String title) { + // Check if the setter has it. + if (sender.hasPermission(Permission.TITLE_COLOR.node)) { + title = ChatColor.translateAlternateColorCodes('&', title); + } + + this.title = title; + } + + // Base concatenations: + + public String getName() { + if (this.name == null) { + // Older versions of FactionsUUID don't save the name, + // so `name` will be null the first time it's retrieved + // after updating + OfflinePlayer offline = Bukkit.getOfflinePlayer(UUID.fromString(getId())); + this.name = offline.getName() != null ? offline.getName() : getId(); + } + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getTag() { + return this.hasFaction() ? this.getFaction().getTag() : ""; + } + + // Colored concatenations: + // These are used in information messages + + public String getNameAndSomething(String something) { + String ret = this.role.getPrefix(); + if (something.length() > 0) { + ret += something + " "; + } + ret += this.getName(); + return ret; + } + + public String getNameAndTitle() { + return this.getNameAndSomething(this.getTitle()); + } + + // Chat Tag: + // These are injected into the format of global chat messages. + + public String getNameAndTag() { + return this.getNameAndSomething(this.getTag()); + } + + public String getNameAndTitle(Faction faction) { + return this.getColorTo(faction) + this.getNameAndTitle(); + } + + public String getNameAndTitle(MemoryFPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } + + public String getChatTag() { + return this.hasFaction() ? String.format(Conf.chatTagFormat, this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString(); + } + + // Colored Chat Tag + public String getChatTag(Faction faction) { + return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : ""; + } + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + public String getChatTag(MemoryFPlayer fplayer) { + return this.hasFaction() ? this.getColorTo(fplayer) + getChatTag() : ""; + } + + public int getKills() { + return isOnline() ? getPlayer().getStatistic(Statistic.PLAYER_KILLS) : this.kills; + } + + public int getDeaths() { + return isOnline() ? getPlayer().getStatistic(Statistic.DEATHS) : this.deaths; + + } + + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } + + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } + + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } + + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } + + public Relation getRelationToLocation() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this); + } + + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } + + //----------------------------------------------// + // Health + //----------------------------------------------// + public void heal(int amnt) { + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.setHealth(player.getHealth() + amnt); + } + + //----------------------------------------------// + // Power + //----------------------------------------------// + public double getPower() { + this.updatePower(); + return this.power; + } + + public void alterPower(double delta) { + this.power += delta; + if (this.power > this.getPowerMax()) { + this.power = this.getPowerMax(); + } else if (this.power < this.getPowerMin()) { + this.power = this.getPowerMin(); + } + } + + public double getPowerMax() { + return Conf.powerPlayerMax + this.powerBoost; + } + + public double getPowerMin() { + return Conf.powerPlayerMin + this.powerBoost; + } + + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } + + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } + + public int getPowerMinRounded() { + return (int) Math.round(this.getPowerMin()); + } + + public void updatePower() { + if (this.isOffline()) { + losePowerFromBeingOffline(); + if (!Conf.powerRegenOffline) { + return; + } + } else if (hasFaction() && getFaction().isPowerFrozen()) { + return; // Don't let power regen if faction power is frozen. + } + + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; + + Player thisPlayer = this.getPlayer(); + if (thisPlayer != null && thisPlayer.isDead()) { + return; // don't let dead players regain power until they respawn + } + + PowerRegenEvent powerRegenEvent = new PowerRegenEvent(getFaction(), this); + Bukkit.getServer().getPluginManager().callEvent(powerRegenEvent); + + if (!powerRegenEvent.isCancelled()) + this.alterPower(millisPassed * Conf.powerPerMinute / 60000); // millisPerMinute : 60 * 1000 + } + + public void losePowerFromBeingOffline() { + if (Conf.powerOfflineLossPerDay > 0.0 && this.power > Conf.powerOfflineLossLimit) { + long now = System.currentTimeMillis(); + long millisPassed = now - this.lastPowerUpdateTime; + this.lastPowerUpdateTime = now; + + double loss = millisPassed * Conf.powerOfflineLossPerDay / (24 * 60 * 60 * 1000); + if (this.power - loss < Conf.powerOfflineLossLimit) { + loss = this.power; + } + this.alterPower(-loss); + } + } + + public void onDeath() { + this.updatePower(); + this.alterPower(-Conf.powerPerDeath); + if (hasFaction()) { + getFaction().setLastDeath(System.currentTimeMillis()); + } + } + + //----------------------------------------------// + // Territory + //----------------------------------------------// + public boolean isInOwnTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)) == this.getFaction(); + } + + public boolean isInOthersTerritory() { + Faction factionHere = Board.getInstance().getFactionAt(new FLocation(this)); + return factionHere != null && factionHere.isNormal() && factionHere != this.getFaction(); + } + + public boolean isInAllyTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isAlly(); + } + + public boolean isInNeutralTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isNeutral(); + } + + public boolean isInEnemyTerritory() { + return Board.getInstance().getFactionAt(new FLocation(this)).getRelationTo(this).isEnemy(); + } + + public void sendFactionHereMessage(Faction from) { + Faction toShow = Board.getInstance().getFactionAt(getLastStoodAt()); + boolean showChat = true; + if (showInfoBoard(toShow)) { + FScoreboard.get(this).setTemporarySidebar(new FInfoSidebar(toShow)); + showChat = SavageFactions.plugin.getConfig().getBoolean("scoreboard.also-send-chat", true); + } + if (showChat) { + this.sendMessage(SavageFactions.plugin.txt.parse(TL.FACTION_LEAVE.format(from.getTag(this), toShow.getTag(this)))); + } + } + + // ------------------------------- + // Actions + // ------------------------------- + + /** + * Check if the scoreboard should be shown. Simple method to be used by above method. + * + * @param toShow Faction to be shown. + * @return true if should show, otherwise false. + */ + public boolean showInfoBoard(Faction toShow) { + return showScoreboard && !toShow.isWarZone() && !toShow.isWilderness() && !toShow.isSafeZone() && SavageFactions.plugin.getConfig().contains("scoreboard.finfo") && SavageFactions.plugin.getConfig().getBoolean("scoreboard.finfo-enabled", false) && FScoreboard.get(this) != null; + } + + @Override + public boolean showScoreboard() { + return this.showScoreboard; + } + + @Override + public void setShowScoreboard(boolean show) { + this.showScoreboard = show; + } + + public void leave(boolean makePay) { + Faction myFaction = this.getFaction(); + makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); + + if (myFaction == null) { + resetFactionData(); + return; + } + + boolean perm = myFaction.isPermanent(); + + if (!perm && this.getRole() == Role.LEADER && myFaction.getFPlayers().size() > 1) { + msg(TL.LEAVE_PASSADMIN); + return; + } + + if (!Conf.canLeaveWithNegativePower && this.getPower() < 0) { + msg(TL.LEAVE_NEGATIVEPOWER); + return; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + if (makePay && !Econ.hasAtLeast(this, Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString())) { + return; + } + + FPlayerLeaveEvent leaveEvent = new FPlayerLeaveEvent(this, myFaction, FPlayerLeaveEvent.PlayerLeaveReason.LEAVE); + Bukkit.getServer().getPluginManager().callEvent(leaveEvent); + if (leaveEvent.isCancelled()) { + return; + } + + // then make 'em pay (if applicable) + if (makePay && !Econ.modifyMoney(this, -Conf.econCostLeave, TL.LEAVE_TOLEAVE.toString(), TL.LEAVE_FORLEAVE.toString())) { + return; + } + + // Am I the last one in the faction? + if (myFaction.getFPlayers().size() == 1) { + // Transfer all money + if (Econ.shouldBeUsed()) { + Econ.transferMoney(this, myFaction, this, Econ.getBalance(myFaction.getAccountId())); + } + } + + if (myFaction.isNormal()) { + for (FPlayer fplayer : myFaction.getFPlayersWhereOnline(true)) { + fplayer.msg(TL.LEAVE_LEFT, this.describeTo(fplayer, true), myFaction.describeTo(fplayer)); + } + + if (Conf.logFactionLeave) { + SavageFactions.plugin.log(TL.LEAVE_LEFT.format(this.getName(), myFaction.getTag())); + } + } + + myFaction.removeAnnouncements(this); + this.resetFactionData(); + + if (myFaction.isNormal() && !perm && myFaction.getFPlayers().isEmpty()) { + // Remove this faction + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg(TL.LEAVE_DISBANDED, myFaction.describeTo(fplayer, true)); + } + + FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), PlayerDisbandReason.LEAVE); + Bukkit.getPluginManager().callEvent(disbandEvent); + + Factions.getInstance().removeFaction(myFaction.getId()); + if (Conf.logFactionDisband) { + SavageFactions.plugin.log(TL.LEAVE_DISBANDEDLOG.format(myFaction.getTag(), myFaction.getId(), this.getName())); + } + } + } + + public boolean canClaimForFaction(Faction forFaction) { + return this.isAdminBypassing() || !forFaction.isWilderness() && (forFaction == this.getFaction() && this.getRole().isAtLeast(Role.MODERATOR)) || (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) || (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, Location location, boolean notifyFailure) { + return canClaimForFactionAtLocation(forFaction, new FLocation(location), notifyFailure); + } + + public boolean canClaimForFactionAtLocation(Faction forFaction, FLocation flocation, boolean notifyFailure) { + String error = null; + Faction myFaction = getFaction(); + Faction currentFaction = Board.getInstance().getFactionAt(flocation); + int ownedLand = forFaction.getLandRounded(); + int factionBuffer = SavageFactions.plugin.getConfig().getInt("hcf.buffer-zone", 0); + int worldBuffer = SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0); + + if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { + // Checks for WorldGuard regions in the chunk attempting to be claimed + error = SavageFactions.plugin.txt.parse(TL.CLAIM_PROTECTED.toString()); + } else if (flocation.isOutsideWorldBorder(SavageFactions.plugin.getConfig().getInt("world-border.buffer", 0))) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_DISABLED.toString()); + } else if (this.isAdminBypassing()) { + return true; + } else if (forFaction.isSafeZone() && Permission.MANAGE_SAFE_ZONE.has(getPlayer())) { + return true; + } else if (forFaction.isWarZone() && Permission.MANAGE_WAR_ZONE.has(getPlayer())) { + return true; + } else if (currentFaction.getAccess(this, PermissableAction.TERRITORY) == Access.ALLOW) { + return true; + } else if (myFaction != forFaction) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_CANTCLAIM.toString(), forFaction.describeTo(this)); + } else if (forFaction == currentFaction) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_ALREADYOWN.toString(), forFaction.describeTo(this, true)); + } else if (this.getRole().value < Role.MODERATOR.value) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_MUSTBE.toString(), Role.MODERATOR.getTranslation()); + } else if (forFaction.getFPlayers().size() < Conf.claimsRequireMinFactionMembers) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_MEMBERS.toString(), Conf.claimsRequireMinFactionMembers); + } else if (currentFaction.isSafeZone()) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_SAFEZONE.toString()); + } else if (currentFaction.isWarZone()) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_WARZONE.toString()); + } else if (SavageFactions.plugin.getConfig().getBoolean("hcf.allow-overclaim", true) && ownedLand >= forFaction.getPowerRounded()) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_POWER.toString()); + } else if (Conf.claimedLandsMax != 0 && ownedLand >= Conf.claimedLandsMax && forFaction.isNormal()) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_LIMIT.toString()); + } else if (currentFaction.getRelationTo(forFaction) == Relation.ALLY) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_ALLY.toString()); + } else if (Conf.claimsMustBeConnected && !this.isAdminBypassing() && myFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, myFaction) && (!Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction || !currentFaction.isNormal())) { + if (Conf.claimsCanBeUnconnectedIfOwnedByOtherFaction) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_CONTIGIOUS.toString()); + } else { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_FACTIONCONTIGUOUS.toString()); + } + } else if (factionBuffer > 0 && Board.getInstance().hasFactionWithin(flocation, myFaction, factionBuffer)) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_TOOCLOSETOOTHERFACTION.format(factionBuffer)); + } else if (flocation.isOutsideWorldBorder(worldBuffer)) { + if (worldBuffer > 0) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_OUTSIDEBORDERBUFFER.format(worldBuffer)); + } else { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); + } + } else if (currentFaction.isNormal()) { + if (myFaction.isPeaceful()) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_PEACEFUL.toString(), currentFaction.getTag(this)); + } else if (currentFaction.isPeaceful()) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_PEACEFULTARGET.toString(), currentFaction.getTag(this)); + } else if (!currentFaction.hasLandInflation()) { + // TODO more messages WARN current faction most importantly + error = SavageFactions.plugin.txt.parse(TL.CLAIM_THISISSPARTA.toString(), currentFaction.getTag(this)); + } else if (currentFaction.hasLandInflation() && !SavageFactions.plugin.getConfig().getBoolean("hcf.allow-overclaim", true)) { + // deny over claim when it normally would be allowed. + error = SavageFactions.plugin.txt.parse(TL.CLAIM_OVERCLAIM_DISABLED.toString()); + } else if (!Board.getInstance().isBorderLocation(flocation)) { + error = SavageFactions.plugin.txt.parse(TL.CLAIM_BORDER.toString()); + } + } + // TODO: Add more else if statements. + + if (notifyFailure && error != null) { + msg(error); + } + return error == null; + } + + public boolean attemptClaim(Faction forFaction, Location location, boolean notifyFailure) { + return attemptClaim(forFaction, new FLocation(location), notifyFailure); + } + + public boolean shouldBeSaved() { + return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); + } + + public void msg(String str, Object... args) { + this.sendMessage(SavageFactions.plugin.txt.parse(str, args)); + } + + public void msg(TL translation, Object... args) { + this.msg(translation.toString(), args); + } + + public Player getPlayer() { + return Bukkit.getPlayer(UUID.fromString(this.getId())); + } + + public boolean isOnline() { + return this.getPlayer() != null; + } + + // make sure target player should be able to detect that this player is online + public boolean isOnlineAndVisibleTo(Player player) { + Player target = this.getPlayer(); + return target != null && player.canSee(target); + } + + public boolean isOffline() { + return !isOnline(); + } + + public boolean isFlying() { + return isFlying; + } + + public void setFlying(boolean fly) { + setFFlying(fly, false); + } + + public void setFFlying(boolean fly, boolean damage) { + Player player = getPlayer(); + if (player != null) { + player.setAllowFlight(fly); + player.setFlying(fly); + } + + if (!damage) { + msg(TL.COMMAND_FLY_CHANGE, fly ? "enabled" : "disabled"); + if (!fly) { + sendMessage(TL.COMMAND_FLY_COOLDOWN.toString().replace("{amount}", SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3) + "")); + } + + } else { + msg(TL.COMMAND_FLY_DAMAGE); + } + + // If leaving fly mode, don't let them take fall damage for x seconds. + if (!fly) { + int cooldown = SavageFactions.plugin.getConfig().getInt("fly-falldamage-cooldown", 3); + CmdFly.flyMap.remove(player.getName()); + + // If the value is 0 or lower, make them take fall damage. + // Otherwise, start a timer and have this cancel after a few seconds. + // Short task so we're just doing it in method. Not clean but eh. + if (cooldown > 0) { + setTakeFallDamage(false); + Bukkit.getScheduler().runTaskLater(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + setTakeFallDamage(true); + } + }, 20L * cooldown); + } + } + + isFlying = fly; + } + + public boolean isInVault() { + return inVault; + } + + public void setInVault(boolean status) { + inVault = status; + } + + public boolean canFlyAtLocation() { + return canFlyAtLocation(lastStoodAt); + } + + public boolean canFlyAtLocation(FLocation location) { + Faction faction = Board.getInstance().getFactionAt(location); + if ((faction == getFaction() && getRole() == Role.LEADER) || isAdminBypassing) { + return true; + } + + Access access = faction.getAccess(this, PermissableAction.FLY); + return access == null || access == Access.UNDEFINED || access == Access.ALLOW; + } + + public boolean shouldTakeFallDamage() { + return this.shouldTakeFallDamage; + } + + public void setTakeFallDamage(boolean fallDamage) { + this.shouldTakeFallDamage = fallDamage; + } + + public boolean isEnteringPassword() { + return enteringPassword; + } + + public void setEnteringPassword(boolean toggle, String warp) { + enteringPassword = toggle; + enteringPasswordWarp = warp; + } + + // -------------------------------------------- // + // Message Sending Helpers + // -------------------------------------------- // + + public String getEnteringWarp() { + return enteringPasswordWarp; + } + + public void sendMessage(String msg) { + if (msg.contains("{null}")) { + return; // user wants this message to not send + } + if (msg.contains("/n/")) { + for (String s : msg.split("/n/")) { + sendMessage(s); + } + return; + } + Player player = this.getPlayer(); + if (player == null) { + return; + } + player.sendMessage(msg); + } + + public void sendMessage(List msgs) { + for (String msg : msgs) { + this.sendMessage(msg); + } + } + + public void sendFancyMessage(FancyMessage message) { + Player player = getPlayer(); + if (player == null || !player.isOnGround()) { + return; + } + + message.send(player); + } + + public void sendFancyMessage(List messages) { + Player player = getPlayer(); + if (player == null) { + return; + } + + for (FancyMessage msg : messages) { + msg.send(player); + } + } + + public int getMapHeight() { + if (this.mapHeight < 1) { + this.mapHeight = Conf.mapHeight; + } + + return this.mapHeight; + } + + public void setMapHeight(int height) { + this.mapHeight = height > (Conf.mapHeight * 2) ? (Conf.mapHeight * 2) : height; + } + + public String getNameAndTitle(FPlayer fplayer) { + return this.getColorTo(fplayer) + this.getNameAndTitle(); + } + + @Override + public String getChatTag(FPlayer fplayer) { + return this.hasFaction() ? this.getRelationTo(fplayer).getColor() + getChatTag() : ""; + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + public abstract void remove(); + + @Override + public void clearWarmup() { + if (warmup != null) { + Bukkit.getScheduler().cancelTask(warmupTask); + this.stopWarmup(); + } + } + + @Override + public void stopWarmup() { + warmup = null; + } + + @Override + public boolean isWarmingUp() { + return warmup != null; + } + + @Override + public WarmUpUtil.Warmup getWarmupType() { + return warmup; + } + + @Override + public void addWarmup(WarmUpUtil.Warmup warmup, int taskId) { + if (this.warmup != null) { + this.clearWarmup(); + } + this.warmup = warmup; + this.warmupTask = taskId; + } + + @Override + public boolean checkIfNearbyEnemies() { + Player me = this.getPlayer(); + int radius = Conf.stealthFlyCheckRadius; + for (Entity e : me.getNearbyEntities(radius, 255, radius)) { + if (e == null) { + continue; + } + if (e instanceof Player) { + Player eplayer = (((Player) e).getPlayer()); + if (eplayer == null) { + continue; + } + FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); + if (efplayer == null) { + continue; + } + if (efplayer != null && this.getRelationTo(efplayer).equals(Relation.ENEMY) && !efplayer.isStealthEnabled()) { + setFlying(false); + msg(TL.COMMAND_FLY_ENEMY_NEAR); + Bukkit.getServer().getPluginManager().callEvent(new FPlayerStoppedFlying(this)); + return true; + } + } + } + return false; + } + + @Override + public Boolean canflyinWilderness() { + return getPlayer().hasPermission("factions.fly.wilderness"); + } + + @Override + public Boolean canflyinWarzone() { + return getPlayer().hasPermission("factions.fly.warzone"); + + } + + @Override + public Boolean canflyinSafezone() { + return getPlayer().hasPermission("factions.fly.safezone"); + + } + + @Override + public Boolean canflyinEnemy() { + return getPlayer().hasPermission("factions.fly.enemy"); + + } + + @Override + public Boolean canflyinAlly() { + return getPlayer().hasPermission("factions.fly.ally"); + + } + + @Override + public Boolean canflyinTruce() { + return getPlayer().hasPermission("factions.fly.truce"); + + } + + @Override + public Boolean canflyinNeutral() { + return getPlayer().hasPermission("factions.fly.neutral"); + + } + + @Override + public boolean isInspectMode() { + return inspectMode; + } + + @Override + public void setInspectMode(boolean status) { + inspectMode = status; + } + + public boolean attemptClaim(Faction forFaction, FLocation flocation, boolean notifyFailure) { + // notifyFailure is false if called by auto-claim; no need to notify on every failure for it + // return value is false on failure, true on success + + Faction currentFaction = Board.getInstance().getFactionAt(flocation); + int ownedLand = forFaction.getLandRounded(); + + if (!this.canClaimForFactionAtLocation(forFaction, flocation, notifyFailure)) { + return false; + } + + // if economy is enabled and they're not on the bypass list, make sure they can pay + boolean mustPay = Econ.shouldBeUsed() && !this.isAdminBypassing() && !forFaction.isSafeZone() && !forFaction.isWarZone(); + double cost = 0.0; + EconomyParticipator payee = null; + if (mustPay) { + cost = Econ.calculateClaimCost(ownedLand, currentFaction.isNormal()); + + + if (Conf.econClaimUnconnectedFee != 0.0 && forFaction.getLandRoundedInWorld(flocation.getWorldName()) > 0 && !Board.getInstance().isConnectedLocation(flocation, forFaction)) { + cost += Conf.econClaimUnconnectedFee; + } + + if (Conf.bankEnabled && Conf.bankFactionPaysLandCosts && this.hasFaction()) { + payee = this.getFaction(); + } else { + payee = this; + } + + if (!Econ.hasAtLeast(payee, cost, TL.CLAIM_TOCLAIM.toString())) { + return false; + } + } + + LandClaimEvent claimEvent = new LandClaimEvent(flocation, forFaction, this); + Bukkit.getPluginManager().callEvent(claimEvent); + if (claimEvent.isCancelled()) { + return false; + } + + // then make 'em pay (if applicable) + if (mustPay && !Econ.modifyMoney(payee, -cost, TL.CLAIM_TOCLAIM.toString(), TL.CLAIM_FORCLAIM.toString())) { + return false; + } + + // Was an over claim + if (currentFaction.isNormal() && currentFaction.hasLandInflation()) { + // Give them money for over claiming. + Econ.modifyMoney(payee, Conf.econOverclaimRewardMultiplier, TL.CLAIM_TOOVERCLAIM.toString(), TL.CLAIM_FOROVERCLAIM.toString()); + } + + // announce success + Set informTheseFPlayers = new HashSet<>(); + informTheseFPlayers.add(this); + informTheseFPlayers.addAll(forFaction.getFPlayersWhereOnline(true)); + for (FPlayer fp : informTheseFPlayers) { + fp.msg(TL.CLAIM_CLAIMED, this.describeTo(fp, true), forFaction.describeTo(fp), currentFaction.describeTo(fp)); + } + + Board.getInstance().setFactionAt(forFaction, flocation); + + if (Conf.logLandClaims) { + SavageFactions.plugin.log(TL.CLAIM_CLAIMEDLOG.toString(), this.getName(), flocation.getCoordString(), forFaction.getTag()); + } + + return true; + } + + + @Override + public String getRolePrefix() { + + switch (getRole()) { + case RECRUIT: + return Conf.prefixRecruit; + case NORMAL: + return Conf.prefixNormal; + case MODERATOR: + return Conf.prefixMod; + case COLEADER: + return Conf.prefixCoLeader; + case LEADER: + return Conf.prefixLeader; + } + + return null; + } + + @Override + public boolean hasMoney(int amt) { + Economy econ = SavageFactions.plugin.getEcon(); + if (econ.getBalance(getPlayer()) >= amt) { + return true; + } else { + getPlayer().closeInventory(); + msg(TL.GENERIC_NOTENOUGHMONEY); + return false; + } + } + + @Override + public void takeMoney(int amt) { + if (hasMoney(amt)) { + Economy econ = SavageFactions.plugin.getEcon(); + econ.withdrawPlayer(getPlayer(), amt); + sendMessage(TL.GENERIC_MONEYTAKE.toString().replace("{amount}", amt + "")); + } + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java index b120e028..02138532 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFPlayers.java @@ -12,55 +12,55 @@ import java.util.*; import java.util.concurrent.ConcurrentSkipListMap; public abstract class MemoryFPlayers extends FPlayers { - public Map fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); + public Map fPlayers = new ConcurrentSkipListMap<>(String.CASE_INSENSITIVE_ORDER); - public void clean() { - for (FPlayer fplayer : this.fPlayers.values()) { - if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) { - SavageFactions.plugin.log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName()); - fplayer.resetFactionData(false); - } - } - } + public void clean() { + for (FPlayer fplayer : this.fPlayers.values()) { + if (!Factions.getInstance().isValidFactionId(fplayer.getFactionId())) { + SavageFactions.plugin.log("Reset faction data (invalid faction:" + fplayer.getFactionId() + ") for player " + fplayer.getName()); + fplayer.resetFactionData(false); + } + } + } - public Collection getOnlinePlayers() { - Set entities = new HashSet<>(); - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - entities.add(this.getByPlayer(player)); - } - return entities; - } + public Collection getOnlinePlayers() { + Set entities = new HashSet<>(); + for (Player player : Bukkit.getServer().getOnlinePlayers()) { + entities.add(this.getByPlayer(player)); + } + return entities; + } - @Override - public FPlayer getByPlayer(Player player) { - return getById(player.getUniqueId().toString()); - } + @Override + public FPlayer getByPlayer(Player player) { + return getById(player.getUniqueId().toString()); + } - @Override - public List getAllFPlayers() { - return new ArrayList<>(fPlayers.values()); - } + @Override + public List getAllFPlayers() { + return new ArrayList<>(fPlayers.values()); + } - @Override - public abstract void forceSave(); + @Override + public abstract void forceSave(); - public abstract void load(); + public abstract void load(); - @Override - public FPlayer getByOfflinePlayer(OfflinePlayer player) { - return getById(player.getUniqueId().toString()); - } + @Override + public FPlayer getByOfflinePlayer(OfflinePlayer player) { + return getById(player.getUniqueId().toString()); + } - @Override - public FPlayer getById(String id) { - FPlayer player = fPlayers.get(id); - if (player == null) { - player = generateFPlayer(id); - } - return player; - } + @Override + public FPlayer getById(String id) { + FPlayer player = fPlayers.get(id); + if (player == null) { + player = generateFPlayer(id); + } + return player; + } - public abstract FPlayer generateFPlayer(String id); + public abstract FPlayer generateFPlayer(String id); - public abstract void convertFrom(MemoryFPlayers old); + public abstract void convertFrom(MemoryFPlayers old); } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java index 306826d4..c66bce5f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFaction.java @@ -34,1211 +34,1211 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; public abstract class MemoryFaction implements Faction, EconomyParticipator { - public HashMap rules = new HashMap(); - public int tnt; - public Location checkpoint; - public LazyLocation vault; - public HashMap upgrades = new HashMap<>(); - protected String id = null; - protected boolean peacefulExplosionsEnabled; - protected boolean permanent; - protected String tag; - protected String description; - protected boolean open; - protected boolean peaceful; - protected Integer permanentPower; - protected LazyLocation home; - protected long foundedDate; - protected transient long lastPlayerLoggedOffTime; - protected double money; - protected double powerBoost; - protected String paypal; - protected Map relationWish = new HashMap<>(); - protected Map> claimOwnership = new ConcurrentHashMap<>(); - protected transient Set fplayers = new HashSet<>(); - protected Set invites = new HashSet<>(); - protected HashMap> announcements = new HashMap<>(); - protected ConcurrentHashMap warps = new ConcurrentHashMap<>(); - protected ConcurrentHashMap warpPasswords = new ConcurrentHashMap<>(); - protected int maxVaults; - protected Role defaultRole; - protected Map> permissions = new HashMap<>(); - protected Set bans = new HashSet<>(); - protected String player; - Inventory chest; - Map bannerSerialized; - private long lastDeath; - - // -------------------------------------------- // - // Construct - // -------------------------------------------- // - public MemoryFaction() { - } - - public MemoryFaction(String id) { - this.id = id; - this.open = Conf.newFactionsDefaultOpen; - this.tag = "???"; - this.description = TL.GENERIC_DEFAULTDESCRIPTION.toString(); - this.lastPlayerLoggedOffTime = 0; - this.peaceful = false; - this.peacefulExplosionsEnabled = false; - this.permanent = false; - this.money = 0.0; - this.powerBoost = 0.0; - this.foundedDate = System.currentTimeMillis(); - this.maxVaults = Conf.defaultMaxVaults; - this.defaultRole = Role.RECRUIT; - - resetPerms(); // Reset on new Faction so it has default values. - } - - public MemoryFaction(MemoryFaction old) { - id = old.id; - peacefulExplosionsEnabled = old.peacefulExplosionsEnabled; - permanent = old.permanent; - tag = old.tag; - description = old.description; - open = old.open; - foundedDate = old.foundedDate; - peaceful = old.peaceful; - permanentPower = old.permanentPower; - home = old.home; - lastPlayerLoggedOffTime = old.lastPlayerLoggedOffTime; - money = old.money; - powerBoost = old.powerBoost; - relationWish = old.relationWish; - claimOwnership = old.claimOwnership; - fplayers = new HashSet<>(); - invites = old.invites; - announcements = old.announcements; - this.defaultRole = Role.NORMAL; - - resetPerms(); // Reset on new Faction so it has default values. - } - - public HashMap> getAnnouncements() { - return this.announcements; - } - - public void addAnnouncement(FPlayer fPlayer, String msg) { - List list = announcements.containsKey(fPlayer.getId()) ? announcements.get(fPlayer.getId()) : new ArrayList(); - list.add(msg); - announcements.put(fPlayer.getId(), list); - } - - public void sendUnreadAnnouncements(FPlayer fPlayer) { - if (!announcements.containsKey(fPlayer.getId())) { - return; - } - fPlayer.msg(TL.FACTIONS_ANNOUNCEMENT_TOP); - for (String s : announcements.get(fPlayer.getPlayer().getUniqueId().toString())) { - fPlayer.sendMessage(s); - } - fPlayer.msg(TL.FACTIONS_ANNOUNCEMENT_BOTTOM); - announcements.remove(fPlayer.getId()); - } - - public void removeAnnouncements(FPlayer fPlayer) { - announcements.remove(fPlayer.getId()); - } - - public ConcurrentHashMap getWarps() { - return this.warps; - } - - public LazyLocation getWarp(String name) { - return this.warps.get(name); - } - - public void setWarp(String name, LazyLocation loc) { - this.warps.put(name, loc); - } - - public boolean isWarp(String name) { - return this.warps.containsKey(name); - } - - public boolean removeWarp(String name) { - warpPasswords.remove(name); // remove password no matter what. - return warps.remove(name) != null; - } - - public boolean isWarpPassword(String warp, String password) { - return hasWarpPassword(warp) && warpPasswords.get(warp.toLowerCase()).equals(password); - } - - public String getPaypal() { - return this.paypal; - } - - public void paypalSet(String paypal) { - this.paypal = paypal; - } - - public boolean hasWarpPassword(String warp) { - return warpPasswords.containsKey(warp.toLowerCase()); - } - - public void setWarpPassword(String warp, String password) { - warpPasswords.put(warp.toLowerCase(), password); - } - - public void clearWarps() { - warps.clear(); - } - - public int getMaxVaults() { - return this.maxVaults; - } - - public void setMaxVaults(int value) { - this.maxVaults = value; - } - - public String getFocused() { - return this.player; - } - - public void setFocused(String fp) { - this.player = fp; - } - - public Set getInvites() { - return invites; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public void invite(FPlayer fplayer) { - this.invites.add(fplayer.getId()); - } - - public void deinvite(FPlayer fplayer) { - this.invites.remove(fplayer.getId()); - } - - public boolean isInvited(FPlayer fplayer) { - return this.invites.contains(fplayer.getId()); - } - - public void ban(FPlayer target, FPlayer banner) { - BanInfo info = new BanInfo(banner.getId(), target.getId(), System.currentTimeMillis()); - this.bans.add(info); - } - - public void unban(FPlayer player) { - Iterator iter = bans.iterator(); - while (iter.hasNext()) { - if (iter.next().getBanned().equalsIgnoreCase(player.getId())) { - iter.remove(); - } - } - } - - @Override - public void disband(Player disbander) { - disband(disbander, PlayerDisbandReason.PLUGIN); - } - - @Override - public void disband(Player disbander, PlayerDisbandReason reason) { - - boolean disbanderIsConsole = disbander == null; - FPlayer fdisbander = FPlayers.getInstance().getByOfflinePlayer(disbander); - - FactionDisbandEvent disbandEvent = new FactionDisbandEvent(disbander, this.getId(), reason); - Bukkit.getServer().getPluginManager().callEvent(disbandEvent); - if (disbandEvent.isCancelled()) { - return; - } - - // Send FPlayerLeaveEvent for each player in the faction - for (FPlayer fplayer : this.getFPlayers()) { - Bukkit.getServer().getPluginManager().callEvent(new FPlayerLeaveEvent(fplayer, this, FPlayerLeaveEvent.PlayerLeaveReason.DISBAND)); - } - - if (Conf.logFactionDisband) { - //TODO: Format this correctly and translate. - SavageFactions.plugin.log("The faction " + this.getTag() + " (" + this.getId() + ") was disbanded by " + (disbanderIsConsole ? "console command" : fdisbander.getName()) + "."); - } - - if (Econ.shouldBeUsed() && !disbanderIsConsole) { - //Give all the faction's money to the disbander - double amount = Econ.getBalance(this.getAccountId()); - Econ.transferMoney(fdisbander, this, fdisbander, amount, false); - - if (amount > 0.0) { - String amountString = Econ.moneyString(amount); - msg(TL.COMMAND_DISBAND_HOLDINGS, amountString); - //TODO: Format this correctly and translate - SavageFactions.plugin.log(fdisbander.getName() + " has been given bank holdings of " + amountString + " from disbanding " + this.getTag() + "."); - } - } - - Factions.getInstance().removeFaction(this.getId()); - FTeamWrapper.applyUpdates(this); - } - - public boolean isBanned(FPlayer player) { - for (BanInfo info : bans) { - if (info.getBanned().equalsIgnoreCase(player.getId())) { - return true; - } - } - - return false; - } - - public Set getBannedPlayers() { - return this.bans; - } - - public String getRule(int index) { - if (rules.size() == 0) return null; - return rules.get(index); - } - - public HashMap getRulesMap() { - return rules; - } - - public void setRule(int index, String rule) { - rules.put(index, rule); - } - - public void removeRule(int index) { - HashMap newRule = rules; - newRule.remove(index); - rules = newRule; - } - - public void addTnt(int amt) { - tnt += amt; - } - - public void takeTnt(int amt) { - tnt -= amt; - } - - public int getTnt() { - return tnt; - } - - - public Location getVault() { - if (vault == null) { - return null; - } - return vault.getLocation(); - } - - public void setVault(Location vaultLocation) { - if (vaultLocation == null) { - vault = null; - return; - } - LazyLocation newlocation = new LazyLocation(vaultLocation); - vault = newlocation; - } - - public int getUpgrade(Upgrade upgrade) { - if (upgrades.keySet().contains(upgrade.toString())) { - return upgrades.get(upgrade.toString()); - } - return 0; - } - - @Override - public Inventory getChestInventory() { - if (chest != null) { - return chest; - } else { - int level = getUpgrade(Upgrade.CHEST); - int size = 9; - if (level == 1) { - size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1") * 9; - } else if (level == 2) { - size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2") * 9; - } else if (level == 3) { - size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3") * 9; - } - - chest = Bukkit.createInventory(null, size, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fchest.Inventory-Title"))); - return chest; - - } - - } - - @Override - public void setChestSize(int chestSize) { - ItemStack[] contents = this.getChestInventory().getContents(); - chest = Bukkit.createInventory(null, chestSize, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fchest.Inventory-Title"))); - chest.setContents(contents); - } - - - @Override - public void setBannerPattern(ItemStack banner) { - bannerSerialized = banner.serialize(); - } - - @Override - public ItemStack getBanner() { - if (bannerSerialized == null) { - return null; - } - return ItemStack.deserialize(bannerSerialized); - } - - public void setUpgrade(Upgrade upgrade, int level) { - upgrades.put(upgrade.toString(), level); - } - - public Location getCheckpoint() { - return checkpoint; - } - - public void setCheckpoint(Location location) { - checkpoint = location; - } - - public void clearRules() { - rules.clear(); - } - - public void addRule(String rule) { - rules.put(rules.size(), rule); - } - - public boolean getOpen() { - return open; - } - - public void setOpen(boolean isOpen) { - open = isOpen; - } - - public boolean isPeaceful() { - return this.peaceful; - } - - public void setPeaceful(boolean isPeaceful) { - this.peaceful = isPeaceful; - } - - public boolean getPeacefulExplosionsEnabled() { - return this.peacefulExplosionsEnabled; - } - - public void setPeacefulExplosionsEnabled(boolean val) { - peacefulExplosionsEnabled = val; - } - - public boolean noExplosionsInTerritory() { - return this.peaceful && !peacefulExplosionsEnabled; - } - - public boolean isPermanent() { - return permanent || !this.isNormal(); - } - - public void setPermanent(boolean isPermanent) { - permanent = isPermanent; - } - - public String getTag() { - return this.tag; - } - - public void setTag(String str) { - if (Conf.factionTagForceUpperCase) { - str = str.toUpperCase(); - } - this.tag = str; - } - - public String getTag(String prefix) { - return prefix + this.tag; - } - - public String getTag(Faction otherFaction) { - if (otherFaction == null) { - return getTag(); - } - return this.getTag(this.getColorTo(otherFaction).toString()); - } - - public String getTag(FPlayer otherFplayer) { - if (otherFplayer == null) { - return getTag(); - } - return this.getTag(this.getColorTo(otherFplayer).toString()); - } - - public String getComparisonTag() { - return MiscUtil.getComparisonString(this.tag); - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String value) { - this.description = value; - } - - public boolean hasHome() { - return this.getHome() != null; - } - - public Location getHome() { - confirmValidHome(); - return (this.home != null) ? this.home.getLocation() : null; - } - - public void setHome(Location home) { - this.home = new LazyLocation(home); - } - - public long getFoundedDate() { - if (this.foundedDate == 0) { - setFoundedDate(System.currentTimeMillis()); - } - return this.foundedDate; - } - - public void setFoundedDate(long newDate) { - this.foundedDate = newDate; - } - - public void confirmValidHome() { - if (!Conf.homesMustBeInClaimedTerritory || this.home == null || (this.home.getLocation() != null && Board.getInstance().getFactionAt(new FLocation(this.home.getLocation())) == this)) { - return; - } - - msg("Your faction home has been un-set since it is no longer in your territory."); - this.home = null; - } - - public String getAccountId() { - String aid = "faction-" + this.getId(); - - // We need to override the default money given to players. - if (!Econ.hasAccount(aid)) { - Econ.setBalance(aid, 0); - } - - return aid; - } - - public Integer getPermanentPower() { - return this.permanentPower; - } - - public void setPermanentPower(Integer permanentPower) { - this.permanentPower = permanentPower; - } - - public boolean hasPermanentPower() { - return this.permanentPower != null; - } - - public double getPowerBoost() { - return this.powerBoost; - } - - public void setPowerBoost(double powerBoost) { - this.powerBoost = powerBoost; - } - - public boolean isPowerFrozen() { - int freezeSeconds = SavageFactions.plugin.getConfig().getInt("hcf.powerfreeze", 0); - return freezeSeconds != 0 && System.currentTimeMillis() - lastDeath < freezeSeconds * 1000; - - } - - public long getLastDeath() { - return this.lastDeath; - } - - // -------------------------------------------- // - // F Permissions stuff - // -------------------------------------------- // - - public void setLastDeath(long time) { - this.lastDeath = time; - } - - public int getKills() { - int kills = 0; - for (FPlayer fp : getFPlayers()) { - kills += fp.getKills(); - } - - return kills; - } - - public int getDeaths() { - int deaths = 0; - for (FPlayer fp : getFPlayers()) { - deaths += fp.getDeaths(); - } - - return deaths; - } - - public Access getAccess(Permissable permissable, PermissableAction permissableAction) { - if (permissable == null || permissableAction == null) { - return Access.UNDEFINED; - } - - Map accessMap = permissions.get(permissable); - if (accessMap != null && accessMap.containsKey(permissableAction)) { - return accessMap.get(permissableAction); - } - - return Access.UNDEFINED; - } - - /** - * Get the Access of a player. Will use player's Role if they are a faction member. Otherwise, uses their Relation. - * - * @param player - * @param permissableAction - * @return - */ - public Access getAccess(FPlayer player, PermissableAction permissableAction) { - if (player == null || permissableAction == null) { - return Access.UNDEFINED; - } - - Permissable perm; - - if (player.getFaction() == this) { - perm = player.getRole(); - } else { - perm = player.getFaction().getRelationTo(this); - } - - Map accessMap = permissions.get(perm); - if (accessMap != null && accessMap.containsKey(permissableAction)) { - return accessMap.get(permissableAction); - } - - return Access.UNDEFINED; - } - - public void setPermission(Permissable permissable, PermissableAction permissableAction, Access access) { - Map accessMap = permissions.get(permissable); - if (accessMap == null) { - accessMap = new HashMap<>(); - } - - accessMap.put(permissableAction, access); - } - - public void resetPerms() { - SavageFactions.plugin.log(Level.WARNING, "Resetting permissions for Faction: " + tag); - - permissions.clear(); - - // First populate a map with undefined as the permission for each action. - Map freshMap = new HashMap<>(); - for (PermissableAction permissableAction : PermissableAction.values()) { - freshMap.put(permissableAction, Access.UNDEFINED); - } - - // Put the map in there for each relation. - for (Relation relation : Relation.values()) { - if (relation != Relation.MEMBER) { - permissions.put(relation, new HashMap<>(freshMap)); - } - } - - // And each role. - for (Role role : Role.values()) { - if (role != Role.LEADER) { - permissions.put(role, new HashMap<>(freshMap)); - } - } - } - - public void setDefaultPerms() { - if (!Conf.useCustomDefaultPermissions) return; - Map defaultMap = new HashMap<>(); - for (PermissableAction permissableAction : PermissableAction.values()) { - defaultMap.put(permissableAction, Access.UNDEFINED); - } - // Put the map in there for each relation. - for (Relation relation : Relation.values()) { - if (relation != Relation.MEMBER) { - if (!Conf.defaultFactionPermissions.containsKey(relation.nicename)) - permissions.put(relation, new HashMap<>(defaultMap)); - else - permissions.put(relation, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(relation.nicename))); - } - } - - // And each role. - for (Role role : Role.values()) { - if (role != Role.LEADER) { - if (!Conf.defaultFactionPermissions.containsKey(role.nicename)) - permissions.put(role, new HashMap<>(defaultMap)); - else - permissions.put(role, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(role.nicename))); - } - } - } - - /** - * Read only map of Permissions. - * - * @return - */ - public Map> getPermissions() { - return Collections.unmodifiableMap(permissions); - } - - public Role getDefaultRole() { - return this.defaultRole; - } - - public void setDefaultRole(Role role) { - this.defaultRole = role; - } - - // -------------------------------------------- // - // Extra Getters And Setters - // -------------------------------------------- // - public boolean noPvPInTerritory() { - return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP); - } - - public boolean noMonstersInTerritory() { - return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters); - } - - // ------------------------------- - // Understand the types - // ------------------------------- - - public boolean isNormal() { - return !(this.isWilderness() || this.isSafeZone() || this.isWarZone()); - } - - public boolean isNone() { - return this.getId().equals("0"); - } - - public boolean isWilderness() { - return this.getId().equals("0"); - } - - public boolean isSafeZone() { - return this.getId().equals("-1"); - } - - public boolean isWarZone() { - return this.getId().equals("-2"); - } - - public boolean isPlayerFreeType() { - return this.isSafeZone() || this.isWarZone(); - } - - // ------------------------------- - // Relation and relation colors - // ------------------------------- - - @Override - public String describeTo(RelationParticipator that, boolean ucfirst) { - return RelationUtil.describeThatToMe(this, that, ucfirst); - } - - @Override - public String describeTo(RelationParticipator that) { - return RelationUtil.describeThatToMe(this, that); - } - - @Override - public Relation getRelationTo(RelationParticipator rp) { - return RelationUtil.getRelationTo(this, rp); - } - - @Override - public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { - return RelationUtil.getRelationTo(this, rp, ignorePeaceful); - } - - @Override - public ChatColor getColorTo(RelationParticipator rp) { - return RelationUtil.getColorOfThatToMe(this, rp); - } - - public Relation getRelationWish(Faction otherFaction) { - if (this.relationWish.containsKey(otherFaction.getId())) { - return this.relationWish.get(otherFaction.getId()); - } - return Relation.fromString(SavageFactions.plugin.getConfig().getString("default-relation", "neutral")); // Always default to old behavior. - } - - public void setRelationWish(Faction otherFaction, Relation relation) { - if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)) { - this.relationWish.remove(otherFaction.getId()); - } else { - this.relationWish.put(otherFaction.getId(), relation); - } - } - - public int getRelationCount(Relation relation) { - int count = 0; - for (Faction faction : Factions.getInstance().getAllFactions()) { - if (faction.getRelationTo(this) == relation) { - count++; - } - } - return count; - } - - // ----------------------------------------------// - // Power - // ----------------------------------------------// - public double getPower() { - if (this.hasPermanentPower()) { - return this.getPermanentPower(); - } - - double ret = 0; - for (FPlayer fplayer : fplayers) { - ret += fplayer.getPower(); - } - if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { - ret = Conf.powerFactionMax; - } - return ret + this.powerBoost; - } - - public double getPowerMax() { - if (this.hasPermanentPower()) { - return this.getPermanentPower(); - } - - double ret = 0; - for (FPlayer fplayer : fplayers) { - ret += fplayer.getPowerMax(); - } - if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { - ret = Conf.powerFactionMax; - } - return ret + this.powerBoost; - } - - public int getPowerRounded() { - return (int) Math.round(this.getPower()); - } - - public int getPowerMaxRounded() { - return (int) Math.round(this.getPowerMax()); - } - - public int getLandRounded() { - return Board.getInstance().getFactionCoordCount(this); - } - - public int getLandRoundedInWorld(String worldName) { - return Board.getInstance().getFactionCoordCountInWorld(this, worldName); - } - - public boolean hasLandInflation() { - return this.getLandRounded() > this.getPowerRounded(); - } - - // ------------------------------- - // FPlayers - // ------------------------------- - - // maintain the reference list of FPlayers in this faction - public void refreshFPlayers() { - fplayers.clear(); - if (this.isPlayerFreeType()) { - return; - } - - for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { - if (fplayer.getFactionId().equalsIgnoreCase(id)) { - fplayers.add(fplayer); - } - } - } - - public boolean addFPlayer(FPlayer fplayer) { - return !this.isPlayerFreeType() && fplayers.add(fplayer); - } - - public boolean removeFPlayer(FPlayer fplayer) { - return !this.isPlayerFreeType() && fplayers.remove(fplayer); - } - - public int getSize() { - return fplayers.size(); - } - - public Set getFPlayers() { - // return a shallow copy of the FPlayer list, to prevent tampering and - // concurrency issues - return new HashSet<>(fplayers); - } - - public Set getFPlayersWhereOnline(boolean online) { - Set ret = new HashSet<>(); - if (!this.isNormal()) { - return ret; - } - - for (FPlayer fplayer : fplayers) { - if (fplayer.isOnline() == online) { - ret.add(fplayer); - } - } - - return ret; - } - - public Set getFPlayersWhereOnline(boolean online, FPlayer viewer) { - Set ret = new HashSet<>(); - if (!this.isNormal()) { - return ret; - } - - for (FPlayer viewed : fplayers) { - // Add if their online status is what we want - if (viewed.isOnline() == online) { - // If we want online, check to see if we are able to see this player - // This checks if they are in vanish. - if (online - && viewed.getPlayer() != null - && viewer.getPlayer() != null - && viewer.getPlayer().canSee(viewed.getPlayer())) { - ret.add(viewed); - // If we want offline, just add them. - // Prob a better way to do this but idk. - } else if (!online) { - ret.add(viewed); - } - } - } - - return ret; - } - - - public FPlayer getFPlayerAdmin() { - if (!this.isNormal()) { - return null; - } - - for (FPlayer fplayer : fplayers) { - if (fplayer.getRole() == Role.LEADER) { - return fplayer; - } - } - return null; - } - - public FPlayer getFPlayerLeader() { - return getFPlayerAdmin(); - } - - public ArrayList getFPlayersWhereRole(Role role) { - ArrayList ret = new ArrayList<>(); - if (!this.isNormal()) { - return ret; - } - - for (FPlayer fplayer : fplayers) { - if (fplayer.getRole() == role) { - ret.add(fplayer); - } - } - - return ret; - } - - public ArrayList getOnlinePlayers() { - ArrayList ret = new ArrayList<>(); - if (this.isPlayerFreeType()) { - return ret; - } - - for (Player player : SavageFactions.plugin.getServer().getOnlinePlayers()) { - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fplayer.getFaction() == this) { - ret.add(player); - } - } - - return ret; - } - - // slightly faster check than getOnlinePlayers() if you just want to see if - // there are any players online - public boolean hasPlayersOnline() { - // only real factions can have players online, not safe zone / war zone - if (this.isPlayerFreeType()) { - return false; - } - - for (Player player : SavageFactions.plugin.getServer().getOnlinePlayers()) { - FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); - if (fplayer != null && fplayer.getFaction() == this) { - return true; - } - } - - // even if all players are technically logged off, maybe someone was on - // recently enough to not consider them officially offline yet - return Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000); - } - - public void memberLoggedOff() { - if (this.isNormal()) { - lastPlayerLoggedOffTime = System.currentTimeMillis(); - } - } - - // used when current leader is about to be removed from the faction; - // promotes new leader, or disbands faction if no other members left - @Override - public void promoteNewLeader() { - promoteNewLeader(false); - } - - @Override - public void promoteNewLeader(boolean autoLeave) { - if (!this.isNormal()) { - return; - } - if (this.isPermanent() && Conf.permanentFactionsDisableLeaderPromotion) { - return; - } - - FPlayer oldLeader = this.getFPlayerAdmin(); - - // get list of moderators, or list of normal members if there are no moderators - ArrayList replacements = this.getFPlayersWhereRole(Role.MODERATOR); - if (replacements == null || replacements.isEmpty()) { - replacements = this.getFPlayersWhereRole(Role.NORMAL); - } - - if (replacements == null || replacements.isEmpty()) { // faction admin is the only member; one-man faction - if (this.isPermanent()) { - if (oldLeader != null) { - oldLeader.setRole(Role.NORMAL); - } - return; - } - - // no members left and faction isn't permanent, so disband it - if (Conf.logFactionDisband) { - SavageFactions.plugin.log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left" + (autoLeave ? " and by inactivity" : "") + "."); - } - - for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { - fplayer.msg("The faction %s was disbanded.", this.getTag(fplayer)); - } - - FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), autoLeave ? PlayerDisbandReason.INACTIVITY : PlayerDisbandReason.LEAVE); - Bukkit.getPluginManager().callEvent(disbandEvent); - - Factions.getInstance().removeFaction(getId()); - } else { // promote new faction admin - if (oldLeader != null) { - oldLeader.setRole(Role.NORMAL); - } - replacements.get(0).setRole(Role.LEADER); - //TODO:TL - this.msg("Faction admin %s has been removed. %s has been promoted as the new faction admin.", oldLeader == null ? "" : oldLeader.getName(), replacements.get(0).getName()); - SavageFactions.plugin.log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); - } - } - - // ----------------------------------------------// - // Messages - // ----------------------------------------------// - public void msg(String message, Object... args) { - message = SavageFactions.plugin.txt.parse(message, args); - - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { - fplayer.sendMessage(message); - } - } - - public void msg(TL translation, Object... args) { - msg(translation.toString(), args); - } - - public void sendMessage(String message) { - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { - fplayer.sendMessage(message); - } - } - - public void sendMessage(List messages) { - for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { - fplayer.sendMessage(messages); - } - } - - // ----------------------------------------------// - // Ownership of specific claims - // ----------------------------------------------// - - public Map> getClaimOwnership() { - return claimOwnership; - } - - public void clearAllClaimOwnership() { - claimOwnership.clear(); - } - - public void clearClaimOwnership(FLocation loc) { - claimOwnership.remove(loc); - } - - public void clearClaimOwnership(FPlayer player) { - if (id == null || id.isEmpty()) { - return; - } - - Set ownerData; - - for (Entry> entry : claimOwnership.entrySet()) { - ownerData = entry.getValue(); - - if (ownerData == null) { - continue; - } - - Iterator iter = ownerData.iterator(); - while (iter.hasNext()) { - if (iter.next().equals(player.getId())) { - iter.remove(); - } - } - - if (ownerData.isEmpty()) { - claimOwnership.remove(entry.getKey()); - } - } - } - - public int getCountOfClaimsWithOwners() { - return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); - } - - public boolean doesLocationHaveOwnersSet(FLocation loc) { - if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { - return false; - } - - Set ownerData = claimOwnership.get(loc); - return ownerData != null && !ownerData.isEmpty(); - } - - public boolean isPlayerInOwnerList(FPlayer player, FLocation loc) { - if (claimOwnership.isEmpty()) { - return false; - } - Set ownerData = claimOwnership.get(loc); - return ownerData != null && ownerData.contains(player.getId()); - } - - public void setPlayerAsOwner(FPlayer player, FLocation loc) { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) { - ownerData = new HashSet<>(); - } - ownerData.add(player.getId()); - claimOwnership.put(loc, ownerData); - } - - public void removePlayerAsOwner(FPlayer player, FLocation loc) { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null) { - return; - } - ownerData.remove(player.getId()); - claimOwnership.put(loc, ownerData); - } - - public Set getOwnerList(FLocation loc) { - return claimOwnership.get(loc); - } - - public String getOwnerListString(FLocation loc) { - Set ownerData = claimOwnership.get(loc); - if (ownerData == null || ownerData.isEmpty()) { - return ""; - } - - StringBuilder ownerList = new StringBuilder(); - - for (String anOwnerData : ownerData) { - if (ownerList.length() > 0) { - ownerList.append(", "); - } - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(anOwnerData)); - //TODO:TL - ownerList.append(offlinePlayer != null ? offlinePlayer.getName() : "null player"); - } - return ownerList.toString(); - } - - public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { - // in own faction, with sufficient role or permission to bypass - // ownership? - if (fplayer.getFaction() == this && (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.LEADER) || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) { - return true; - } - - // make sure claimOwnership is initialized - if (claimOwnership.isEmpty()) { - return true; - } - - // need to check the ownership list, then - Set ownerData = claimOwnership.get(loc); - - // if no owner list, owner list is empty, or player is in owner list, - // they're allowed - return ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getId()); - } - - // ----------------------------------------------// - // Persistance and entity management - // ----------------------------------------------// - public void remove() { - if (Econ.shouldBeUsed()) { - Econ.setBalance(getAccountId(), 0); - } - - // Clean the board - ((MemoryBoard) Board.getInstance()).clean(id); - - for (FPlayer fPlayer : fplayers) { - fPlayer.resetFactionData(false); - } - } - - public Set getAllClaims() { - return Board.getInstance().getAllClaims(this); - } + public HashMap rules = new HashMap(); + public int tnt; + public Location checkpoint; + public LazyLocation vault; + public HashMap upgrades = new HashMap<>(); + protected String id = null; + protected boolean peacefulExplosionsEnabled; + protected boolean permanent; + protected String tag; + protected String description; + protected boolean open; + protected boolean peaceful; + protected Integer permanentPower; + protected LazyLocation home; + protected long foundedDate; + protected transient long lastPlayerLoggedOffTime; + protected double money; + protected double powerBoost; + protected String paypal; + protected Map relationWish = new HashMap<>(); + protected Map> claimOwnership = new ConcurrentHashMap<>(); + protected transient Set fplayers = new HashSet<>(); + protected Set invites = new HashSet<>(); + protected HashMap> announcements = new HashMap<>(); + protected ConcurrentHashMap warps = new ConcurrentHashMap<>(); + protected ConcurrentHashMap warpPasswords = new ConcurrentHashMap<>(); + protected int maxVaults; + protected Role defaultRole; + protected Map> permissions = new HashMap<>(); + protected Set bans = new HashSet<>(); + protected String player; + Inventory chest; + Map bannerSerialized; + private long lastDeath; + + // -------------------------------------------- // + // Construct + // -------------------------------------------- // + public MemoryFaction() { + } + + public MemoryFaction(String id) { + this.id = id; + this.open = Conf.newFactionsDefaultOpen; + this.tag = "???"; + this.description = TL.GENERIC_DEFAULTDESCRIPTION.toString(); + this.lastPlayerLoggedOffTime = 0; + this.peaceful = false; + this.peacefulExplosionsEnabled = false; + this.permanent = false; + this.money = 0.0; + this.powerBoost = 0.0; + this.foundedDate = System.currentTimeMillis(); + this.maxVaults = Conf.defaultMaxVaults; + this.defaultRole = Role.RECRUIT; + + resetPerms(); // Reset on new Faction so it has default values. + } + + public MemoryFaction(MemoryFaction old) { + id = old.id; + peacefulExplosionsEnabled = old.peacefulExplosionsEnabled; + permanent = old.permanent; + tag = old.tag; + description = old.description; + open = old.open; + foundedDate = old.foundedDate; + peaceful = old.peaceful; + permanentPower = old.permanentPower; + home = old.home; + lastPlayerLoggedOffTime = old.lastPlayerLoggedOffTime; + money = old.money; + powerBoost = old.powerBoost; + relationWish = old.relationWish; + claimOwnership = old.claimOwnership; + fplayers = new HashSet<>(); + invites = old.invites; + announcements = old.announcements; + this.defaultRole = Role.NORMAL; + + resetPerms(); // Reset on new Faction so it has default values. + } + + public HashMap> getAnnouncements() { + return this.announcements; + } + + public void addAnnouncement(FPlayer fPlayer, String msg) { + List list = announcements.containsKey(fPlayer.getId()) ? announcements.get(fPlayer.getId()) : new ArrayList(); + list.add(msg); + announcements.put(fPlayer.getId(), list); + } + + public void sendUnreadAnnouncements(FPlayer fPlayer) { + if (!announcements.containsKey(fPlayer.getId())) { + return; + } + fPlayer.msg(TL.FACTIONS_ANNOUNCEMENT_TOP); + for (String s : announcements.get(fPlayer.getPlayer().getUniqueId().toString())) { + fPlayer.sendMessage(s); + } + fPlayer.msg(TL.FACTIONS_ANNOUNCEMENT_BOTTOM); + announcements.remove(fPlayer.getId()); + } + + public void removeAnnouncements(FPlayer fPlayer) { + announcements.remove(fPlayer.getId()); + } + + public ConcurrentHashMap getWarps() { + return this.warps; + } + + public LazyLocation getWarp(String name) { + return this.warps.get(name); + } + + public void setWarp(String name, LazyLocation loc) { + this.warps.put(name, loc); + } + + public boolean isWarp(String name) { + return this.warps.containsKey(name); + } + + public boolean removeWarp(String name) { + warpPasswords.remove(name); // remove password no matter what. + return warps.remove(name) != null; + } + + public boolean isWarpPassword(String warp, String password) { + return hasWarpPassword(warp) && warpPasswords.get(warp.toLowerCase()).equals(password); + } + + public String getPaypal() { + return this.paypal; + } + + public void paypalSet(String paypal) { + this.paypal = paypal; + } + + public boolean hasWarpPassword(String warp) { + return warpPasswords.containsKey(warp.toLowerCase()); + } + + public void setWarpPassword(String warp, String password) { + warpPasswords.put(warp.toLowerCase(), password); + } + + public void clearWarps() { + warps.clear(); + } + + public int getMaxVaults() { + return this.maxVaults; + } + + public void setMaxVaults(int value) { + this.maxVaults = value; + } + + public String getFocused() { + return this.player; + } + + public void setFocused(String fp) { + this.player = fp; + } + + public Set getInvites() { + return invites; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public void invite(FPlayer fplayer) { + this.invites.add(fplayer.getId()); + } + + public void deinvite(FPlayer fplayer) { + this.invites.remove(fplayer.getId()); + } + + public boolean isInvited(FPlayer fplayer) { + return this.invites.contains(fplayer.getId()); + } + + public void ban(FPlayer target, FPlayer banner) { + BanInfo info = new BanInfo(banner.getId(), target.getId(), System.currentTimeMillis()); + this.bans.add(info); + } + + public void unban(FPlayer player) { + Iterator iter = bans.iterator(); + while (iter.hasNext()) { + if (iter.next().getBanned().equalsIgnoreCase(player.getId())) { + iter.remove(); + } + } + } + + @Override + public void disband(Player disbander) { + disband(disbander, PlayerDisbandReason.PLUGIN); + } + + @Override + public void disband(Player disbander, PlayerDisbandReason reason) { + + boolean disbanderIsConsole = disbander == null; + FPlayer fdisbander = FPlayers.getInstance().getByOfflinePlayer(disbander); + + FactionDisbandEvent disbandEvent = new FactionDisbandEvent(disbander, this.getId(), reason); + Bukkit.getServer().getPluginManager().callEvent(disbandEvent); + if (disbandEvent.isCancelled()) { + return; + } + + // Send FPlayerLeaveEvent for each player in the faction + for (FPlayer fplayer : this.getFPlayers()) { + Bukkit.getServer().getPluginManager().callEvent(new FPlayerLeaveEvent(fplayer, this, FPlayerLeaveEvent.PlayerLeaveReason.DISBAND)); + } + + if (Conf.logFactionDisband) { + //TODO: Format this correctly and translate. + SavageFactions.plugin.log("The faction " + this.getTag() + " (" + this.getId() + ") was disbanded by " + (disbanderIsConsole ? "console command" : fdisbander.getName()) + "."); + } + + if (Econ.shouldBeUsed() && !disbanderIsConsole) { + //Give all the faction's money to the disbander + double amount = Econ.getBalance(this.getAccountId()); + Econ.transferMoney(fdisbander, this, fdisbander, amount, false); + + if (amount > 0.0) { + String amountString = Econ.moneyString(amount); + msg(TL.COMMAND_DISBAND_HOLDINGS, amountString); + //TODO: Format this correctly and translate + SavageFactions.plugin.log(fdisbander.getName() + " has been given bank holdings of " + amountString + " from disbanding " + this.getTag() + "."); + } + } + + Factions.getInstance().removeFaction(this.getId()); + FTeamWrapper.applyUpdates(this); + } + + public boolean isBanned(FPlayer player) { + for (BanInfo info : bans) { + if (info.getBanned().equalsIgnoreCase(player.getId())) { + return true; + } + } + + return false; + } + + public Set getBannedPlayers() { + return this.bans; + } + + public String getRule(int index) { + if (rules.size() == 0) return null; + return rules.get(index); + } + + public HashMap getRulesMap() { + return rules; + } + + public void setRule(int index, String rule) { + rules.put(index, rule); + } + + public void removeRule(int index) { + HashMap newRule = rules; + newRule.remove(index); + rules = newRule; + } + + public void addTnt(int amt) { + tnt += amt; + } + + public void takeTnt(int amt) { + tnt -= amt; + } + + public int getTnt() { + return tnt; + } + + + public Location getVault() { + if (vault == null) { + return null; + } + return vault.getLocation(); + } + + public void setVault(Location vaultLocation) { + if (vaultLocation == null) { + vault = null; + return; + } + LazyLocation newlocation = new LazyLocation(vaultLocation); + vault = newlocation; + } + + public int getUpgrade(Upgrade upgrade) { + if (upgrades.keySet().contains(upgrade.toString())) { + return upgrades.get(upgrade.toString()); + } + return 0; + } + + @Override + public Inventory getChestInventory() { + if (chest != null) { + return chest; + } else { + int level = getUpgrade(Upgrade.CHEST); + int size = 9; + if (level == 1) { + size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-1") * 9; + } else if (level == 2) { + size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-2") * 9; + } else if (level == 3) { + size = SavageFactions.plugin.getConfig().getInt("fupgrades.MainMenu.Chest.Chest-Size.level-3") * 9; + } + + chest = Bukkit.createInventory(null, size, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fchest.Inventory-Title"))); + return chest; + + } + + } + + @Override + public void setChestSize(int chestSize) { + ItemStack[] contents = this.getChestInventory().getContents(); + chest = Bukkit.createInventory(null, chestSize, SavageFactions.plugin.color(SavageFactions.plugin.getConfig().getString("fchest.Inventory-Title"))); + chest.setContents(contents); + } + + + @Override + public void setBannerPattern(ItemStack banner) { + bannerSerialized = banner.serialize(); + } + + @Override + public ItemStack getBanner() { + if (bannerSerialized == null) { + return null; + } + return ItemStack.deserialize(bannerSerialized); + } + + public void setUpgrade(Upgrade upgrade, int level) { + upgrades.put(upgrade.toString(), level); + } + + public Location getCheckpoint() { + return checkpoint; + } + + public void setCheckpoint(Location location) { + checkpoint = location; + } + + public void clearRules() { + rules.clear(); + } + + public void addRule(String rule) { + rules.put(rules.size(), rule); + } + + public boolean getOpen() { + return open; + } + + public void setOpen(boolean isOpen) { + open = isOpen; + } + + public boolean isPeaceful() { + return this.peaceful; + } + + public void setPeaceful(boolean isPeaceful) { + this.peaceful = isPeaceful; + } + + public boolean getPeacefulExplosionsEnabled() { + return this.peacefulExplosionsEnabled; + } + + public void setPeacefulExplosionsEnabled(boolean val) { + peacefulExplosionsEnabled = val; + } + + public boolean noExplosionsInTerritory() { + return this.peaceful && !peacefulExplosionsEnabled; + } + + public boolean isPermanent() { + return permanent || !this.isNormal(); + } + + public void setPermanent(boolean isPermanent) { + permanent = isPermanent; + } + + public String getTag() { + return this.tag; + } + + public void setTag(String str) { + if (Conf.factionTagForceUpperCase) { + str = str.toUpperCase(); + } + this.tag = str; + } + + public String getTag(String prefix) { + return prefix + this.tag; + } + + public String getTag(Faction otherFaction) { + if (otherFaction == null) { + return getTag(); + } + return this.getTag(this.getColorTo(otherFaction).toString()); + } + + public String getTag(FPlayer otherFplayer) { + if (otherFplayer == null) { + return getTag(); + } + return this.getTag(this.getColorTo(otherFplayer).toString()); + } + + public String getComparisonTag() { + return MiscUtil.getComparisonString(this.tag); + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String value) { + this.description = value; + } + + public boolean hasHome() { + return this.getHome() != null; + } + + public Location getHome() { + confirmValidHome(); + return (this.home != null) ? this.home.getLocation() : null; + } + + public void setHome(Location home) { + this.home = new LazyLocation(home); + } + + public long getFoundedDate() { + if (this.foundedDate == 0) { + setFoundedDate(System.currentTimeMillis()); + } + return this.foundedDate; + } + + public void setFoundedDate(long newDate) { + this.foundedDate = newDate; + } + + public void confirmValidHome() { + if (!Conf.homesMustBeInClaimedTerritory || this.home == null || (this.home.getLocation() != null && Board.getInstance().getFactionAt(new FLocation(this.home.getLocation())) == this)) { + return; + } + + msg("Your faction home has been un-set since it is no longer in your territory."); + this.home = null; + } + + public String getAccountId() { + String aid = "faction-" + this.getId(); + + // We need to override the default money given to players. + if (!Econ.hasAccount(aid)) { + Econ.setBalance(aid, 0); + } + + return aid; + } + + public Integer getPermanentPower() { + return this.permanentPower; + } + + public void setPermanentPower(Integer permanentPower) { + this.permanentPower = permanentPower; + } + + public boolean hasPermanentPower() { + return this.permanentPower != null; + } + + public double getPowerBoost() { + return this.powerBoost; + } + + public void setPowerBoost(double powerBoost) { + this.powerBoost = powerBoost; + } + + public boolean isPowerFrozen() { + int freezeSeconds = SavageFactions.plugin.getConfig().getInt("hcf.powerfreeze", 0); + return freezeSeconds != 0 && System.currentTimeMillis() - lastDeath < freezeSeconds * 1000; + + } + + public long getLastDeath() { + return this.lastDeath; + } + + // -------------------------------------------- // + // F Permissions stuff + // -------------------------------------------- // + + public void setLastDeath(long time) { + this.lastDeath = time; + } + + public int getKills() { + int kills = 0; + for (FPlayer fp : getFPlayers()) { + kills += fp.getKills(); + } + + return kills; + } + + public int getDeaths() { + int deaths = 0; + for (FPlayer fp : getFPlayers()) { + deaths += fp.getDeaths(); + } + + return deaths; + } + + public Access getAccess(Permissable permissable, PermissableAction permissableAction) { + if (permissable == null || permissableAction == null) { + return Access.UNDEFINED; + } + + Map accessMap = permissions.get(permissable); + if (accessMap != null && accessMap.containsKey(permissableAction)) { + return accessMap.get(permissableAction); + } + + return Access.UNDEFINED; + } + + /** + * Get the Access of a player. Will use player's Role if they are a faction member. Otherwise, uses their Relation. + * + * @param player + * @param permissableAction + * @return + */ + public Access getAccess(FPlayer player, PermissableAction permissableAction) { + if (player == null || permissableAction == null) { + return Access.UNDEFINED; + } + + Permissable perm; + + if (player.getFaction() == this) { + perm = player.getRole(); + } else { + perm = player.getFaction().getRelationTo(this); + } + + Map accessMap = permissions.get(perm); + if (accessMap != null && accessMap.containsKey(permissableAction)) { + return accessMap.get(permissableAction); + } + + return Access.UNDEFINED; + } + + public void setPermission(Permissable permissable, PermissableAction permissableAction, Access access) { + Map accessMap = permissions.get(permissable); + if (accessMap == null) { + accessMap = new HashMap<>(); + } + + accessMap.put(permissableAction, access); + } + + public void resetPerms() { + SavageFactions.plugin.log(Level.WARNING, "Resetting permissions for Faction: " + tag); + + permissions.clear(); + + // First populate a map with undefined as the permission for each action. + Map freshMap = new HashMap<>(); + for (PermissableAction permissableAction : PermissableAction.values()) { + freshMap.put(permissableAction, Access.UNDEFINED); + } + + // Put the map in there for each relation. + for (Relation relation : Relation.values()) { + if (relation != Relation.MEMBER) { + permissions.put(relation, new HashMap<>(freshMap)); + } + } + + // And each role. + for (Role role : Role.values()) { + if (role != Role.LEADER) { + permissions.put(role, new HashMap<>(freshMap)); + } + } + } + + public void setDefaultPerms() { + if (!Conf.useCustomDefaultPermissions) return; + Map defaultMap = new HashMap<>(); + for (PermissableAction permissableAction : PermissableAction.values()) { + defaultMap.put(permissableAction, Access.UNDEFINED); + } + // Put the map in there for each relation. + for (Relation relation : Relation.values()) { + if (relation != Relation.MEMBER) { + if (!Conf.defaultFactionPermissions.containsKey(relation.nicename)) + permissions.put(relation, new HashMap<>(defaultMap)); + else + permissions.put(relation, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(relation.nicename))); + } + } + + // And each role. + for (Role role : Role.values()) { + if (role != Role.LEADER) { + if (!Conf.defaultFactionPermissions.containsKey(role.nicename)) + permissions.put(role, new HashMap<>(defaultMap)); + else + permissions.put(role, PermissableAction.fromDefaults(Conf.defaultFactionPermissions.get(role.nicename))); + } + } + } + + /** + * Read only map of Permissions. + * + * @return + */ + public Map> getPermissions() { + return Collections.unmodifiableMap(permissions); + } + + public Role getDefaultRole() { + return this.defaultRole; + } + + public void setDefaultRole(Role role) { + this.defaultRole = role; + } + + // -------------------------------------------- // + // Extra Getters And Setters + // -------------------------------------------- // + public boolean noPvPInTerritory() { + return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisablePVP); + } + + public boolean noMonstersInTerritory() { + return isSafeZone() || (peaceful && Conf.peacefulTerritoryDisableMonsters); + } + + // ------------------------------- + // Understand the types + // ------------------------------- + + public boolean isNormal() { + return !(this.isWilderness() || this.isSafeZone() || this.isWarZone()); + } + + public boolean isNone() { + return this.getId().equals("0"); + } + + public boolean isWilderness() { + return this.getId().equals("0"); + } + + public boolean isSafeZone() { + return this.getId().equals("-1"); + } + + public boolean isWarZone() { + return this.getId().equals("-2"); + } + + public boolean isPlayerFreeType() { + return this.isSafeZone() || this.isWarZone(); + } + + // ------------------------------- + // Relation and relation colors + // ------------------------------- + + @Override + public String describeTo(RelationParticipator that, boolean ucfirst) { + return RelationUtil.describeThatToMe(this, that, ucfirst); + } + + @Override + public String describeTo(RelationParticipator that) { + return RelationUtil.describeThatToMe(this, that); + } + + @Override + public Relation getRelationTo(RelationParticipator rp) { + return RelationUtil.getRelationTo(this, rp); + } + + @Override + public Relation getRelationTo(RelationParticipator rp, boolean ignorePeaceful) { + return RelationUtil.getRelationTo(this, rp, ignorePeaceful); + } + + @Override + public ChatColor getColorTo(RelationParticipator rp) { + return RelationUtil.getColorOfThatToMe(this, rp); + } + + public Relation getRelationWish(Faction otherFaction) { + if (this.relationWish.containsKey(otherFaction.getId())) { + return this.relationWish.get(otherFaction.getId()); + } + return Relation.fromString(SavageFactions.plugin.getConfig().getString("default-relation", "neutral")); // Always default to old behavior. + } + + public void setRelationWish(Faction otherFaction, Relation relation) { + if (this.relationWish.containsKey(otherFaction.getId()) && relation.equals(Relation.NEUTRAL)) { + this.relationWish.remove(otherFaction.getId()); + } else { + this.relationWish.put(otherFaction.getId(), relation); + } + } + + public int getRelationCount(Relation relation) { + int count = 0; + for (Faction faction : Factions.getInstance().getAllFactions()) { + if (faction.getRelationTo(this) == relation) { + count++; + } + } + return count; + } + + // ----------------------------------------------// + // Power + // ----------------------------------------------// + public double getPower() { + if (this.hasPermanentPower()) { + return this.getPermanentPower(); + } + + double ret = 0; + for (FPlayer fplayer : fplayers) { + ret += fplayer.getPower(); + } + if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { + ret = Conf.powerFactionMax; + } + return ret + this.powerBoost; + } + + public double getPowerMax() { + if (this.hasPermanentPower()) { + return this.getPermanentPower(); + } + + double ret = 0; + for (FPlayer fplayer : fplayers) { + ret += fplayer.getPowerMax(); + } + if (Conf.powerFactionMax > 0 && ret > Conf.powerFactionMax) { + ret = Conf.powerFactionMax; + } + return ret + this.powerBoost; + } + + public int getPowerRounded() { + return (int) Math.round(this.getPower()); + } + + public int getPowerMaxRounded() { + return (int) Math.round(this.getPowerMax()); + } + + public int getLandRounded() { + return Board.getInstance().getFactionCoordCount(this); + } + + public int getLandRoundedInWorld(String worldName) { + return Board.getInstance().getFactionCoordCountInWorld(this, worldName); + } + + public boolean hasLandInflation() { + return this.getLandRounded() > this.getPowerRounded(); + } + + // ------------------------------- + // FPlayers + // ------------------------------- + + // maintain the reference list of FPlayers in this faction + public void refreshFPlayers() { + fplayers.clear(); + if (this.isPlayerFreeType()) { + return; + } + + for (FPlayer fplayer : FPlayers.getInstance().getAllFPlayers()) { + if (fplayer.getFactionId().equalsIgnoreCase(id)) { + fplayers.add(fplayer); + } + } + } + + public boolean addFPlayer(FPlayer fplayer) { + return !this.isPlayerFreeType() && fplayers.add(fplayer); + } + + public boolean removeFPlayer(FPlayer fplayer) { + return !this.isPlayerFreeType() && fplayers.remove(fplayer); + } + + public int getSize() { + return fplayers.size(); + } + + public Set getFPlayers() { + // return a shallow copy of the FPlayer list, to prevent tampering and + // concurrency issues + return new HashSet<>(fplayers); + } + + public Set getFPlayersWhereOnline(boolean online) { + Set ret = new HashSet<>(); + if (!this.isNormal()) { + return ret; + } + + for (FPlayer fplayer : fplayers) { + if (fplayer.isOnline() == online) { + ret.add(fplayer); + } + } + + return ret; + } + + public Set getFPlayersWhereOnline(boolean online, FPlayer viewer) { + Set ret = new HashSet<>(); + if (!this.isNormal()) { + return ret; + } + + for (FPlayer viewed : fplayers) { + // Add if their online status is what we want + if (viewed.isOnline() == online) { + // If we want online, check to see if we are able to see this player + // This checks if they are in vanish. + if (online + && viewed.getPlayer() != null + && viewer.getPlayer() != null + && viewer.getPlayer().canSee(viewed.getPlayer())) { + ret.add(viewed); + // If we want offline, just add them. + // Prob a better way to do this but idk. + } else if (!online) { + ret.add(viewed); + } + } + } + + return ret; + } + + + public FPlayer getFPlayerAdmin() { + if (!this.isNormal()) { + return null; + } + + for (FPlayer fplayer : fplayers) { + if (fplayer.getRole() == Role.LEADER) { + return fplayer; + } + } + return null; + } + + public FPlayer getFPlayerLeader() { + return getFPlayerAdmin(); + } + + public ArrayList getFPlayersWhereRole(Role role) { + ArrayList ret = new ArrayList<>(); + if (!this.isNormal()) { + return ret; + } + + for (FPlayer fplayer : fplayers) { + if (fplayer.getRole() == role) { + ret.add(fplayer); + } + } + + return ret; + } + + public ArrayList getOnlinePlayers() { + ArrayList ret = new ArrayList<>(); + if (this.isPlayerFreeType()) { + return ret; + } + + for (Player player : SavageFactions.plugin.getServer().getOnlinePlayers()) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer.getFaction() == this) { + ret.add(player); + } + } + + return ret; + } + + // slightly faster check than getOnlinePlayers() if you just want to see if + // there are any players online + public boolean hasPlayersOnline() { + // only real factions can have players online, not safe zone / war zone + if (this.isPlayerFreeType()) { + return false; + } + + for (Player player : SavageFactions.plugin.getServer().getOnlinePlayers()) { + FPlayer fplayer = FPlayers.getInstance().getByPlayer(player); + if (fplayer != null && fplayer.getFaction() == this) { + return true; + } + } + + // even if all players are technically logged off, maybe someone was on + // recently enough to not consider them officially offline yet + return Conf.considerFactionsReallyOfflineAfterXMinutes > 0 && System.currentTimeMillis() < lastPlayerLoggedOffTime + (Conf.considerFactionsReallyOfflineAfterXMinutes * 60000); + } + + public void memberLoggedOff() { + if (this.isNormal()) { + lastPlayerLoggedOffTime = System.currentTimeMillis(); + } + } + + // used when current leader is about to be removed from the faction; + // promotes new leader, or disbands faction if no other members left + @Override + public void promoteNewLeader() { + promoteNewLeader(false); + } + + @Override + public void promoteNewLeader(boolean autoLeave) { + if (!this.isNormal()) { + return; + } + if (this.isPermanent() && Conf.permanentFactionsDisableLeaderPromotion) { + return; + } + + FPlayer oldLeader = this.getFPlayerAdmin(); + + // get list of moderators, or list of normal members if there are no moderators + ArrayList replacements = this.getFPlayersWhereRole(Role.MODERATOR); + if (replacements == null || replacements.isEmpty()) { + replacements = this.getFPlayersWhereRole(Role.NORMAL); + } + + if (replacements == null || replacements.isEmpty()) { // faction admin is the only member; one-man faction + if (this.isPermanent()) { + if (oldLeader != null) { + oldLeader.setRole(Role.NORMAL); + } + return; + } + + // no members left and faction isn't permanent, so disband it + if (Conf.logFactionDisband) { + SavageFactions.plugin.log("The faction " + this.getTag() + " (" + this.getId() + ") has been disbanded since it has no members left" + (autoLeave ? " and by inactivity" : "") + "."); + } + + for (FPlayer fplayer : FPlayers.getInstance().getOnlinePlayers()) { + fplayer.msg("The faction %s was disbanded.", this.getTag(fplayer)); + } + + FactionDisbandEvent disbandEvent = new FactionDisbandEvent(null, getId(), autoLeave ? PlayerDisbandReason.INACTIVITY : PlayerDisbandReason.LEAVE); + Bukkit.getPluginManager().callEvent(disbandEvent); + + Factions.getInstance().removeFaction(getId()); + } else { // promote new faction admin + if (oldLeader != null) { + oldLeader.setRole(Role.NORMAL); + } + replacements.get(0).setRole(Role.LEADER); + //TODO:TL + this.msg("Faction admin %s has been removed. %s has been promoted as the new faction admin.", oldLeader == null ? "" : oldLeader.getName(), replacements.get(0).getName()); + SavageFactions.plugin.log("Faction " + this.getTag() + " (" + this.getId() + ") admin was removed. Replacement admin: " + replacements.get(0).getName()); + } + } + + // ----------------------------------------------// + // Messages + // ----------------------------------------------// + public void msg(String message, Object... args) { + message = SavageFactions.plugin.txt.parse(message, args); + + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } + + public void msg(TL translation, Object... args) { + msg(translation.toString(), args); + } + + public void sendMessage(String message) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(message); + } + } + + public void sendMessage(List messages) { + for (FPlayer fplayer : this.getFPlayersWhereOnline(true)) { + fplayer.sendMessage(messages); + } + } + + // ----------------------------------------------// + // Ownership of specific claims + // ----------------------------------------------// + + public Map> getClaimOwnership() { + return claimOwnership; + } + + public void clearAllClaimOwnership() { + claimOwnership.clear(); + } + + public void clearClaimOwnership(FLocation loc) { + claimOwnership.remove(loc); + } + + public void clearClaimOwnership(FPlayer player) { + if (id == null || id.isEmpty()) { + return; + } + + Set ownerData; + + for (Entry> entry : claimOwnership.entrySet()) { + ownerData = entry.getValue(); + + if (ownerData == null) { + continue; + } + + Iterator iter = ownerData.iterator(); + while (iter.hasNext()) { + if (iter.next().equals(player.getId())) { + iter.remove(); + } + } + + if (ownerData.isEmpty()) { + claimOwnership.remove(entry.getKey()); + } + } + } + + public int getCountOfClaimsWithOwners() { + return claimOwnership.isEmpty() ? 0 : claimOwnership.size(); + } + + public boolean doesLocationHaveOwnersSet(FLocation loc) { + if (claimOwnership.isEmpty() || !claimOwnership.containsKey(loc)) { + return false; + } + + Set ownerData = claimOwnership.get(loc); + return ownerData != null && !ownerData.isEmpty(); + } + + public boolean isPlayerInOwnerList(FPlayer player, FLocation loc) { + if (claimOwnership.isEmpty()) { + return false; + } + Set ownerData = claimOwnership.get(loc); + return ownerData != null && ownerData.contains(player.getId()); + } + + public void setPlayerAsOwner(FPlayer player, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + ownerData = new HashSet<>(); + } + ownerData.add(player.getId()); + claimOwnership.put(loc, ownerData); + } + + public void removePlayerAsOwner(FPlayer player, FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null) { + return; + } + ownerData.remove(player.getId()); + claimOwnership.put(loc, ownerData); + } + + public Set getOwnerList(FLocation loc) { + return claimOwnership.get(loc); + } + + public String getOwnerListString(FLocation loc) { + Set ownerData = claimOwnership.get(loc); + if (ownerData == null || ownerData.isEmpty()) { + return ""; + } + + StringBuilder ownerList = new StringBuilder(); + + for (String anOwnerData : ownerData) { + if (ownerList.length() > 0) { + ownerList.append(", "); + } + OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(UUID.fromString(anOwnerData)); + //TODO:TL + ownerList.append(offlinePlayer != null ? offlinePlayer.getName() : "null player"); + } + return ownerList.toString(); + } + + public boolean playerHasOwnershipRights(FPlayer fplayer, FLocation loc) { + // in own faction, with sufficient role or permission to bypass + // ownership? + if (fplayer.getFaction() == this && (fplayer.getRole().isAtLeast(Conf.ownedAreaModeratorsBypass ? Role.MODERATOR : Role.LEADER) || Permission.OWNERSHIP_BYPASS.has(fplayer.getPlayer()))) { + return true; + } + + // make sure claimOwnership is initialized + if (claimOwnership.isEmpty()) { + return true; + } + + // need to check the ownership list, then + Set ownerData = claimOwnership.get(loc); + + // if no owner list, owner list is empty, or player is in owner list, + // they're allowed + return ownerData == null || ownerData.isEmpty() || ownerData.contains(fplayer.getId()); + } + + // ----------------------------------------------// + // Persistance and entity management + // ----------------------------------------------// + public void remove() { + if (Econ.shouldBeUsed()) { + Econ.setBalance(getAccountId(), 0); + } + + // Clean the board + ((MemoryBoard) Board.getInstance()).clean(id); + + for (FPlayer fPlayer : fplayers) { + fPlayer.resetFactionData(false); + } + } + + public Set getAllClaims() { + return Board.getInstance().getAllClaims(this); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java index 76d1caee..292f083f 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/MemoryFactions.java @@ -13,164 +13,164 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public abstract class MemoryFactions extends Factions { - public final Map factions = new ConcurrentHashMap<>(); - public int nextId = 1; + public final Map factions = new ConcurrentHashMap<>(); + public int nextId = 1; - public void load() { - // Make sure the default neutral faction exists - if (!factions.containsKey("0")) { - Faction faction = generateFactionObject("0"); - factions.put("0", faction); - faction.setTag(TL.WILDERNESS.toString()); - faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); - } else { - Faction faction = factions.get("0"); - if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { - faction.setTag(TL.WILDERNESS.toString()); - } - if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { - faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); - } - } + public void load() { + // Make sure the default neutral faction exists + if (!factions.containsKey("0")) { + Faction faction = generateFactionObject("0"); + factions.put("0", faction); + faction.setTag(TL.WILDERNESS.toString()); + faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("0"); + if (!faction.getTag().equalsIgnoreCase(TL.WILDERNESS.toString())) { + faction.setTag(TL.WILDERNESS.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.WILDERNESS_DESCRIPTION.toString())) { + faction.setDescription(TL.WILDERNESS_DESCRIPTION.toString()); + } + } - // Make sure the safe zone faction exists - if (!factions.containsKey("-1")) { - Faction faction = generateFactionObject("-1"); - factions.put("-1", faction); - faction.setTag(TL.SAFEZONE.toString()); - faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); - } else { - Faction faction = factions.get("-1"); - if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { - faction.setTag(TL.SAFEZONE.toString()); - } - if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { - faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); - } - // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " - if (faction.getTag().contains(" ")) { - faction.setTag(TL.SAFEZONE.toString()); - } - } + // Make sure the safe zone faction exists + if (!factions.containsKey("-1")) { + Faction faction = generateFactionObject("-1"); + factions.put("-1", faction); + faction.setTag(TL.SAFEZONE.toString()); + faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("-1"); + if (!faction.getTag().equalsIgnoreCase(TL.SAFEZONE.toString())) { + faction.setTag(TL.SAFEZONE.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.SAFEZONE_DESCRIPTION.toString())) { + faction.setDescription(TL.SAFEZONE_DESCRIPTION.toString()); + } + // if SafeZone has old pre-1.6.0 name, rename it to remove troublesome " " + if (faction.getTag().contains(" ")) { + faction.setTag(TL.SAFEZONE.toString()); + } + } - // Make sure the war zone faction exists - if (!factions.containsKey("-2")) { - Faction faction = generateFactionObject("-2"); - factions.put("-2", faction); - faction.setTag(TL.WARZONE.toString()); - faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); - } else { - Faction faction = factions.get("-2"); - if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) { - faction.setTag(TL.WARZONE.toString()); - } - if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { - faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); - } - // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " - if (faction.getTag().contains(" ")) { - faction.setTag(TL.WARZONE.toString()); - } - } - } + // Make sure the war zone faction exists + if (!factions.containsKey("-2")) { + Faction faction = generateFactionObject("-2"); + factions.put("-2", faction); + faction.setTag(TL.WARZONE.toString()); + faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); + } else { + Faction faction = factions.get("-2"); + if (!faction.getTag().equalsIgnoreCase(TL.WARZONE.toString())) { + faction.setTag(TL.WARZONE.toString()); + } + if (!faction.getDescription().equalsIgnoreCase(TL.WARZONE_DESCRIPTION.toString())) { + faction.setDescription(TL.WARZONE_DESCRIPTION.toString()); + } + // if WarZone has old pre-1.6.0 name, rename it to remove troublesome " " + if (faction.getTag().contains(" ")) { + faction.setTag(TL.WARZONE.toString()); + } + } + } - public Faction getFactionById(String id) { - return factions.get(id); - } + public Faction getFactionById(String id) { + return factions.get(id); + } - public abstract Faction generateFactionObject(String string); + public abstract Faction generateFactionObject(String string); - public Faction getByTag(String str) { - String compStr = MiscUtil.getComparisonString(str); - for (Faction faction : factions.values()) { - if (faction.getComparisonTag().equals(compStr)) { - return faction; - } - } - return null; - } + public Faction getByTag(String str) { + String compStr = MiscUtil.getComparisonString(str); + for (Faction faction : factions.values()) { + if (faction.getComparisonTag().equals(compStr)) { + return faction; + } + } + return null; + } - public Faction getBestTagMatch(String start) { - int best = 0; - start = start.toLowerCase(); - int minlength = start.length(); - Faction bestMatch = null; - for (Faction faction : factions.values()) { - String candidate = faction.getTag(); - candidate = ChatColor.stripColor(candidate); - if (candidate.length() < minlength) { - continue; - } - if (!candidate.toLowerCase().startsWith(start)) { - continue; - } + public Faction getBestTagMatch(String start) { + int best = 0; + start = start.toLowerCase(); + int minlength = start.length(); + Faction bestMatch = null; + for (Faction faction : factions.values()) { + String candidate = faction.getTag(); + candidate = ChatColor.stripColor(candidate); + if (candidate.length() < minlength) { + continue; + } + if (!candidate.toLowerCase().startsWith(start)) { + continue; + } - // The closer to zero the better - int lendiff = candidate.length() - minlength; - if (lendiff == 0) { - return faction; - } - if (lendiff < best || best == 0) { - best = lendiff; - bestMatch = faction; - } - } + // The closer to zero the better + int lendiff = candidate.length() - minlength; + if (lendiff == 0) { + return faction; + } + if (lendiff < best || best == 0) { + best = lendiff; + bestMatch = faction; + } + } - return bestMatch; - } + return bestMatch; + } - public boolean isTagTaken(String str) { - return this.getByTag(str) != null; - } + public boolean isTagTaken(String str) { + return this.getByTag(str) != null; + } - public boolean isValidFactionId(String id) { - return factions.containsKey(id); - } + public boolean isValidFactionId(String id) { + return factions.containsKey(id); + } - public Faction createFaction() { - Faction faction = generateFactionObject(); - factions.put(faction.getId(), faction); - return faction; - } + public Faction createFaction() { + Faction faction = generateFactionObject(); + factions.put(faction.getId(), faction); + return faction; + } - public Set getFactionTags() { - Set tags = new HashSet<>(); - for (Faction faction : factions.values()) { - tags.add(faction.getTag()); - } - return tags; - } + public Set getFactionTags() { + Set tags = new HashSet<>(); + for (Faction faction : factions.values()) { + tags.add(faction.getTag()); + } + return tags; + } - public abstract Faction generateFactionObject(); + public abstract Faction generateFactionObject(); - public void removeFaction(String id) { - factions.remove(id).remove(); - } + public void removeFaction(String id) { + factions.remove(id).remove(); + } - @Override - public ArrayList getAllFactions() { - return new ArrayList<>(factions.values()); - } + @Override + public ArrayList getAllFactions() { + return new ArrayList<>(factions.values()); + } - @Override - public Faction getNone() { - return factions.get("0"); - } + @Override + public Faction getNone() { + return factions.get("0"); + } - @Override - public Faction getWilderness() { - return factions.get("0"); - } + @Override + public Faction getWilderness() { + return factions.get("0"); + } - @Override - public Faction getSafeZone() { - return factions.get("-1"); - } + @Override + public Faction getSafeZone() { + return factions.get("-1"); + } - @Override - public Faction getWarZone() { - return factions.get("-2"); - } + @Override + public Faction getWarZone() { + return factions.get("-2"); + } - public abstract void convertFrom(MemoryFactions old); + public abstract void convertFrom(MemoryFactions old); } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java index 232c9d21..892b0853 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/SaveTask.java @@ -7,24 +7,24 @@ import com.massivecraft.factions.zcore.MPlugin; public class SaveTask implements Runnable { - private static boolean running = false; + private static boolean running = false; - MPlugin p; + MPlugin p; - public SaveTask(MPlugin p) { - this.p = p; - } + public SaveTask(MPlugin p) { + this.p = p; + } - public void run() { - if (!p.getAutoSave() || running) { - return; - } - running = true; - p.preAutoSave(); - Factions.getInstance().forceSave(false); - FPlayers.getInstance().forceSave(false); - Board.getInstance().forceSave(false); - p.postAutoSave(); - running = false; - } + public void run() { + if (!p.getAutoSave() || running) { + return; + } + running = true; + p.preAutoSave(); + Factions.getInstance().forceSave(false); + FPlayers.getInstance().forceSave(false); + Board.getInstance().forceSave(false); + p.postAutoSave(); + running = false; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java index 2ee4d2da..f72c2aac 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/FactionsJSON.java @@ -10,36 +10,36 @@ import java.util.logging.Logger; public class FactionsJSON { - public static void convertTo() { - if (!(Factions.getInstance() instanceof MemoryFactions)) { - return; - } - if (!(FPlayers.getInstance() instanceof MemoryFPlayers)) { - return; - } - if (!(Board.getInstance() instanceof MemoryBoard)) { - return; - } - new BukkitRunnable() { - @Override - public void run() { - Logger logger = SavageFactions.plugin.getLogger(); - logger.info("Beginning Board conversion to JSON"); - new JSONBoard().convertFrom((MemoryBoard) Board.getInstance()); - logger.info("Board Converted"); - logger.info("Beginning FPlayers conversion to JSON"); - new JSONFPlayers().convertFrom((MemoryFPlayers) FPlayers.getInstance()); - logger.info("FPlayers Converted"); - logger.info("Beginning Factions conversion to JSON"); - new JSONFactions().convertFrom((MemoryFactions) Factions.getInstance()); - logger.info("Factions Converted"); - logger.info("Refreshing object caches"); - for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { - Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); - faction.addFPlayer(fPlayer); - } - logger.info("Conversion Complete"); - } - }.runTaskAsynchronously(SavageFactions.plugin); - } + public static void convertTo() { + if (!(Factions.getInstance() instanceof MemoryFactions)) { + return; + } + if (!(FPlayers.getInstance() instanceof MemoryFPlayers)) { + return; + } + if (!(Board.getInstance() instanceof MemoryBoard)) { + return; + } + new BukkitRunnable() { + @Override + public void run() { + Logger logger = SavageFactions.plugin.getLogger(); + logger.info("Beginning Board conversion to JSON"); + new JSONBoard().convertFrom((MemoryBoard) Board.getInstance()); + logger.info("Board Converted"); + logger.info("Beginning FPlayers conversion to JSON"); + new JSONFPlayers().convertFrom((MemoryFPlayers) FPlayers.getInstance()); + logger.info("FPlayers Converted"); + logger.info("Beginning Factions conversion to JSON"); + new JSONFactions().convertFrom((MemoryFactions) Factions.getInstance()); + logger.info("Factions Converted"); + logger.info("Refreshing object caches"); + for (FPlayer fPlayer : FPlayers.getInstance().getAllFPlayers()) { + Faction faction = Factions.getInstance().getFactionById(fPlayer.getFactionId()); + faction.addFPlayer(fPlayer); + } + logger.info("Conversion Complete"); + } + }.runTaskAsynchronously(SavageFactions.plugin); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java index d2b447ac..618d39d8 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONBoard.java @@ -16,88 +16,88 @@ import java.util.TreeMap; public class JSONBoard extends MemoryBoard { - private static transient File file = new File(SavageFactions.plugin.getDataFolder(), "board.json"); + private static transient File file = new File(SavageFactions.plugin.getDataFolder(), "board.json"); - // -------------------------------------------- // - // Persistance - // -------------------------------------------- // + // -------------------------------------------- // + // Persistance + // -------------------------------------------- // - public Map> dumpAsSaveFormat() { - Map> worldCoordIds = new HashMap<>(); + public Map> dumpAsSaveFormat() { + Map> worldCoordIds = new HashMap<>(); - String worldName, coords; - String id; + String worldName, coords; + String id; - for (Entry entry : flocationIds.entrySet()) { - worldName = entry.getKey().getWorldName(); - coords = entry.getKey().getCoordString(); - id = entry.getValue(); - if (!worldCoordIds.containsKey(worldName)) { - worldCoordIds.put(worldName, new TreeMap()); - } + for (Entry entry : flocationIds.entrySet()) { + worldName = entry.getKey().getWorldName(); + coords = entry.getKey().getCoordString(); + id = entry.getValue(); + if (!worldCoordIds.containsKey(worldName)) { + worldCoordIds.put(worldName, new TreeMap()); + } - worldCoordIds.get(worldName).put(coords, id); - } + worldCoordIds.get(worldName).put(coords, id); + } - return worldCoordIds; - } + return worldCoordIds; + } - public void loadFromSaveFormat(Map> worldCoordIds) { - flocationIds.clear(); + public void loadFromSaveFormat(Map> worldCoordIds) { + flocationIds.clear(); - String worldName; - String[] coords; - int x, z; - String factionId; + String worldName; + String[] coords; + int x, z; + String factionId; - for (Entry> entry : worldCoordIds.entrySet()) { - worldName = entry.getKey(); - for (Entry entry2 : entry.getValue().entrySet()) { - coords = entry2.getKey().trim().split("[,\\s]+"); - x = Integer.parseInt(coords[0]); - z = Integer.parseInt(coords[1]); - factionId = entry2.getValue(); - flocationIds.put(new FLocation(worldName, x, z), factionId); - } - } - } + for (Entry> entry : worldCoordIds.entrySet()) { + worldName = entry.getKey(); + for (Entry entry2 : entry.getValue().entrySet()) { + coords = entry2.getKey().trim().split("[,\\s]+"); + x = Integer.parseInt(coords[0]); + z = Integer.parseInt(coords[1]); + factionId = entry2.getValue(); + flocationIds.put(new FLocation(worldName, x, z), factionId); + } + } + } - public void forceSave() { - forceSave(true); - } + public void forceSave() { + forceSave(true); + } - public void forceSave(boolean sync) { - DiscUtil.writeCatch(file, SavageFactions.plugin.gson.toJson(dumpAsSaveFormat()), sync); - } + public void forceSave(boolean sync) { + DiscUtil.writeCatch(file, SavageFactions.plugin.gson.toJson(dumpAsSaveFormat()), sync); + } - public boolean load() { - SavageFactions.plugin.log("Loading board from disk"); + public boolean load() { + SavageFactions.plugin.log("Loading board from disk"); - if (!file.exists()) { - SavageFactions.plugin.log("No board to load from disk. Creating new file."); - forceSave(); - return true; - } + if (!file.exists()) { + SavageFactions.plugin.log("No board to load from disk. Creating new file."); + forceSave(); + return true; + } - try { - Type type = new TypeToken>>() { - }.getType(); - Map> worldCoordIds = SavageFactions.plugin.gson.fromJson(DiscUtil.read(file), type); - loadFromSaveFormat(worldCoordIds); - SavageFactions.plugin.log("Loaded " + flocationIds.size() + " board locations"); - } catch (Exception e) { - e.printStackTrace(); - SavageFactions.plugin.log("Failed to load the board from disk."); - return false; - } + try { + Type type = new TypeToken>>() { + }.getType(); + Map> worldCoordIds = SavageFactions.plugin.gson.fromJson(DiscUtil.read(file), type); + loadFromSaveFormat(worldCoordIds); + SavageFactions.plugin.log("Loaded " + flocationIds.size() + " board locations"); + } catch (Exception e) { + e.printStackTrace(); + SavageFactions.plugin.log("Failed to load the board from disk."); + return false; + } - return true; - } + return true; + } - @Override - public void convertFrom(MemoryBoard old) { - this.flocationIds = old.flocationIds; - forceSave(); - Board.instance = this; - } + @Override + public void convertFrom(MemoryBoard old) { + this.flocationIds = old.flocationIds; + forceSave(); + Board.instance = this; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java index ade236a0..d2e0618c 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayer.java @@ -6,20 +6,20 @@ import com.massivecraft.factions.zcore.persist.MemoryFPlayer; public class JSONFPlayer extends MemoryFPlayer { - public JSONFPlayer(MemoryFPlayer arg0) { - super(arg0); - } + public JSONFPlayer(MemoryFPlayer arg0) { + super(arg0); + } - public JSONFPlayer(String id) { - super(id); - } + public JSONFPlayer(String id) { + super(id); + } - @Override - public void remove() { - ((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId()); - } + @Override + public void remove() { + ((JSONFPlayers) FPlayers.getInstance()).fPlayers.remove(getId()); + } - public boolean shouldBeSaved() { - return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); - } + public boolean shouldBeSaved() { + return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java index c6c843ad..9851824a 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFPlayers.java @@ -21,170 +21,170 @@ import java.util.Map.Entry; import java.util.logging.Level; public class JSONFPlayers extends MemoryFPlayers { - // Info on how to persist - private Gson gson; - private File file; + // Info on how to persist + private Gson gson; + private File file; - public JSONFPlayers() { - file = new File(SavageFactions.plugin.getDataFolder(), "players.json"); - gson = SavageFactions.plugin.gson; - } + public JSONFPlayers() { + file = new File(SavageFactions.plugin.getDataFolder(), "players.json"); + gson = SavageFactions.plugin.gson; + } - public Gson getGson() { - return gson; - } + public Gson getGson() { + return gson; + } - public void setGson(Gson gson) { - this.gson = gson; - } + public void setGson(Gson gson) { + this.gson = gson; + } - public void convertFrom(MemoryFPlayers old) { - this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function() { - @Override - public JSONFPlayer apply(FPlayer arg0) { - return new JSONFPlayer((MemoryFPlayer) arg0); - } - })); - forceSave(); - FPlayers.instance = this; - } + public void convertFrom(MemoryFPlayers old) { + this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function() { + @Override + public JSONFPlayer apply(FPlayer arg0) { + return new JSONFPlayer((MemoryFPlayer) arg0); + } + })); + forceSave(); + FPlayers.instance = this; + } - public void forceSave() { - forceSave(true); - } + public void forceSave() { + forceSave(true); + } - public void forceSave(boolean sync) { - final Map entitiesThatShouldBeSaved = new HashMap<>(); - for (FPlayer entity : this.fPlayers.values()) { - if (((MemoryFPlayer) entity).shouldBeSaved()) { - entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity); - } - } + public void forceSave(boolean sync) { + final Map entitiesThatShouldBeSaved = new HashMap<>(); + for (FPlayer entity : this.fPlayers.values()) { + if (((MemoryFPlayer) entity).shouldBeSaved()) { + entitiesThatShouldBeSaved.put(entity.getId(), (JSONFPlayer) entity); + } + } - saveCore(file, entitiesThatShouldBeSaved, sync); - } + saveCore(file, entitiesThatShouldBeSaved, sync); + } - private boolean saveCore(File target, Map data, boolean sync) { - return DiscUtil.writeCatch(target, this.gson.toJson(data), sync); - } + private boolean saveCore(File target, Map data, boolean sync) { + return DiscUtil.writeCatch(target, this.gson.toJson(data), sync); + } - public void load() { - Map fplayers = this.loadCore(); - if (fplayers == null) { - return; - } - this.fPlayers.clear(); - this.fPlayers.putAll(fplayers); - SavageFactions.plugin.log("Loaded " + fPlayers.size() + " players"); - } + public void load() { + Map fplayers = this.loadCore(); + if (fplayers == null) { + return; + } + this.fPlayers.clear(); + this.fPlayers.putAll(fplayers); + SavageFactions.plugin.log("Loaded " + fPlayers.size() + " players"); + } - private Map loadCore() { - if (!this.file.exists()) { - return new HashMap<>(); - } + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap<>(); + } - String content = DiscUtil.readCatch(this.file); - if (content == null) { - return null; - } + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } - Map data = this.gson.fromJson(content, new TypeToken>() { - }.getType()); - Set list = new HashSet<>(); - Set invalidList = new HashSet<>(); - for (Entry entry : data.entrySet()) { - String key = entry.getKey(); - entry.getValue().setId(key); - if (doesKeyNeedMigration(key)) { - if (!isKeyInvalid(key)) { - list.add(key); - } else { - invalidList.add(key); - } - } - } + Map data = this.gson.fromJson(content, new TypeToken>() { + }.getType()); + Set list = new HashSet<>(); + Set invalidList = new HashSet<>(); + for (Entry entry : data.entrySet()) { + String key = entry.getKey(); + entry.getValue().setId(key); + if (doesKeyNeedMigration(key)) { + if (!isKeyInvalid(key)) { + list.add(key); + } else { + invalidList.add(key); + } + } + } - if (list.size() > 0) { - // We've got some converting to do! - Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json"); + if (list.size() > 0) { + // We've got some converting to do! + Bukkit.getLogger().log(Level.INFO, "Factions is now updating players.json"); - // First we'll make a backup, because god forbid anybody heed a - // warning - File file = new File(this.file.getParentFile(), "players.json.old"); - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - saveCore(file, data, true); - Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); + // First we'll make a backup, because god forbid anybody heed a + // warning + File file = new File(this.file.getParentFile(), "players.json.old"); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + saveCore(file, data, true); + Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); - // Start fetching those UUIDs - Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + list.size() + " old player names to UUID. This may take a while."); - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); - try { - Map response = fetcher.call(); - for (String s : list) { - // Are we missing any responses? - if (!response.containsKey(s)) { - // They don't have a UUID so they should just be removed - invalidList.add(s); - } - } - for (String value : response.keySet()) { - // For all the valid responses, let's replace their old - // named entry with a UUID key - String id = response.get(value).toString(); + // Start fetching those UUIDs + Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + list.size() + " old player names to UUID. This may take a while."); + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String s : list) { + // Are we missing any responses? + if (!response.containsKey(s)) { + // They don't have a UUID so they should just be removed + invalidList.add(s); + } + } + for (String value : response.keySet()) { + // For all the valid responses, let's replace their old + // named entry with a UUID key + String id = response.get(value).toString(); - JSONFPlayer player = data.get(value); + JSONFPlayer player = data.get(value); - if (player == null) { - // The player never existed here, and shouldn't persist - invalidList.add(value); - continue; - } + if (player == null) { + // The player never existed here, and shouldn't persist + invalidList.add(value); + continue; + } - player.setId(id); // Update the object so it knows + player.setId(id); // Update the object so it knows - data.remove(value); // Out with the old... - data.put(id, player); // And in with the new - } - } catch (Exception e) { - e.printStackTrace(); - } - if (invalidList.size() > 0) { - for (String name : invalidList) { - // Remove all the invalid names we collected - data.remove(name); - } - Bukkit.getLogger().log(Level.INFO, "While converting we found names that either don't have a UUID or aren't players and removed them from storage."); - Bukkit.getLogger().log(Level.INFO, "The following names were detected as being invalid: " + StringUtils.join(invalidList, ", ")); - } - saveCore(this.file, data, true); // Update the - // flatfile - Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID."); - } - return data; - } + data.remove(value); // Out with the old... + data.put(id, player); // And in with the new + } + } catch (Exception e) { + e.printStackTrace(); + } + if (invalidList.size() > 0) { + for (String name : invalidList) { + // Remove all the invalid names we collected + data.remove(name); + } + Bukkit.getLogger().log(Level.INFO, "While converting we found names that either don't have a UUID or aren't players and removed them from storage."); + Bukkit.getLogger().log(Level.INFO, "The following names were detected as being invalid: " + StringUtils.join(invalidList, ", ")); + } + saveCore(this.file, data, true); // Update the + // flatfile + Bukkit.getLogger().log(Level.INFO, "Done converting players.json to UUID."); + } + return data; + } - private boolean doesKeyNeedMigration(String key) { - if (!key.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { - // Not a valid UUID.. - // Valid playername, we'll mark this as one for conversion - // to UUID - return key.matches("[a-zA-Z0-9_]{2,16}"); - } - return false; - } + private boolean doesKeyNeedMigration(String key) { + if (!key.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + // Not a valid UUID.. + // Valid playername, we'll mark this as one for conversion + // to UUID + return key.matches("[a-zA-Z0-9_]{2,16}"); + } + return false; + } - private boolean isKeyInvalid(String key) { - return !key.matches("[a-zA-Z0-9_]{2,16}"); - } + private boolean isKeyInvalid(String key) { + return !key.matches("[a-zA-Z0-9_]{2,16}"); + } - @Override - public FPlayer generateFPlayer(String id) { - FPlayer player = new JSONFPlayer(id); - this.fPlayers.put(player.getId(), player); - return player; - } + @Override + public FPlayer generateFPlayer(String id) { + FPlayer player = new JSONFPlayer(id); + this.fPlayers.put(player.getId(), player); + return player; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java index af1b4e81..c96e85c9 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFaction.java @@ -4,14 +4,14 @@ import com.massivecraft.factions.zcore.persist.MemoryFaction; public class JSONFaction extends MemoryFaction { - public JSONFaction(MemoryFaction arg0) { - super(arg0); - } + public JSONFaction(MemoryFaction arg0) { + super(arg0); + } - public JSONFaction() { - } + public JSONFaction() { + } - public JSONFaction(String id) { - super(id); - } + public JSONFaction(String id) { + super(id); + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java index 89ecac94..9d79dfb8 100644 --- a/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java +++ b/src/main/java/com/massivecraft/factions/zcore/persist/json/JSONFactions.java @@ -1,253 +1,253 @@ -package com.massivecraft.factions.zcore.persist.json; - -import com.google.common.base.Function; -import com.google.common.collect.Maps; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import com.massivecraft.factions.FLocation; -import com.massivecraft.factions.Faction; -import com.massivecraft.factions.Factions; -import com.massivecraft.factions.SavageFactions; -import com.massivecraft.factions.zcore.persist.MemoryFaction; -import com.massivecraft.factions.zcore.persist.MemoryFactions; -import com.massivecraft.factions.zcore.util.DiscUtil; -import com.massivecraft.factions.zcore.util.UUIDFetcher; -import org.bukkit.Bukkit; - -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.Map.Entry; -import java.util.logging.Level; - -public class JSONFactions extends MemoryFactions { - // Info on how to persist - private final Gson gson; - private final File file; - - public JSONFactions() { - this.file = new File(SavageFactions.plugin.getDataFolder(), "factions.json"); - this.gson = SavageFactions.plugin.gson; - this.nextId = 1; - } - - public Gson getGson() { - return gson; - } - - // -------------------------------------------- // - // CONSTRUCTORS - // -------------------------------------------- // - - public File getFile() { - return file; - } - - public void forceSave() { - forceSave(true); - } - - public void forceSave(boolean sync) { - final Map entitiesThatShouldBeSaved = new HashMap<>(); - for (Faction entity : this.factions.values()) { - entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity); - } - - saveCore(file, entitiesThatShouldBeSaved, sync); - } - - private boolean saveCore(File target, Map entities, boolean sync) { - return DiscUtil.writeCatch(target, this.gson.toJson(entities), sync); - } - - public void load() { - Map factions = this.loadCore(); - if (factions == null) { - return; - } - this.factions.putAll(factions); - - super.load(); - SavageFactions.plugin.log("Loaded " + factions.size() + " Factions"); - } - - private Map loadCore() { - if (!this.file.exists()) { - return new HashMap<>(); - } - - String content = DiscUtil.readCatch(this.file); - if (content == null) { - return null; - } - - Map data = this.gson.fromJson(content, new TypeToken>() { - }.getType()); - - this.nextId = 1; - // Do we have any names that need updating in claims or invites? - - int needsUpdate = 0; - for (Entry entry : data.entrySet()) { - String id = entry.getKey(); - Faction f = entry.getValue(); - f.setId(id); - this.updateNextIdForId(id); - needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); - for (Set keys : f.getClaimOwnership().values()) { - needsUpdate += whichKeysNeedMigration(keys).size(); - } - } - - if (needsUpdate > 0) { - // We've got some converting to do! - Bukkit.getLogger().log(Level.INFO, "Factions is now updating factions.json"); - - // First we'll make a backup, because god forbid anybody heed a - // warning - File file = new File(this.file.getParentFile(), "factions.json.old"); - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - saveCore(file, data, true); - Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); - - Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + needsUpdate + " old player names to UUID. This may take a while."); - - // Update claim ownership - - for (String string : data.keySet()) { - Faction f = data.get(string); - Map> claims = f.getClaimOwnership(); - for (FLocation key : claims.keySet()) { - Set set = claims.get(key); - - Set list = whichKeysNeedMigration(set); - - if (list.size() > 0) { - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); - try { - Map response = fetcher.call(); - for (String value : response.keySet()) { - // Let's replace their old named entry with a - // UUID key - String id = response.get(value).toString(); - set.remove(value.toLowerCase()); // Out with the - // old... - set.add(id); // And in with the new - } - } catch (Exception e) { - e.printStackTrace(); - } - claims.put(key, set); // Update - } - } - } - - // Update invites - - for (String string : data.keySet()) { - Faction f = data.get(string); - Set invites = f.getInvites(); - Set list = whichKeysNeedMigration(invites); - - if (list.size() > 0) { - UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); - try { - Map response = fetcher.call(); - for (String value : response.keySet()) { - // Let's replace their old named entry with a UUID - // key - String id = response.get(value).toString(); - invites.remove(value.toLowerCase()); // Out with the - // old... - invites.add(id); // And in with the new - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - saveCore(this.file, data, true); // Update the flatfile - Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); - } - return data; - } - - private Set whichKeysNeedMigration(Set keys) { - HashSet list = new HashSet<>(); - for (String value : keys) { - if (!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { - // Not a valid UUID.. - if (value.matches("[a-zA-Z0-9_]{2,16}")) { - // Valid playername, we'll mark this as one for conversion - // to UUID - list.add(value); - } - } - } - return list; - } - - // -------------------------------------------- // - // ID MANAGEMENT - // -------------------------------------------- // - - public String getNextId() { - while (!isIdFree(this.nextId)) { - this.nextId += 1; - } - return Integer.toString(this.nextId); - } - - public boolean isIdFree(String id) { - return !this.factions.containsKey(id); - } - - public boolean isIdFree(int id) { - return this.isIdFree(Integer.toString(id)); - } - - protected synchronized void updateNextIdForId(int id) { - if (this.nextId < id) { - this.nextId = id + 1; - } - } - - protected void updateNextIdForId(String id) { - try { - int idAsInt = Integer.parseInt(id); - this.updateNextIdForId(idAsInt); - } catch (Exception ignored) { - } - } - - @Override - public Faction generateFactionObject() { - String id = getNextId(); - Faction faction = new JSONFaction(id); - updateNextIdForId(id); - return faction; - } - - @Override - public Faction generateFactionObject(String id) { - return new JSONFaction(id); - } - - @Override - public void convertFrom(MemoryFactions old) { - this.factions.putAll(Maps.transformValues(old.factions, new Function() { - @Override - public JSONFaction apply(Faction arg0) { - return new JSONFaction((MemoryFaction) arg0); - } - })); - this.nextId = old.nextId; - forceSave(); - Factions.instance = this; - } -} +package com.massivecraft.factions.zcore.persist.json; + +import com.google.common.base.Function; +import com.google.common.collect.Maps; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.massivecraft.factions.FLocation; +import com.massivecraft.factions.Faction; +import com.massivecraft.factions.Factions; +import com.massivecraft.factions.SavageFactions; +import com.massivecraft.factions.zcore.persist.MemoryFaction; +import com.massivecraft.factions.zcore.persist.MemoryFactions; +import com.massivecraft.factions.zcore.util.DiscUtil; +import com.massivecraft.factions.zcore.util.UUIDFetcher; +import org.bukkit.Bukkit; + +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.Map.Entry; +import java.util.logging.Level; + +public class JSONFactions extends MemoryFactions { + // Info on how to persist + private final Gson gson; + private final File file; + + public JSONFactions() { + this.file = new File(SavageFactions.plugin.getDataFolder(), "factions.json"); + this.gson = SavageFactions.plugin.gson; + this.nextId = 1; + } + + public Gson getGson() { + return gson; + } + + // -------------------------------------------- // + // CONSTRUCTORS + // -------------------------------------------- // + + public File getFile() { + return file; + } + + public void forceSave() { + forceSave(true); + } + + public void forceSave(boolean sync) { + final Map entitiesThatShouldBeSaved = new HashMap<>(); + for (Faction entity : this.factions.values()) { + entitiesThatShouldBeSaved.put(entity.getId(), (JSONFaction) entity); + } + + saveCore(file, entitiesThatShouldBeSaved, sync); + } + + private boolean saveCore(File target, Map entities, boolean sync) { + return DiscUtil.writeCatch(target, this.gson.toJson(entities), sync); + } + + public void load() { + Map factions = this.loadCore(); + if (factions == null) { + return; + } + this.factions.putAll(factions); + + super.load(); + SavageFactions.plugin.log("Loaded " + factions.size() + " Factions"); + } + + private Map loadCore() { + if (!this.file.exists()) { + return new HashMap<>(); + } + + String content = DiscUtil.readCatch(this.file); + if (content == null) { + return null; + } + + Map data = this.gson.fromJson(content, new TypeToken>() { + }.getType()); + + this.nextId = 1; + // Do we have any names that need updating in claims or invites? + + int needsUpdate = 0; + for (Entry entry : data.entrySet()) { + String id = entry.getKey(); + Faction f = entry.getValue(); + f.setId(id); + this.updateNextIdForId(id); + needsUpdate += whichKeysNeedMigration(f.getInvites()).size(); + for (Set keys : f.getClaimOwnership().values()) { + needsUpdate += whichKeysNeedMigration(keys).size(); + } + } + + if (needsUpdate > 0) { + // We've got some converting to do! + Bukkit.getLogger().log(Level.INFO, "Factions is now updating factions.json"); + + // First we'll make a backup, because god forbid anybody heed a + // warning + File file = new File(this.file.getParentFile(), "factions.json.old"); + try { + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + saveCore(file, data, true); + Bukkit.getLogger().log(Level.INFO, "Backed up your old data at " + file.getAbsolutePath()); + + Bukkit.getLogger().log(Level.INFO, "Please wait while Factions converts " + needsUpdate + " old player names to UUID. This may take a while."); + + // Update claim ownership + + for (String string : data.keySet()) { + Faction f = data.get(string); + Map> claims = f.getClaimOwnership(); + for (FLocation key : claims.keySet()) { + Set set = claims.get(key); + + Set list = whichKeysNeedMigration(set); + + if (list.size() > 0) { + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String value : response.keySet()) { + // Let's replace their old named entry with a + // UUID key + String id = response.get(value).toString(); + set.remove(value.toLowerCase()); // Out with the + // old... + set.add(id); // And in with the new + } + } catch (Exception e) { + e.printStackTrace(); + } + claims.put(key, set); // Update + } + } + } + + // Update invites + + for (String string : data.keySet()) { + Faction f = data.get(string); + Set invites = f.getInvites(); + Set list = whichKeysNeedMigration(invites); + + if (list.size() > 0) { + UUIDFetcher fetcher = new UUIDFetcher(new ArrayList<>(list)); + try { + Map response = fetcher.call(); + for (String value : response.keySet()) { + // Let's replace their old named entry with a UUID + // key + String id = response.get(value).toString(); + invites.remove(value.toLowerCase()); // Out with the + // old... + invites.add(id); // And in with the new + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + saveCore(this.file, data, true); // Update the flatfile + Bukkit.getLogger().log(Level.INFO, "Done converting factions.json to UUID."); + } + return data; + } + + private Set whichKeysNeedMigration(Set keys) { + HashSet list = new HashSet<>(); + for (String value : keys) { + if (!value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { + // Not a valid UUID.. + if (value.matches("[a-zA-Z0-9_]{2,16}")) { + // Valid playername, we'll mark this as one for conversion + // to UUID + list.add(value); + } + } + } + return list; + } + + // -------------------------------------------- // + // ID MANAGEMENT + // -------------------------------------------- // + + public String getNextId() { + while (!isIdFree(this.nextId)) { + this.nextId += 1; + } + return Integer.toString(this.nextId); + } + + public boolean isIdFree(String id) { + return !this.factions.containsKey(id); + } + + public boolean isIdFree(int id) { + return this.isIdFree(Integer.toString(id)); + } + + protected synchronized void updateNextIdForId(int id) { + if (this.nextId < id) { + this.nextId = id + 1; + } + } + + protected void updateNextIdForId(String id) { + try { + int idAsInt = Integer.parseInt(id); + this.updateNextIdForId(idAsInt); + } catch (Exception ignored) { + } + } + + @Override + public Faction generateFactionObject() { + String id = getNextId(); + Faction faction = new JSONFaction(id); + updateNextIdForId(id); + return faction; + } + + @Override + public Faction generateFactionObject(String id) { + return new JSONFaction(id); + } + + @Override + public void convertFrom(MemoryFactions old) { + this.factions.putAll(Maps.transformValues(old.factions, new Function() { + @Override + public JSONFaction apply(Faction arg0) { + return new JSONFaction((MemoryFaction) arg0); + } + })); + this.nextId = old.nextId; + forceSave(); + Factions.instance = this; + } +} diff --git a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java index eaf37257..fcf2e7ca 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/DiscUtil.java @@ -1,121 +1,121 @@ -package com.massivecraft.factions.zcore.util; - -import com.massivecraft.factions.SavageFactions; -import org.bukkit.Bukkit; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -public class DiscUtil { - - // -------------------------------------------- // - // CONSTANTS - // -------------------------------------------- // - - private final static String UTF8 = "UTF-8"; - - // -------------------------------------------- // - // BYTE - // -------------------------------------------- // - private static HashMap locks = new HashMap<>(); - - public static byte[] readBytes(File file) throws IOException { - int length = (int) file.length(); - byte[] output = new byte[length]; - InputStream in = new FileInputStream(file); - int offset = 0; - while (offset < length) { - offset += in.read(output, offset, (length - offset)); - } - in.close(); - return output; - } - - // -------------------------------------------- // - // STRING - // -------------------------------------------- // - - public static void writeBytes(File file, byte[] bytes) throws IOException { - FileOutputStream out = new FileOutputStream(file); - out.write(bytes); - out.close(); - } - - public static void write(File file, String content) throws IOException { - writeBytes(file, utf8(content)); - } - - // -------------------------------------------- // - // CATCH - // -------------------------------------------- // - - public static String read(File file) throws IOException { - return utf8(readBytes(file)); - } - - public static boolean writeCatch(final File file, final String content, boolean sync) { - String name = file.getName(); - final Lock lock; - - // Create lock for each file if there isn't already one. - if (locks.containsKey(name)) { - lock = locks.get(name); - } else { - ReadWriteLock rwl = new ReentrantReadWriteLock(); - lock = rwl.writeLock(); - locks.put(name, lock); - } - - if (sync) { - lock.lock(); - try { - write(file, content); - } catch (IOException e) { - e.printStackTrace(); - } finally { - lock.unlock(); - } - } else { - Bukkit.getScheduler().runTaskAsynchronously(SavageFactions.plugin, new Runnable() { - @Override - public void run() { - lock.lock(); - try { - write(file, content); - } catch (IOException e) { - e.printStackTrace(); - } finally { - lock.unlock(); - } - } - }); - } - - return true; // don't really care but for some reason this is a boolean. - } - - public static String readCatch(File file) { - try { - return read(file); - } catch (IOException e) { - return null; - } - } - - // -------------------------------------------- // - // UTF8 ENCODE AND DECODE - // -------------------------------------------- // - - public static byte[] utf8(String string) { - return string.getBytes(StandardCharsets.UTF_8); - } - - public static String utf8(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - +package com.massivecraft.factions.zcore.util; + +import com.massivecraft.factions.SavageFactions; +import org.bukkit.Bukkit; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class DiscUtil { + + // -------------------------------------------- // + // CONSTANTS + // -------------------------------------------- // + + private final static String UTF8 = "UTF-8"; + + // -------------------------------------------- // + // BYTE + // -------------------------------------------- // + private static HashMap locks = new HashMap<>(); + + public static byte[] readBytes(File file) throws IOException { + int length = (int) file.length(); + byte[] output = new byte[length]; + InputStream in = new FileInputStream(file); + int offset = 0; + while (offset < length) { + offset += in.read(output, offset, (length - offset)); + } + in.close(); + return output; + } + + // -------------------------------------------- // + // STRING + // -------------------------------------------- // + + public static void writeBytes(File file, byte[] bytes) throws IOException { + FileOutputStream out = new FileOutputStream(file); + out.write(bytes); + out.close(); + } + + public static void write(File file, String content) throws IOException { + writeBytes(file, utf8(content)); + } + + // -------------------------------------------- // + // CATCH + // -------------------------------------------- // + + public static String read(File file) throws IOException { + return utf8(readBytes(file)); + } + + public static boolean writeCatch(final File file, final String content, boolean sync) { + String name = file.getName(); + final Lock lock; + + // Create lock for each file if there isn't already one. + if (locks.containsKey(name)) { + lock = locks.get(name); + } else { + ReadWriteLock rwl = new ReentrantReadWriteLock(); + lock = rwl.writeLock(); + locks.put(name, lock); + } + + if (sync) { + lock.lock(); + try { + write(file, content); + } catch (IOException e) { + e.printStackTrace(); + } finally { + lock.unlock(); + } + } else { + Bukkit.getScheduler().runTaskAsynchronously(SavageFactions.plugin, new Runnable() { + @Override + public void run() { + lock.lock(); + try { + write(file, content); + } catch (IOException e) { + e.printStackTrace(); + } finally { + lock.unlock(); + } + } + }); + } + + return true; // don't really care but for some reason this is a boolean. + } + + public static String readCatch(File file) { + try { + return read(file); + } catch (IOException e) { + return null; + } + } + + // -------------------------------------------- // + // UTF8 ENCODE AND DECODE + // -------------------------------------------- // + + public static byte[] utf8(String string) { + return string.getBytes(StandardCharsets.UTF_8); + } + + public static String utf8(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } + } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java index 3d8a8933..5d457631 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/PermUtil.java @@ -10,65 +10,65 @@ import java.util.Map.Entry; public class PermUtil { - public Map permissionDescriptions = new HashMap<>(); + public Map permissionDescriptions = new HashMap<>(); - protected MPlugin p; + protected MPlugin p; - public PermUtil(MPlugin p) { - this.p = p; - this.setup(); - } + public PermUtil(MPlugin p) { + this.p = p; + this.setup(); + } - public String getForbiddenMessage(String perm) { - return p.txt.parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm)); - } + public String getForbiddenMessage(String perm) { + return p.txt.parse(TL.GENERIC_NOPERMISSION.toString(), getPermissionDescription(perm)); + } - /** - * This method hooks into all permission plugins we are supporting - */ - public final void setup() { - for (Permission permission : p.getDescription().getPermissions()) { - //plugin.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); - this.permissionDescriptions.put(permission.getName(), permission.getDescription()); - } - } + /** + * This method hooks into all permission plugins we are supporting + */ + public final void setup() { + for (Permission permission : p.getDescription().getPermissions()) { + //plugin.log("\""+permission.getName()+"\" = \""+permission.getDescription()+"\""); + this.permissionDescriptions.put(permission.getName(), permission.getDescription()); + } + } - public String getPermissionDescription(String perm) { - String desc = permissionDescriptions.get(perm); + public String getPermissionDescription(String perm) { + String desc = permissionDescriptions.get(perm); - return desc != null ? desc : TL.GENERIC_DOTHAT.toString(); - } + return desc != null ? desc : TL.GENERIC_DOTHAT.toString(); + } - /** - * This method tests if me has a certain permission and returns true if me has. Otherwise false - */ - public boolean has(CommandSender me, String perm) { - return me != null && me.hasPermission(perm); - } + /** + * This method tests if me has a certain permission and returns true if me has. Otherwise false + */ + public boolean has(CommandSender me, String perm) { + return me != null && me.hasPermission(perm); + } - public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { - if (has(me, perm)) { - return true; - } else if (informSenderIfNot && me != null) { - me.sendMessage(this.getForbiddenMessage(perm)); - } - return false; - } + public boolean has(CommandSender me, String perm, boolean informSenderIfNot) { + if (has(me, perm)) { + return true; + } else if (informSenderIfNot && me != null) { + me.sendMessage(this.getForbiddenMessage(perm)); + } + return false; + } - public T pickFirstVal(CommandSender me, Map perm2val) { - if (perm2val == null) { - return null; - } - T ret = null; + public T pickFirstVal(CommandSender me, Map perm2val) { + if (perm2val == null) { + return null; + } + T ret = null; - for (Entry entry : perm2val.entrySet()) { - ret = entry.getValue(); - if (has(me, entry.getKey())) { - break; - } - } + for (Entry entry : perm2val.entrySet()) { + ret = entry.getValue(); + if (has(me, entry.getKey())) { + break; + } + } - return ret; - } + return ret; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java index 65042cb2..21d3027a 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/Persist.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/Persist.java @@ -10,144 +10,144 @@ import java.util.logging.Level; public class Persist { - private MPlugin p; + private MPlugin p; - public Persist(MPlugin p) { - this.p = p; - } + public Persist(MPlugin p) { + this.p = p; + } - // ------------------------------------------------------------ // - // GET NAME - What should we call this type of object? - // ------------------------------------------------------------ // + // ------------------------------------------------------------ // + // GET NAME - What should we call this type of object? + // ------------------------------------------------------------ // - public static String getName(Class clazz) { - return clazz.getSimpleName().toLowerCase(); - } + public static String getName(Class clazz) { + return clazz.getSimpleName().toLowerCase(); + } - public static String getName(Object o) { - return getName(o.getClass()); - } + public static String getName(Object o) { + return getName(o.getClass()); + } - public static String getName(Type type) { - return getName(type.getClass()); - } + public static String getName(Type type) { + return getName(type.getClass()); + } - // ------------------------------------------------------------ // - // GET FILE - In which file would we like to store this object? - // ------------------------------------------------------------ // + // ------------------------------------------------------------ // + // GET FILE - In which file would we like to store this object? + // ------------------------------------------------------------ // - public File getFile(String name) { - return new File(p.getDataFolder(), name + ".json"); - } + public File getFile(String name) { + return new File(p.getDataFolder(), name + ".json"); + } - public File getFile(Class clazz) { - return getFile(getName(clazz)); - } + public File getFile(Class clazz) { + return getFile(getName(clazz)); + } - public File getFile(Object obj) { - return getFile(getName(obj)); - } + public File getFile(Object obj) { + return getFile(getName(obj)); + } - public File getFile(Type type) { - return getFile(getName(type)); - } + public File getFile(Type type) { + return getFile(getName(type)); + } - // NICE WRAPPERS + // NICE WRAPPERS - public T loadOrSaveDefault(T def, Class clazz) { - return loadOrSaveDefault(def, clazz, getFile(clazz)); - } + public T loadOrSaveDefault(T def, Class clazz) { + return loadOrSaveDefault(def, clazz, getFile(clazz)); + } - public T loadOrSaveDefault(T def, Class clazz, String name) { - return loadOrSaveDefault(def, clazz, getFile(name)); - } + public T loadOrSaveDefault(T def, Class clazz, String name) { + return loadOrSaveDefault(def, clazz, getFile(name)); + } - public T loadOrSaveDefault(T def, Class clazz, File file) { - if (!file.exists()) { - p.log("Creating default: " + file); - this.save(def, file); - return def; - } + public T loadOrSaveDefault(T def, Class clazz, File file) { + if (!file.exists()) { + p.log("Creating default: " + file); + this.save(def, file); + return def; + } - T loaded = this.load(clazz, file); + T loaded = this.load(clazz, file); - if (loaded == null) { - p.log(Level.WARNING, "Using default as I failed to load: " + file); + if (loaded == null) { + p.log(Level.WARNING, "Using default as I failed to load: " + file); - // backup bad file, so user can attempt to recover their changes from it - File backup = new File(file.getPath() + "_bad"); - if (backup.exists()) { - backup.delete(); - } - p.log(Level.WARNING, "Backing up copy of bad file to: " + backup); - file.renameTo(backup); + // backup bad file, so user can attempt to recover their changes from it + File backup = new File(file.getPath() + "_bad"); + if (backup.exists()) { + backup.delete(); + } + p.log(Level.WARNING, "Backing up copy of bad file to: " + backup); + file.renameTo(backup); - return def; - } + return def; + } - return loaded; - } + return loaded; + } - // SAVE + // SAVE - public boolean save(Object instance) { - return save(instance, getFile(instance)); - } + public boolean save(Object instance) { + return save(instance, getFile(instance)); + } - public boolean save(Object instance, String name) { - return save(instance, getFile(name)); - } + public boolean save(Object instance, String name) { + return save(instance, getFile(name)); + } - public boolean save(Object instance, File file) { - return DiscUtil.writeCatch(file, p.gson.toJson(instance), true); - } + public boolean save(Object instance, File file) { + return DiscUtil.writeCatch(file, p.gson.toJson(instance), true); + } - // LOAD BY CLASS + // LOAD BY CLASS - public T load(Class clazz) { - return load(clazz, getFile(clazz)); - } + public T load(Class clazz) { + return load(clazz, getFile(clazz)); + } - public T load(Class clazz, String name) { - return load(clazz, getFile(name)); - } + public T load(Class clazz, String name) { + return load(clazz, getFile(name)); + } - public T load(Class clazz, File file) { - String content = DiscUtil.readCatch(file); - if (content == null) { - return null; - } + public T load(Class clazz, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } - try { - return p.gson.fromJson(content, clazz); - } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely - p.log(Level.WARNING, ex.getMessage()); - } + try { + return p.gson.fromJson(content, clazz); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + p.log(Level.WARNING, ex.getMessage()); + } - return null; - } + return null; + } - // LOAD BY TYPE - @SuppressWarnings("unchecked") - public T load(Type typeOfT, String name) { - return (T) load(typeOfT, getFile(name)); - } + // LOAD BY TYPE + @SuppressWarnings("unchecked") + public T load(Type typeOfT, String name) { + return (T) load(typeOfT, getFile(name)); + } - @SuppressWarnings("unchecked") - public T load(Type typeOfT, File file) { - String content = DiscUtil.readCatch(file); - if (content == null) { - return null; - } + @SuppressWarnings("unchecked") + public T load(Type typeOfT, File file) { + String content = DiscUtil.readCatch(file); + if (content == null) { + return null; + } - try { - return (T) p.gson.fromJson(content, typeOfT); - } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely - p.log(Level.WARNING, ex.getMessage()); - } + try { + return (T) p.gson.fromJson(content, typeOfT); + } catch (Exception ex) { // output the error message rather than full stack trace; error parsing the file, most likely + p.log(Level.WARNING, ex.getMessage()); + } - return null; - } + return null; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java index 1f9ffe84..cacba74b 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/SmokeUtil.java @@ -1,82 +1,82 @@ -package com.massivecraft.factions.zcore.util; - -import org.bukkit.Effect; -import org.bukkit.Location; - -import java.util.Collection; -import java.util.Random; - -// http://mc.kev009.com/Protocol -// ----------------------------- -// Smoke Directions -// ----------------------------- -// Direction ID Direction -// 0 South - East -// 1 South -// 2 South - West -// 3 East -// 4 (Up or middle ?) -// 5 West -// 6 North - East -// 7 North -// 8 North - West -//----------------------------- - -public class SmokeUtil { - - public static Random random = new Random(); - - // -------------------------------------------- // - // Spawn once - // -------------------------------------------- // - - // Single ======== - public static void spawnSingle(Location location, int direction) { - if (location == null) { - return; - } - location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); - } - - public static void spawnSingle(Location location) { - spawnSingle(location, 4); - } - - public static void spawnSingleRandom(Location location) { - spawnSingle(location, random.nextInt(9)); - } - - // Simple Cloud ======== - public static void spawnCloudSimple(Location location) { - for (int i = 0; i <= 8; i++) { - spawnSingle(location, i); - } - } - - public static void spawnCloudSimple(Collection locations) { - for (Location location : locations) { - spawnCloudSimple(location); - } - } - - // Random Cloud ======== - public static void spawnCloudRandom(Location location, float thickness) { - int singles = (int) Math.floor(thickness * 9); - for (int i = 0; i < singles; i++) { - spawnSingleRandom(location.clone()); - } - } - - public static void spawnCloudRandom(Collection locations, float thickness) { - for (Location location : locations) { - spawnCloudRandom(location, thickness); - } - } - - // -------------------------------------------- // - // Attach continuous effects to or locations - // -------------------------------------------- // - - // TODO - -} +package com.massivecraft.factions.zcore.util; + +import org.bukkit.Effect; +import org.bukkit.Location; + +import java.util.Collection; +import java.util.Random; + +// http://mc.kev009.com/Protocol +// ----------------------------- +// Smoke Directions +// ----------------------------- +// Direction ID Direction +// 0 South - East +// 1 South +// 2 South - West +// 3 East +// 4 (Up or middle ?) +// 5 West +// 6 North - East +// 7 North +// 8 North - West +//----------------------------- + +public class SmokeUtil { + + public static Random random = new Random(); + + // -------------------------------------------- // + // Spawn once + // -------------------------------------------- // + + // Single ======== + public static void spawnSingle(Location location, int direction) { + if (location == null) { + return; + } + location.getWorld().playEffect(location.clone(), Effect.SMOKE, direction); + } + + public static void spawnSingle(Location location) { + spawnSingle(location, 4); + } + + public static void spawnSingleRandom(Location location) { + spawnSingle(location, random.nextInt(9)); + } + + // Simple Cloud ======== + public static void spawnCloudSimple(Location location) { + for (int i = 0; i <= 8; i++) { + spawnSingle(location, i); + } + } + + public static void spawnCloudSimple(Collection locations) { + for (Location location : locations) { + spawnCloudSimple(location); + } + } + + // Random Cloud ======== + public static void spawnCloudRandom(Location location, float thickness) { + int singles = (int) Math.floor(thickness * 9); + for (int i = 0; i < singles; i++) { + spawnSingleRandom(location.clone()); + } + } + + public static void spawnCloudRandom(Collection locations, float thickness) { + for (Location location : locations) { + spawnCloudRandom(location, thickness); + } + } + + // -------------------------------------------- // + // Attach continuous effects to or locations + // -------------------------------------------- // + + // TODO + +} 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 8edff483..202c3e83 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TL.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TL.java @@ -26,1018 +26,1018 @@ import java.text.SimpleDateFormat; * changes. */ public enum TL { - /** - * Translation meta - */ - _AUTHOR("misc"), - _RESPONSIBLE("misc"), - _LANGUAGE("English"), - _ENCODING("UTF-8"), - _LOCALE("en_US"), - _REQUIRESUNICODE("false"), - _DEFAULT("true"), - _STATE("complete"), //incomplete, limited, partial, majority, complete - - /** - * Localised translation meta - */ - _LOCAL_AUTHOR("misc"), - _LOCAL_RESPONSIBLE("misc"), - _LOCAL_LANGUAGE("English"), - _LOCAL_REGION("US"), - _LOCAL_STATE("complete"), //And this is the English version. It's not ever going to be not complete. - - /** - * Command translations - */ - - /** - * Messsges for /f help - */ - COMMAND_HELP_NEXTCREATE("Learn how to create a faction on the next page."), - COMMAND_HELP_INVITATIONS("command.help.invitations", "You might want to close it and use invitations:"), - COMMAND_HELP_HOME("And don't forget to set your home:"), - COMMAND_HELP_404("&c&l» &7This page does &cnot &7exist"), - COMMAND_HELP_BANK_1("Your faction has a bank which is used to pay for certain"), //Move to last /f help page - COMMAND_HELP_BANK_2("things, so it will need to have money deposited into it."), //Move to last /f help page - COMMAND_HELP_BANK_3("To learn more, use the money command."), //Move to last /f help page - COMMAND_HELP_PLAYERTITLES("Player titles are just for fun. No rules connected to them."), //Move to last /f help page - COMMAND_HELP_OWNERSHIP_1("Claimed land with ownership set is further protected so"), //Move to last /f help page - COMMAND_HELP_OWNERSHIP_2("that only the owner(s), faction admin, and possibly the"), //Move to last /f help page - COMMAND_HELP_OWNERSHIP_3("faction moderators have full access."), //Move to last /f help page - COMMAND_HELP_RELATIONS_1("Set the relation you WISH to have with another faction."), //Move to last /f help page - COMMAND_HELP_RELATIONS_2("Your default relation with other factions will be neutral."), //Move to last /f help page - COMMAND_HELP_RELATIONS_3("If BOTH factions choose \"ally\" you will be allies."), //Move to last /f help page - COMMAND_HELP_RELATIONS_4("If ONE faction chooses \"enemy\" you will be enemies."), //Move to last /f help page - COMMAND_HELP_RELATIONS_5("You can never hurt members or allies."), //Move to last /f help page - COMMAND_HELP_RELATIONS_6("You can not hurt neutrals in their own territory."), //Move to last /f help page - COMMAND_HELP_RELATIONS_7("You can always hurt enemies and players without faction."), //Move to last /f help page - COMMAND_HELP_RELATIONS_8(""), - COMMAND_HELP_RELATIONS_9("Damage from enemies is reduced in your own territory."), //Move to last /f help page - COMMAND_HELP_RELATIONS_10("When you die you lose power. It is restored over time."), //Move to last /f help page - COMMAND_HELP_RELATIONS_11("The power of a faction is the sum of all member power."), //Move to last /f help page - COMMAND_HELP_RELATIONS_12("The power of a faction determines how much land it can hold."), //Move to last /f help page - COMMAND_HELP_RELATIONS_13("You can claim land from factions with too little power."), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_1("Only faction members can build and destroy in their own"), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_2("territory. Usage of the following items is also restricted:"), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_3("Door, Chest, Furnace, Dispenser, Diode."), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_4(""), - COMMAND_HELP_PERMISSIONS_5("Make sure to put pressure plates in front of doors for your"), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_6("guest visitors. Otherwise they can't get through. You can"), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_7("also use this to create member only areas."), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_8("As dispensers are protected, you can create traps without"), //Move to last /f help page - COMMAND_HELP_PERMISSIONS_9("worrying about those arrows getting stolen."), //Move to last /f help page - COMMAND_HELP_ADMIN_1("&a&l» &a/f claim safezone \n &7claim land for the Safe Zone"), - COMMAND_HELP_ADMIN_2("&a&l» &a/f claim warzone \n &7claim land for the War Zone"), - COMMAND_HELP_ADMIN_3("&a&l» &a/f autoclaim [safezone|warzone] \n &7take a guess"), - COMMAND_HELP_MOAR_1("Finally some commands for the server admins:"), - COMMAND_HELP_MOAR_2("More commands for server admins:"), - COMMAND_HELP_MOAR_3("Even more commands for server admins:"), - COMMAND_HELP_DESCRIPTION("\n &a&l» &7Display a &ahelp &7page"), - - COMMAND_NEAR_DESCRIPTION("Get nearby faction players in a radius."), - COMMAND_NEAR_DISABLED_MSG("&cThis command is disabled!"), - COMMAND_NEAR_FORMAT("{playername} &c({distance}m)"), - COMMAND_NEAR_USE_MSG("&cFaction members nearby"), - - /** - * Messsges for Faction Admins/Mods - */ - - COMMAND_UPGRADES_DESCRIPTION("&cOpen the Upgrades Menu"), - - COMMAND_ADMIN_NOTMEMBER("&c&l[!] &7%1$s &cis not a member in your faction."), - COMMAND_ADMIN_NOTADMIN("&c&l[!] &cYou are not the faction admin."), - COMMAND_ADMIN_TARGETSELF("'&c&l[!] &cThe target player musn''t be yourself."), - COMMAND_ADMIN_DEMOTES("&c&l[!] &cYou have demoted &7%1$s &cfrom the position of faction admin."), - COMMAND_ADMIN_DEMOTED("&c&l[!] &cYou have been demoted from the position of faction admin by &7%1$s&c"), - COMMAND_ADMIN_PROMOTES("&e&l[!] &eYou have promoted &6%1$s &eto the position of faction admin."), - COMMAND_ADMIN_PROMOTED("&e&l[!] &6%1$s &egave &6%2$s ðe leadership of &6%3$s&e."), - COMMAND_ADMIN_DESCRIPTION("Hand over your admin rights"), - COMMAND_ADMIN_NOMEMBERS("&e&l[!] &cNo one else to promote, please disband faction."), - - COMMAND_AHOME_DESCRIPTION("Send a player to their f home no matter what."), - COMMAND_AHOME_NOHOME("%1$s doesn't have an f home."), - COMMAND_AHOME_SUCCESS("$1%s was sent to their f home."), - COMMAND_AHOME_OFFLINE("%1$s is offline."), - COMMAND_AHOME_TARGET("You were sent to your f home."), - - COMMAND_ANNOUNCE_DESCRIPTION("Announce a message to players in faction."), - - COMMAND_FREECAM_ENEMYINRADIUS("Freecam disabled, An enemy is closeby!"), - COMMAND_FREECAM_OUTSIDEFLIGHT("Please dont leave the flight radius!"), - COMMAND_FREECAM_ENABLED("Freecam is now enabled!"), - COMMAND_FREECAM_DISABLED("Freecam is now disabled"), - COMMAND_FREECAM_DESCRIPTION("Go into spectator mode"), - - - COMMAND_AUTOCLAIM_ENABLED("&c&l[!] &7Now &cauto-claiming&7 land for %1$s."), - COMMAND_AUTOCLAIM_DISABLED("&c&l[!] Auto-claiming&7 of land is now &cdisabled."), - COMMAND_AUTOCLAIM_REQUIREDRANK("&c&l[!] &7You must be &c%1$s&7 to claim land."), - COMMAND_AUTOCLAIM_OTHERFACTION("&c&l[!]&7 You &ccan't &7claim land for &c%1$s&7."), - COMMAND_AUTOCLAIM_DESCRIPTION("Auto-claim land as you walk around"), - - COMMAND_AUTOHELP_HELPFOR("Help for command \""), - - COMMAND_BAN_DESCRIPTION("Ban players from joining your Faction."), - COMMAND_BAN_TARGET("&c&l[!] &7You were &cbanned &7from &c%1$s"), // banned player perspective - COMMAND_BAN_BANNED("&c&l[!] &7%1$s &cbanned &7%2$s"), - COMMAND_BAN_SELF("&c&l[!] &7You may &cnot &7ban &cyourself&7."), - COMMAND_BAN_INSUFFICIENTRANK("&c&l[!] &7Your &crank &7is too low to&c ban &7%1$s"), - COMMAND_BAN_ALREADYBANNED("&c&l[!] &7This player is &calready banned&7!"), - - COMMAND_BANLIST_DESCRIPTION("View a Faction's ban list"), - COMMAND_BANLIST_HEADER("&c&l[!] &7There are &c%d&7 bans for &c%s"), - COMMAND_BANLIST_ENTRY("&7%d. &c%s &r&7// &c%s &r&7// &c%s"), - COMMAND_BANLIST_NOFACTION("&c&l[!] &7You are &cnot &7in a Faction."), - COMMAND_BANLIST_INVALID("&c&l[!] &7The faction &c%s &7does not exist"), - - COMMAND_BOOM_PEACEFULONLY("&c&l[!] &7This command is &conly &7usable by factions which are &cspecifically &7designated as &cpeaceful&7."), - COMMAND_BOOM_TOTOGGLE("to toggle explosions"), - COMMAND_BOOM_FORTOGGLE("for toggling explosions"), - COMMAND_BOOM_ENABLED("&c&l[!] &c%1$s&7 has&c %2$s&7 explosions in your faction's territory."), - COMMAND_BOOM_DESCRIPTION("Toggle explosions (peaceful factions only)"), - - - COMMAND_BYPASS_ENABLE("&e&l[!] &eYou have enabled admin bypass mode. You will be able to build or destroy anywhere."), - COMMAND_BYPASS_ENABLELOG(" has ENABLED admin bypass mode."), - COMMAND_BYPASS_DISABLE("&c&l[!] &cYou have disabled admin bypass mode."), - COMMAND_BYPASS_DISABLELOG(" has DISABLED admin bypass mode."), - COMMAND_BYPASS_DESCRIPTION("Enable admin bypass mode"), - - COMMAND_BANNER_DESCRIPTION("Turn a held banner into a war banner"), - COMMAND_BANNER_NOTENOUGHMONEY("&c&l[!] &7You do&c not&7 have enough money"), - COMMAND_BANNER_MONEYTAKE("&c&l[!] $&c{amount} &7has been taken from your account."), - COMMAND_BANNER_SUCCESS("&c&l[!] &7You have created a &c&lWarBanner!"), - COMMAND_BANNER_DISABLED("&c&l[!] &7Buying&c warbanners&7 is &cdisabled!"), - - COMMAND_TPBANNER_NOTSET("&c&l[!] &7Your faction &cdoes not &7have a &c&lWarBanner &7placed!"), - COMMAND_TPBANNER_SUCCESS("&c&l[!] &cTeleporting &7to your factions's &c&lWarBanner"), - COMMAND_TPBANNER_DESCRIPTION("Teleport to your faction banner"), - - - COMMAND_CHAT_DISABLED("&c&l[!] &7The built in chat channels are &cdisabled &7on this server."), - COMMAND_CHAT_INVALIDMODE("&c&l[!] &cUnrecognised &7chat mode. Please enter either '&da&7','&af&7','&6m&7' or '&fp&7'"), - COMMAND_CHAT_DESCRIPTION("Change chat mode"), - - COMMAND_CHAT_MODE_PUBLIC("&c&l[!] &fPublic &7chat mode."), - COMMAND_CHAT_MODE_ALLIANCE("&c&l[!] &dAlliance &7only chat mode."), - COMMAND_CHAT_MODE_TRUCE("&c&l[!] &5Truce &7only chat mode."), - COMMAND_CHAT_MODE_FACTION("&c&l[!] &aFaction&7 only chat mode."), - COMMAND_CHAT_MODE_MOD("&c&l[!] &dMod &7only chat mode."), - COMMAND_CHAT_MOD_ONLY("&c&l[!] &7Only Mods can talk through this chat mode."), - - COMMAND_CHATSPY_ENABLE("&c&l[!] &7You have &cenabled &7chat spying mode."), - COMMAND_CHATSPY_ENABLELOG(" has ENABLED chat spying mode."), - COMMAND_CHATSPY_DISABLE("&c&l[!] &7You have &cdisabled &7chat spying mode."), - COMMAND_CHATSPY_DISABLELOG(" has DISABLED chat spying mode."), - COMMAND_CHATSPY_DESCRIPTION("Enable admin chat spy mode"), - - COMMAND_CLAIM_INVALIDRADIUS("&c&l[!]&7 If you specify a &cradius&7, it must be at least &c1&7."), - COMMAND_CLAIM_DENIED("&c&l[!]&7 You &cdo not &7have &cpermission&7 to &cclaim&7 in a radius."), - COMMAND_CLAIM_DESCRIPTION("Claim land from where you are standing"), - - COMMAND_CLAIMLINE_INVALIDRADIUS("&c&l[!]&7 If you &cspecify&7 a distance, it must be at least &c1&7."), - COMMAND_CLAIMLINE_DENIED("&c&l[!]&7 You &cdo not &7have&c permission&7 to claim in a line."), - COMMAND_CLAIMLINE_DESCRIPTION("Claim land in a straight line."), - COMMAND_CLAIMLINE_ABOVEMAX("&c&l[!]&7 The &cmaximum&7 limit for claim line is &c%s&7."), - COMMAND_CLAIMLINE_NOTVALID("&c&l[!]&7 &c%s&7 is not a &ccardinal &7direction. You may use &cnorth&7, &ceast&7, &csouth &7or &cwest&7."), - - COMMAND_CONFIG_NOEXIST("&c&l[!]&7 No configuration setting \"&c%1$s&7\" exists."), - COMMAND_CONFIG_SET_TRUE("\" option set to true (enabled)."), - COMMAND_CONFIG_SET_FALSE("\" option set to false (disabled)."), - COMMAND_CONFIG_OPTIONSET("\" option set to "), - COMMAND_CONFIG_COLOURSET("\" color option set to \""), - COMMAND_CONFIG_INTREQUIRED("Cannot set \"%1$s\": An integer (whole number) value required."), - COMMAND_CONFIG_LONGREQUIRED("Cannot set \"%1$s\": A long integer (whole number) value required."), - COMMAND_CONFIG_DOUBLEREQUIRED("Cannot set \"%1$s\": A double (numeric) value required."), - COMMAND_CONFIG_FLOATREQUIRED("Cannot set \"%1$s\": A float (numeric) value required."), - COMMAND_CONFIG_INVALID_COLOUR("Cannot set \"%1$s\": \"%2$s\" is not a valid color."), - COMMAND_CONFIG_INVALID_COLLECTION("\"%1$s\" is not a data collection type which can be modified with this command."), - COMMAND_CONFIG_INVALID_MATERIAL("Cannot change \"%1$s\" set: \"%2$s\" is not a valid material."), - COMMAND_CONFIG_INVALID_TYPESET("\"%1$s\" is not a data type set which can be modified with this command."), - COMMAND_CONFIG_MATERIAL_ADDED("\"%1$s\" set: Material \"%2$s\" added."), - COMMAND_CONFIG_MATERIAL_REMOVED("\"%1$s\" set: Material \"%2$s\" removed."), - COMMAND_CONFIG_SET_ADDED("\"%1$s\" set: \"%2$s\" added."), - COMMAND_CONFIG_SET_REMOVED("\"%1$s\" set: \"%2$s\" removed."), - COMMAND_CONFIG_LOG(" (Command was run by %1$s.)"), - COMMAND_CONFIG_ERROR_SETTING("Error setting configuration setting \"%1$s\" to \"%2$s\"."), - COMMAND_CONFIG_ERROR_MATCHING("Configuration setting \"%1$s\" couldn't be matched, though it should be... please report this error."), - COMMAND_CONFIG_ERROR_TYPE("'%1$s' is of type '%2$s', which cannot be modified with this command."), - COMMAND_CONFIG_DESCRIPTION("Change a conf.json setting"), - - COMMAND_CONVERT_BACKEND_RUNNING("&c&l[!]&7 Already running that backend."), - COMMAND_CONVERT_BACKEND_INVALID("&c&l[!]&7 Invalid backend"), - COMMAND_CONVERT_DESCRIPTION("Convert the plugin backend"), - - COMMAND_COORDS_MESSAGE("&c&l[!] &7{player}&7's coords are &c{x}&7,&c{y}&7,&c{z}&7 in &c{world}"), - COMMAND_COORDS_DESCRIPTION("broadcast your coords to your faction"), - - COMMAND_CHECKPOINT_DISABLED("&c&l[!]&7 You &ccannot&7 use checkpoint while its&c disabled&7!"), - COMMAND_CHECKPOINT_SET("&c&l[!]&7 You have &cset&7 the &cfaction checkpoint&7 at your &cLocation&7."), - COMMAND_CHECKPOINT_GO("&c&l[!]&7 &cTeleporting&7 to &cfaction checkpoint"), - COMMAND_CHECKPOINT_INVALIDLOCATION("&c&l[!]&7 &cInvalid Location!&7 You can &cset&7 checkpoints in &cyour claims&7 or &2wilderness&7."), - COMMAND_CHECKPOINT_NOT_SET("&c&l[!]&7 You have to &cset &7the &cfaction checkpoint&7 first."), - COMMAND_CHECKPOINT_CLAIMED("&c&l[!]&7 Your current &cfaction checkpoint&7 is claimed, set a &cnew &7one!"), - COMMAND_CHECKPOINT_DESCRIPTION("Set or go to your faction checkpoint!"), - - COMMAND_CREATE_MUSTLEAVE("&c&l[!]&7 You must &cleave &7your &ccurrent faction &7first."), - COMMAND_CREATE_INUSE("&c&l[!]&7 That tag is &calready &7in use."), - COMMAND_CREATE_TOCREATE("to create a new faction"), - COMMAND_CREATE_FORCREATE("for creating a new faction"), - COMMAND_CREATE_ERROR("&c&l[!]&7 There was an &cinternal error&7 while trying to create your faction. &cPlease try again&7."), - COMMAND_CREATE_CREATED("&c&l[!]&7 &c%1$s &7created a new faction &c&l%2$s"), - COMMAND_CREATE_YOUSHOULD("&c&l[!]&7 You should now: &c%1$s"), - COMMAND_CREATE_CREATEDLOG(" created a new faction: "), - COMMAND_CREATE_DESCRIPTION("Create a new faction"), - - COMMAND_DEINVITE_CANDEINVITE("&c&l[!]&7 Players you can &cdeinvite: "), - COMMAND_DEINVITE_CLICKTODEINVITE("&c&l[!]&7 Click to &crevoke&7 invite for &c%1$s"), - COMMAND_DEINVITE_ALREADYMEMBER("&c&l[!]&7 &c%1$s&7 is already a member of &c%2$s"), - COMMAND_DEINVITE_MIGHTWANT("&c&l[!]&7 You might want to: &c%1$s"), - COMMAND_DEINVITE_REVOKED("&c&l[!]&7 &7%1$s &crevoked&7 your invitation to &c%2$s&7."), - COMMAND_DEINVITE_REVOKES("&c&l[!]&7 %1$s&c revoked &7%2$s's&c invitation."), - COMMAND_DEINVITE_DESCRIPTION("Remove a pending invitation"), - - COMMAND_DELFWARP_DELETED("&c&l[!]&7 Deleted warp &c%1$s"), - COMMAND_DELFWARP_INVALID("&c&l[!]&7 Couldn't &cfind&7 warp &c%1$s"), - COMMAND_DELFWARP_TODELETE("to delete warp"), - COMMAND_DELFWARP_FORDELETE("for deleting warp"), - COMMAND_DELFWARP_DESCRIPTION("Delete a faction warp"), - - COMMAND_DESCRIPTION_CHANGES("&c&l[!]&7 You have &cchanged&7 the &cdescription&7 for &c%1$s&7 to:"), - COMMAND_DESCRIPTION_CHANGED("&c&l[!]&7 The faction&c %1$s&7 changed their &cdescription &7to:"), - COMMAND_DESCRIPTION_TOCHANGE("to change faction description"), - COMMAND_DESCRIPTION_FORCHANGE("for changing faction description"), - COMMAND_DESCRIPTION_DESCRIPTION("Change the faction description"), - - COMMAND_DISBAND_IMMUTABLE("&c&l[!]&7 &7You &ccannot&7 disband &2Wilderness&7,&e SafeZone&7, or &4WarZone."), - COMMAND_DISBAND_MARKEDPERMANENT("&c&l[!]&7 This faction is designated as&c permanent&7, so you cannot disband it."), - COMMAND_DISBAND_BROADCAST_YOURS("&c&l[!]&7 &c%1$s&7 disbanded your &cfaction."), - COMMAND_DISBAND_BROADCAST_NOTYOURS("&c&l[!]&7 &c%1$s &7disbanded the faction &c%2$s."), - COMMAND_DISBAND_HOLDINGS("&c&l[!]&7 &7You have been given the disbanded &cfaction's bank&7, totaling &c%1$s."), - COMMAND_DISBAND_PLAYER("&c&l[!] &7You have disbanded your &cfaction"), - COMMAND_DISBAND_CONFIRM("&c&l[!]&7 Your Faction has&c {tnt} &7tnt left in the bank, it will be &clost&7 if the faction is &cdisbanded&7. Type&c /f disband &7again within &c10&7 seconds to&c disband&7."), - COMMAND_DISBAND_DESCRIPTION("Disband a faction"), - - COMMAND_FLY_DISABLED("&c&l[!]&7 Sorry, Faction flight is &cdisabled &7on this server"), - COMMAND_FLY_DESCRIPTION("Enter or leave Faction flight mode"), - COMMAND_FLY_CHANGE("&c&l[!]&7 Faction flight &c%1$s"), - COMMAND_FLY_COOLDOWN("&c&l[!]&7 You will &cnot&7 take fall damage for &c{amount}&7 seconds"), - COMMAND_FLY_DAMAGE("&c&l[!]&7 Faction flight &cdisabled&7 due to entering combat"), - COMMAND_FLY_NO_ACCESS("&c&l[!]&7 &cCannot fly &7in territory of %1$s"), - COMMAND_FLY_ENEMY_NEAR("&c&l[!]&7 Flight has been&c disabled&7 an enemy is nearby"), - COMMAND_FLY_CHECK_ENEMY("&c&l[!]&7 Cannot fly here, an enemy is &cnearby"), - COMMAND_FLY_NO_EPEARL("&c&l[!] &7You &ccannot&7 throw enderpearls while flying!"), - - COMMAND_FOCUS_SAMEFACTION("&c[!] You may not focus players in your faction!"), - COMMAND_FOCUS_FOCUSING("&c&l[!] &7Your faction is now focusing &c%s"), - COMMAND_FOCUS_NO_LONGER("&c&l[!] &7Your faction is no longer focusing &c%s"), - COMMAND_FOCUS_DESCRIPTION("Focus a Specific Player"), - - - COMMAND_FWARP_CLICKTOWARP("&c&l[!]&7 Click to &cwarp!"), - COMMAND_FWARP_COMMANDFORMAT("&c&l[!]&7 /f warp &c[password]"), - COMMAND_FWARP_WARPED("&c&l[!]&7 Warped to &c%1$s"), - COMMAND_FWARP_INVALID_WARP("&c&l[!]&7 Couldn't find warp &c%1$s"), - COMMAND_FWARP_TOWARP("to warp"), - COMMAND_FWARP_FORWARPING("for warping"), - COMMAND_FWARP_WARPS("Warps: "), - COMMAND_FWARP_DESCRIPTION("Teleport to a faction warp"), - COMMAND_FWARP_INVALID_PASSWORD("&c&l[!]&7 &cInvalid password!"), - COMMAND_FWARP_PASSWORD_REQUIRED("&c&l[!]&c Warp Password:"), - COMMAND_FWARP_PASSWORD_TIMEOUT("&c&l[!]&7 Warp password &ccanceled"), - - COMMAND_HINT_PERMISSION("&aYou can manage your factions permissions using &7/f perms"), - - COMMAND_HOME_DISABLED("&c&l[!]&7 Sorry, Faction homes are &cdisabled on this server."), - COMMAND_HOME_TELEPORTDISABLED("&c&l[!]&7 Sorry, the ability to &cteleport &7to Faction homes is &cdisabled &7on this server."), - COMMAND_HOME_NOHOME("&c&l[!]&7 Your faction does &cnot &7have a home. "), - COMMAND_HOME_INENEMY("&c&l[!]&7 You &ccannot teleport &7to your &cfaction home&7 while in the territory of an &cenemy faction&7."), - COMMAND_HOME_WRONGWORLD("&c&l[!]&7 You &ccannot &7teleport to your &cfaction home&7 while in a different world."), - COMMAND_HOME_ENEMYNEAR("&c&l[!]&7 You &ccannot teleport&7 to your faction home while an enemy is within &c%s&7 blocks of you."), - COMMAND_HOME_TOTELEPORT("to teleport to your faction home"), - COMMAND_HOME_FORTELEPORT("for teleporting to your faction home"), - COMMAND_HOME_DESCRIPTION("Teleport to the faction home"), - COMMAND_HOME_BLOCKED("&c&l[!] You may not teleport to a home that is claimed by &b%1$s"), - - COMMAND_INSPECT_DISABLED_MSG("&c&l[!]&7 Inspect mode is now &cdisabled."), - COMMAND_INSPECT_DISABLED_NOFAC("&c&l[!]&7 Inspect mode is now &cdisabled,&7 because you &cdo not have a faction!"), - COMMAND_INSPECT_ENABLED("&c&l[!]&7 Inspect mode is now &aEnabled."), - COMMAND_INSPECT_HEADER("&c&m---&7Inspect Data&c&m---&c//&7x:{x},y:{y},z:{z}"), - COMMAND_INSPECT_ROW("&c{time} &7// &c{action} &7// &c{player} &7// &c{block-type}"), - COMMAND_INSPECT_NODATA("&c&l[!]&7 &7No Data was found!"), - COMMAND_INSPECT_NOTINCLAIM("&c&l[!]&7 &7You can &conly&7 inspect in &cyour &7claims!"), - COMMAND_INSPECT_BYPASS("&c&l[!]&7 Inspecting in &cbypass&7 mode"), - COMMAND_INSPECT_DESCRIPTION("Inspect blocks!"), - - COMMAND_INVITE_TOINVITE("to invite someone"), - COMMAND_INVITE_FORINVITE("for inviting someone"), - COMMAND_INVITE_CLICKTOJOIN("Click to join!"), - COMMAND_INVITE_INVITEDYOU(" &chas invited you to join "), - COMMAND_INVITE_INVITED("&c&l[!]&7 &c%1$s&7 invited &c%2$s&7 to your faction."), - COMMAND_INVITE_ALREADYMEMBER("&c&l[!]&7 &c%1$s&7 is already a member of&c %2$s"), - COMMAND_INVITE_ALREADYINVITED("&c&l[!]&7 &c%1$s&7 has already been invited"), - COMMAND_INVITE_DESCRIPTION("Invite a player to your faction"), - COMMAND_INVITE_BANNED("&c&l[!]&7 &7%1$s &cis banned &7from your Faction. &cNot &7sending an invite."), - - COMMAND_JOIN_CANNOTFORCE("&c&l[!]&7 You&c do not&7 have permission to &cmove other players&7 into a faction."), - COMMAND_JOIN_SYSTEMFACTION("&c&l[!]&7 Players may only join &cnormal factions&7. This is a &c&lsystem faction&7."), - COMMAND_JOIN_ALREADYMEMBER("&c&l[!]&7 &c%1$s %2$s already a member of&c %3$s"), - COMMAND_JOIN_ATLIMIT(" &c&l[!]&7 The faction &c%1$s &7is at the limit of&c %2$d&7 members, so&c %3$s&7 cannot currently join."), - COMMAND_JOIN_INOTHERFACTION("&c&l[!]&7 &c%1$s &7must leave&c %2$s &7current faction first."), - COMMAND_JOIN_NEGATIVEPOWER("&c&l[!]&7 &c%1$s &7cannot join a faction with a &cnegative power&7 level."), - COMMAND_JOIN_REQUIRESINVITATION("&c&l[!]&7 This faction &crequires&7 an invitation."), - COMMAND_JOIN_ATTEMPTEDJOIN("&c&l[!]&7 &c%1$s&7 tried to join your faction."), - COMMAND_JOIN_TOJOIN("to join a faction"), - COMMAND_JOIN_FORJOIN("for joining a faction"), - COMMAND_JOIN_SUCCESS("&c&l[!]&7 &c%1$s &7successfully joined &c%2$s."), - COMMAND_JOIN_MOVED("&c&l[!]&7 &c%1$s &7moved you into the faction&c %2$s."), - COMMAND_JOIN_JOINED("&c&l[!]&7 &c%1$s &7joined your faction."), - COMMAND_JOIN_JOINEDLOG("&c&l[!]&7 &c%1$s&7 joined the faction&c %2$s."), - COMMAND_JOIN_MOVEDLOG("&c&l[!]&7 &c%1$s &7moved the player&c %2$s &7into the faction&c %3$s&7."), - COMMAND_JOIN_DESCRIPTION("&a&l» &7Join a faction"), - COMMAND_JOIN_BANNED("&c&l[!]&7 You are &cbanned &7from &c%1$s."), - - COMMAND_KICK_CANDIDATES("&c&l[!]&7 Players you can kick: "), - COMMAND_KICK_CLICKTOKICK("Click to kick "), - COMMAND_KICK_SELF("&c&l[!]&7 You &ccannot &7kick&c yourself&7."), - COMMAND_KICK_NONE("&c&l[!]&7 That player&c is not&7 in a faction."), - COMMAND_KICK_NOTMEMBER("&c&l[!]&7 &c%1$s is not a member of %2$s"), - COMMAND_KICK_INSUFFICIENTRANK("&c&l[!]&7 Your rank is &ctoo low &7to kick this player."), - COMMAND_KICK_NEGATIVEPOWER("&c&l[!]&7 You &ccannot &7kick that member until their power is &apositive&7."), - COMMAND_KICK_TOKICK("to kick someone from the faction"), - COMMAND_KICK_FORKICK("for kicking someone from the faction"), - COMMAND_KICK_FACTION("&c&l[!]&7 %1$s&7 kicked %2$s&c from the faction!"), //message given to faction members - COMMAND_KICK_KICKS("&c&l[!]&7 You kicked &c%1$s&7 from the faction&c %2$s&7!"), //kicker perspective - COMMAND_KICK_KICKED("&c&l[!]&7 &c%1$s &7kicked you from&c %2$s&7!"), //kicked player perspective - COMMAND_KICK_DESCRIPTION("Kick a player from the faction"), - - COMMAND_LIST_FACTIONLIST("&c&l[!]&7 Faction List "), - COMMAND_LIST_TOLIST("to list the factions"), - COMMAND_LIST_FORLIST("for listing the factions"), - COMMAND_LIST_ONLINEFACTIONLESS("Online factionless: "), - COMMAND_LIST_DESCRIPTION("&a&l» &7See a list of the factions"), - - COMMAND_LOCK_LOCKED("&c&l[!]&7 Factions is now&c locked"), - COMMAND_LOCK_UNLOCKED("&c&l[!]&7 Factions in now&a unlocked"), - COMMAND_LOCK_DESCRIPTION("Lock all write stuff. Apparently."), - - COMMAND_LOGINS_TOGGLE("&c&l[!]&7 Set login / logout notifications for Faction members to: &c%s"), - COMMAND_LOGINS_DESCRIPTION("Toggle(?) login / logout notifications for Faction members"), - - COMMAND_LOWPOWER_HEADER("&8&m--------&8&8&m---------"), - COMMAND_LOWPOWER_FORMAT("&c{player} &8(&c{player_power}&8/&c{maxpower}&8)"), - COMMAND_LOWPOWER_DESCRIPTION("Shows a list of players in your faction with lower power levels"), - - COMMAND_MAP_TOSHOW("to show the map"), - COMMAND_MAP_FORSHOW("for showing the map"), - COMMAND_MAP_UPDATE_ENABLED("&c&l[!]&7 Map auto update &aENABLED."), - COMMAND_MAP_UPDATE_DISABLED("&c&l[!]&7 Map auto update &cDISABLED."), - COMMAND_MAP_DESCRIPTION("Show the territory map, and set optional auto update"), - - COMMAND_MAPHEIGHT_DESCRIPTION("&eUpdate the lines that /f map sends"), - COMMAND_MAPHEIGHT_SET("&c&l[!]&7 Set /f map lines to &c&a%1$d"), - COMMAND_MAPHEIGHT_CURRENT("&c&l[!]&7 Current &cmapheight: &a%1$d"), - - COMMAND_MOD_CANDIDATES("&c&l[!]&7 Players you can promote: "), - COMMAND_MOD_CLICKTOPROMOTE("Click to promote "), - COMMAND_MOD_NOTMEMBER("&c&l[!]&7 &c%1$s7 is not a member in your faction."), - COMMAND_MOD_NOTADMIN("&c&l[!]&7 You &care not&7 the faction admin."), - COMMAND_MOD_SELF("&c&l[!]&7 The target player&c musn't&7 be yourself."), - COMMAND_MOD_TARGETISADMIN("&c&l[!]&7 The target player is a &cfaction admin.&7 Demote them first."), - COMMAND_MOD_REVOKES("&c&l[!]&7 &7You have &cremoved&7 moderator status from &c%1$s."), - COMMAND_MOD_REVOKED("&c&l[!]&7 &c%1$s&7 is &cno longer&7 moderator in your faction."), - COMMAND_MOD_PROMOTES("&c&l[!]&7 &c%1$s&7 was &cpromoted&7 to moderator in your faction."), - COMMAND_MOD_PROMOTED("&c&l[!]&7 You have promoted&c %1$s&7 to moderator."), - COMMAND_MOD_DESCRIPTION("Give or revoke moderator rights"), - - COMMAND_COLEADER_CANDIDATES("&c&l[!]&7 Players you can promote: "), - COMMAND_COLEADER_CLICKTOPROMOTE("Click to promote "), - COMMAND_COLEADER_NOTMEMBER("&c&l[!]&7 &c%1$s&7 is &cnot a member&7 in your faction."), - COMMAND_COLEADER_NOTADMIN("&c&l[!]&7 You are&c not&7 the faction admin."), - COMMAND_COLEADER_SELF("&c&l[!]&7 The target player&c musn't&7 be yourself."), - COMMAND_COLEADER_TARGETISADMIN("&c&l[!]&7 The target player is a &cfaction admin&7. Demote them first."), - COMMAND_COLEADER_REVOKES("&c&l[!]&7 You have removed &ccoleader &7status from&c %1$s&7."), - COMMAND_COLEADER_REVOKED("&c&l[!]&7 &c%1$s&7 is no longer&c coleader &7in your faction."), - COMMAND_COLEADER_PROMOTES("&c&l[!]&7 &c%1$s&7 was promoted to &ccoleader &7in your faction."), - COMMAND_COLEADER_PROMOTED("&c&l[!]&7 You have &cpromoted &7%1$s to &ccoleader."), - COMMAND_COLEADER_DESCRIPTION("Give or revoke coleader rights"), - - COMMAND_MODIFYPOWER_ADDED("&c&l[!]&7 Added &c%1$f &7power to &c%2$s. &7New total rounded power: &c%3$d"), - COMMAND_MODIFYPOWER_DESCRIPTION("Modify the power of a faction/player"), - - COMMAND_MONEY_LONG("&c&l[!]&7 The faction money commands."), - COMMAND_MONEY_DESCRIPTION("Faction money commands"), - - COMMAND_MONEYBALANCE_SHORT("show faction balance"), - COMMAND_MONEYBALANCE_DESCRIPTION("Show your factions current money balance"), - - COMMAND_MONEYDEPOSIT_DESCRIPTION("Deposit money"), - COMMAND_MONEYDEPOSIT_DEPOSITED("&c&l[!]&7 &c%1$s &7deposited&c %2$s&7 in the faction bank:&c %3$s"), - - COMMAND_MONEYTRANSFERFF_DESCRIPTION("Transfer f -> f"), - COMMAND_MONEYTRANSFERFF_TRANSFER("&c&l[!]&7 &c%1$s&7 transferred&c %2$s &7from the faction &c\"%3$s\"&7 to the faction&c \"%4$s\"&7"), - - COMMAND_MONEYTRANSFERFP_DESCRIPTION("Transfer f -> plugin"), - COMMAND_MONEYTRANSFERFP_TRANSFER("&c&l[!]&7 &c%1$s &7transferred&c %2$s &7from the faction&c \"%3$s\" &7to the player &c\"%4$s\""), - - COMMAND_MONEYTRANSFERPF_DESCRIPTION("Transfer plugin -> f"), - COMMAND_MONEYTRANSFERPF_TRANSFER("&c&l[!]&7 &c%1$s&7 transferred &c%2$s&7 from the player &c\"%3$s\" &7to the faction&c \"%4$s\""), - - COMMAND_MONEYWITHDRAW_DESCRIPTION("Withdraw money"), - COMMAND_MONEYWITHDRAW_WITHDRAW("&c&l[!]&7 &c%1$s&7 withdrew&c %2$s &7from the faction bank:&c %3$s"), - - COMMAND_OPEN_TOOPEN("to open or close the faction"), - COMMAND_OPEN_FOROPEN("for opening or closing the faction"), - COMMAND_OPEN_OPEN("open"), - COMMAND_OPEN_CLOSED("closed"), - COMMAND_OPEN_CHANGES("&c&l[!]&7 &c%1$s&7 changed the faction to &c%2$s&7."), - COMMAND_OPEN_CHANGED("&c&l[!]&7 The faction &c%1$s&7 is now &c%2$s"), - COMMAND_OPEN_DESCRIPTION("Switch if invitation is required to join"), - - COMMAND_OWNER_DISABLED("&c&l[!]&7 Sorry, but &cowned areas &7are &cdisabled &7on this server."), - COMMAND_OWNER_LIMIT("&c&l[!]&7 Sorry, but you have reached the server's &climit&7 of &c%1$d&7 owned areas per faction."), - COMMAND_OWNER_WRONGFACTION("&c&l[!]&7 &7This land is &cnot claimed &7by your faction, so you &ccan't set&7 ownership of it."), - COMMAND_OWNER_NOTCLAIMED("&c&l[!]&7 This land&c is not &7claimed by a faction. Ownership &cis not &7possible."), - COMMAND_OWNER_NOTMEMBER("&c&l[!]&7 &c%1$s&7 is &cnot a member &7of this faction."), - COMMAND_OWNER_CLEARED("&c&l[!]&7 You have &ccleared &7ownership for this claimed area."), - COMMAND_OWNER_REMOVED("&c&l[!]&7 You have&c removed ownership &7of this &cclaimed land&7 from &c%1$s&7."), - COMMAND_OWNER_TOSET("to set ownership of claimed land"), - COMMAND_OWNER_FORSET("for setting ownership of claimed land"), - COMMAND_OWNER_ADDED("&c&l[!]&7 You have added &c%1$s&7 to the &cowner list&7 for this claimed land."), - COMMAND_OWNER_DESCRIPTION("Set ownership of claimed land"), - - COMMAND_KILLHOLOGRAMS_DESCRIPTION("Kill holograms in a radius, admin command"), - - COMMAND_OWNERLIST_DISABLED("&c&l[!]&7 &cSorry, &7but owned areas are &cdisabled&7 on this server."),//dup-> - COMMAND_OWNERLIST_WRONGFACTION("&c&l[!]&7 This land &cis not&7 claimed by your faction."),//eq - COMMAND_OWNERLIST_NOTCLAIMED("&c&l[!]&7 This land is not claimed by any faction, thus no owners."),//eq - COMMAND_OWNERLIST_NONE("&c&l[!]&7 No owners are set here; everyone in the faction has access."), - COMMAND_OWNERLIST_OWNERS("&c&l[!]&7 Current owner(s) of this land: %1$s"), - COMMAND_OWNERLIST_DESCRIPTION("List owner(s) of this claimed land"), - - COMMAND_PAYPALSET_DESCRIPTION("&c&l[!] &7Set the email of your faction to claim rewards."), - COMMAND_PAYPALSEE_DESCRIPTION("&c&l[!] &7View a specific factions paypal email with &b/f &b."), - COMMAND_PAYPALSET_CREATED("&c&l[!] &7Make sure to type &b/f &7!"), - COMMAND_PAYPALSET_SUCCESSFUL("&c&l[!] &7Successfully set your factions email - &b%1$s&7."), - COMMAND_PAYPALSEE_FACTION_PAYPAL("&c&l[!] &b%1$s's &7faction has their paypal set to &b%2$s&7."), - COMMAND_PAYPALSEE_FACTION_NOTSET("&c&l[!] &b%1$s's &7paypal has not yet been set!"), - COMMAND_PAYPALSEE_FACTION_NOFACTION("&c&l[!] &b%1$s &7does not have a faction!"), - - COMMAND_PEACEFUL_DESCRIPTION("&c&l[!]&7Set a faction to peaceful"), - COMMAND_PEACEFUL_YOURS("&c&l[!]&7%1$s has %2$s your faction"), - COMMAND_PEACEFUL_OTHER("&c&l[!]&7%s has %s the faction '%s'."), - COMMAND_PEACEFUL_GRANT("&c&l[!]&7 granted peaceful status to"), - COMMAND_PEACEFUL_REVOKE("removed peaceful status from"), - - COMMAND_PERM_DESCRIPTION("&c&l[!]&7&6Edit or list your Faction's permissions."), - COMMAND_PERM_INVALID_RELATION("&c&l[!]&7Invalid relation defined. Try something like&c 'ally'"), - COMMAND_PERM_INVALID_ACCESS("&c&l[!]&7 Invalid access defined. Try something like &c'allow'"), - COMMAND_PERM_INVALID_ACTION("&c&l[!]&7 Invalid action defined. Try something like &c'build'"), - COMMAND_PERM_SET("&c&l[!]&7 Set permission&c %1$s &7to &c%2$s &7for relation&c %3$s"), - COMMAND_PERM_TOP("RCT MEM OFF ALLY TRUCE NEUT ENEMY"), - - COMMAND_PERMANENT_DESCRIPTION("Toggles a permanent faction option"), - COMMAND_PERMANENT_GRANT("&c&l[!]&7 added permanent status to"), - COMMAND_PERMANENT_REVOKE("&c&l[!]&7 removed permanent status from"), - COMMAND_PERMANENT_YOURS("&c&l[!]&7 &c%1$s&7 has &c%2$s&7 your faction"), - COMMAND_PERMANENT_OTHER("&c&l[!]&7 &c%s &7has &c%s &7the faction &c'%s'."), - COMMAND_PROMOTE_TARGET("&c&l[!]&7 You've been &c%1$s&7 to &c%2$s"), - COMMAND_PROMOTE_SUCCESS("&c&l[!]&7 You successfully&c %1$s %2$s &cto&7 %3$s"), - COMMAND_PROMOTE_PROMOTED("promoted"), - COMMAND_PROMOTE_DEMOTED("demoted"), - COMMAND_PROMOTE_COLEADER_ADMIN("&c&l[!]&7 &cColeaders cant promote players to Admin!"), - - COMMAND_PERMANENTPOWER_DESCRIPTION("Toggle permanent faction power option"), - COMMAND_PERMANENTPOWER_GRANT("added permanentpower status to"), - COMMAND_PERMANENTPOWER_REVOKE("removed permanentpower status from"), - COMMAND_PERMANENTPOWER_SUCCESS("&c&l[!]&7 You&c %s &7%s."), - COMMAND_PERMANENTPOWER_FACTION("&c&l[!]&7 &c%s %s &7your faction"), - - COMMAND_PROMOTE_DESCRIPTION("/f promote "), - COMMAND_PROMOTE_WRONGFACTION("&c&l[!]&7 &c%1$s&7 is &cnot&7 part of your faction."), - COMMAND_NOACCESS("&c&l[!]&7 You don't have access to that."), - COMMAND_PROMOTE_NOTTHATPLAYER("&c&l[!]&7 That player &ccannot&7 be promoted."), - COMMAND_PROMOTE_NOT_ALLOWED("&c&l[!]&7 You cannot promote to the same rank as yourself!"), - COMMAND_PROMOTE_NOTSELF("&c&l[!]&7 You cannot manage your own rank."), - COMMAND_PROMOTE_NOT_SAME("&c&l[!]&7 You cannot promote to the same rank as yourself!"), - - - COMMAND_POWER_TOSHOW("to show player power info"), - COMMAND_POWER_FORSHOW("for showing player power info"), - COMMAND_POWER_POWER("&c&l[!]&7 &c%1$s » &cPower &7/ &cMaxpower&a » &c%2$d &7/&c%3$d %4$s"), - COMMAND_POWER_BONUS(" (bonus: "), - COMMAND_POWER_PENALTY(" (penalty: "), - COMMAND_POWER_DESCRIPTION("&a&l» &7Show player &apower &7info"), - - COMMAND_POWERBOOST_HELP_1("&c&l[!]&7 You must specify \"plugin\" or \"player\" to target a player or \"f\" or \"faction\" to target a faction."), - COMMAND_POWERBOOST_HELP_2("&c&l[!]&7 ex. /f powerboost plugin SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"), - COMMAND_POWERBOOST_INVALIDNUM("You must specify a valid numeric value for the power bonus/penalty amount."), - COMMAND_POWERBOOST_PLAYER("Player \"%1$s\""), - COMMAND_POWERBOOST_FACTION("Faction \"%1$s\""), - COMMAND_POWERBOOST_BOOST("%1$s now has a power bonus/penalty of %2$d to min and max power levels."), - COMMAND_POWERBOOST_BOOSTLOG("%1$s has set the power bonus/penalty for %2$s to %3$d."), - COMMAND_POWERBOOST_DESCRIPTION("Apply permanent power bonus/penalty to specified player or faction"), - - COMMAND_RELATIONS_ALLTHENOPE("&c&l[!]&7 &cNope!You can't."), - COMMAND_RELATIONS_MORENOPE("&c&l[!]&7 &cNope!&7You can't declare a relation to &cyourself"), - COMMAND_RELATIONS_ALREADYINRELATIONSHIP("&c&l[!]&7 You &calready&7 have that relation wish set with&c %1$s."), - COMMAND_RELATIONS_TOMARRY("to change a relation wish"), - COMMAND_RELATIONS_FORMARRY("for changing a relation wish"), - COMMAND_RELATIONS_MUTUAL("&c&l[!]&7 Your faction is now %1$s to %2$s"), - COMMAND_RELATIONS_PEACEFUL("&c&l[!]&7 This will have no effect while your faction is peaceful."), - COMMAND_RELATIONS_PEACEFULOTHER("&c&l[!]&7 This will have &cno effect&7 while their faction is peaceful."), - COMMAND_RELATIONS_DESCRIPTION("Set relation wish to another faction"), - COMMAND_RELATIONS_EXCEEDS_ME("&c&l[!]&7 Failed to set relation wish. You can only have %1$s %2$s."), - COMMAND_RELATIONS_EXCEEDS_THEY("&c&l[!]&7 Failed to set relation wish. They can only have %1$s %2$s."), - - COMMAND_RELATIONS_PROPOSAL_1("&c&l[!]&7&c %1$s &7wishes to be your&c %2$s"), - COMMAND_RELATIONS_PROPOSAL_2("&c&l[!]&7 Type &c/%1$s %2$s %3$s&7 to accept."), - COMMAND_RELATIONS_PROPOSAL_SENT("&c&l[!]&7 &c%1$s&7 were informed that you wish to be &c%2$s"), - - COMMAND_RELOAD_TIME("&c&l[!]&7 Reloaded &call &7configuration files from disk, took &c%1$d ms."), - COMMAND_RELOAD_DESCRIPTION("Reload data file(s) from disk"), - - COMMAND_SAFEUNCLAIMALL_DESCRIPTION("Unclaim all safezone land"), - COMMAND_SAFEUNCLAIMALL_UNCLAIMED("&c&l[!]&7 You unclaimed&c ALL&7 safe zone land."), - COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG("&c&l[!]&7 &c%1$s&7 unclaimed all safe zones."), - - COMMAND_SAVEALL_SUCCESS("&c&l[!]&7 &cFactions saved to disk!"), - COMMAND_SAVEALL_DESCRIPTION("Save all data to disk"), - - COMMAND_SCOREBOARD_DESCRIPTION("Scoreboardy things"), - - COMMAND_SETBANNER_SUCCESS("&c&l[!] &7Banner Pattern Set!"), - COMMAND_SETBANNER_NOTBANNER("&c&l[!] &7The item is &cnot&7 a banner!"), - COMMAND_SETBANNER_DESCRIPTION("set banner pattern for your faction"), - - - COMMAND_SETDEFAULTROLE_DESCRIPTION("/f defaultrole - set your Faction's default role."), - COMMAND_SETDEFAULTROLE_NOTTHATROLE("&c&l[!]&7 You cannot set the default to admin."), - COMMAND_SETDEFAULTROLE_SUCCESS("Set default role of your faction to %1$s"), - COMMAND_SETDEFAULTROLE_INVALIDROLE("Couldn't find matching role for %1$s"), - - COMMAND_SETFWARP_NOTCLAIMED("&c&l[!]&7 You can &conly&7 set warps in your faction territory."), - COMMAND_SETFWARP_LIMIT("&c&l[!]&7 Your Faction already has the &cmax amount&7 of warps set &c(%1$d)."), - COMMAND_SETFWARP_SET("&c&l[!]&7 Set warp &c%1$s&7 and password &c'%2$s' &7to your location."), - COMMAND_SETFWARP_TOSET("to set warp"), - COMMAND_SETFWARP_FORSET("for setting warp"), - COMMAND_SETFWARP_DESCRIPTION("Set a faction warp"), - - COMMAND_SETHOME_DISABLED("&c&l[!]&7 &cSorry&7, Faction homes are disabled on this server."), - COMMAND_SETHOME_NOTCLAIMED("&c&l[!]&c Sorry&7, your faction home can only be set inside your &cown &7claimed territory."), - COMMAND_SETHOME_TOSET("to set the faction home"), - COMMAND_SETHOME_FORSET("for setting the faction home"), - COMMAND_SETHOME_SET("&c&l[!]&c %1$s&7 set the home for your faction. You can now use:"), - COMMAND_SETHOME_SETOTHER("&c&l[!]&7 You have set the home for the &c%1$s&7 faction."), - COMMAND_SETHOME_DESCRIPTION("Set the faction home"), - - COMMAND_SETMAXVAULTS_DESCRIPTION("Set max vaults for a Faction."), - COMMAND_SETMAXVAULTS_SUCCESS("&aSet max vaults for &e%s &ato &b%d"), - - COMMAND_VAULT_DESCRIPTION("Open your placed faction vault!"), - COMMAND_VAULT_INVALID("&c&l[!]&7 Your vault was either&c claimed&7, &cbroken&7, or has&c not been&7 placed yet."), - COMMAND_VAULT_OPENING("&c&l[!]&7 Opening faction vault."), - COMMAND_VAULT_NO_HOPPER("&c&l[!] &7You cannot place a hopper near a vault!"), - - COMMAND_GETVAULT_ALREADYSET("&c&l[!]&7 Vault has already been set!"), - COMMAND_GETVAULT_ALREADYHAVE("&c&l[!]&7 You already have a vault in your inventory!"), - COMMAND_GETVAULT_CHESTNEAR("&c&l[!]&7 &7There is a chest or hopper &cnearby"), - COMMAND_GETVAULT_SUCCESS("&cSucessfully set vault."), - COMMAND_GETVAULT_INVALIDLOCATION("&cVault can only be placed in faction land!"), - COMMAND_GETVAULT_DESCRIPTION("Get the faction vault item!"), - COMMAND_GETVAULT_RECEIVE("&cYou have recieved a faction vault!"), - COMMAND_GETVAULT_NOMONEY("&cYou do not have enough money"), - COMMAND_GETVAULT_MONEYTAKE("&c{amount} has been taken from your account"), - - COMMAND_SHOW_NOFACTION_SELF("You are not in a faction"), - COMMAND_SHOW_NOFACTION_OTHER("That's not a faction"), - COMMAND_SHOW_TOSHOW("to show faction information"), - COMMAND_SHOW_FORSHOW("for showing faction information"), - COMMAND_SHOW_DESCRIPTION("Description: %1$s"), - COMMAND_SHOW_PEACEFUL("This faction is Peaceful"), - COMMAND_SHOW_PERMANENT("This faction is permanent, remaining even with no members."), - COMMAND_SHOW_JOINING("Joining: %1$s "), - COMMAND_SHOW_INVITATION("invitation is required"), - COMMAND_SHOW_UNINVITED("no invitation is needed"), - COMMAND_SHOW_NOHOME("n/a"), - COMMAND_SHOW_POWER("Land / Power / Maxpower: %1$d/%2$d/%3$d %4$s."), - COMMAND_SHOW_BONUS(" (bonus: "), - COMMAND_SHOW_PENALTY(" (penalty: "), - COMMAND_SHOW_DEPRECIATED("(%1$s depreciated)"), //This is spelled correctly. - COMMAND_SHOW_LANDVALUE("Total land value: %1$s %2$s"), - COMMAND_SHOW_BANKCONTAINS("Bank contains: %1$s"), - COMMAND_SHOW_ALLIES("Allies: "), - COMMAND_SHOW_ENEMIES("Enemies: "), - COMMAND_SHOW_MEMBERSONLINE("Members online: "), - COMMAND_SHOW_MEMBERSOFFLINE("Members offline: "), - COMMAND_SHOW_COMMANDDESCRIPTION("Show faction information"), - COMMAND_SHOW_DEATHS_TIL_RAIDABLE("DTR: %1$d"), - COMMAND_SHOW_EXEMPT("This faction is exempt and cannot be seen."), - COMMAND_SHOW_NEEDFACTION("&cYou need to join a faction to view your own!"), - - COMMAND_SHOWCLAIMS_HEADER("&8&m-------------&8<{faction}'s claims&8>&8&m-------------"), - COMMAND_SHOWCLAIMS_FORMAT("&8[{world}]:"), - COMMAND_SHOWCLAIMS_CHUNKSFORMAT("&8(&c{x}&8,&c{z}&8)"), - COMMAND_SHOWCLAIMS_DESCRIPTION("show your factions claims!"), - - COMMAND_SHOWINVITES_PENDING("Players with pending invites: "), - COMMAND_SHOWINVITES_CLICKTOREVOKE("Click to revoke invite for %1$s"), - COMMAND_SHOWINVITES_DESCRIPTION("Show pending faction invites"), - - COMMAND_STATUS_FORMAT("%1$s Power: %2$s Last Seen: %3$s"), - COMMAND_STATUS_ONLINE("Online"), - COMMAND_STATUS_AGOSUFFIX(" ago."), - COMMAND_STATUS_DESCRIPTION("Show the status of a player"), - - COMMAND_STEALTH_DESCRIPTION("Enable and Disable Stealth Mode"), - COMMAND_STEALTH_ENABLE("&cStealth &7» &7You will no longer disable nearby players in /f fly."), - COMMAND_STEALTH_DISABLE("&cStealth &8» &7You will now disable other nearby players in /f fly."), - COMMAND_STEALTH_MUSTBEMEMBER("&cStealth &8» &4You must be in a faction to use this command"), - - COMMAND_STUCK_TIMEFORMAT("m 'minutes', s 'seconds.'"), - COMMAND_STUCK_CANCELLED("Teleport cancelled because you were damaged"), - COMMAND_STUCK_OUTSIDE("Teleport cancelled because you left %1$d block radius"), - COMMAND_STUCK_EXISTS("You are already teleporting, you must wait %1$s"), - COMMAND_STUCK_START("Teleport will commence in %s. Don't take or deal damage. "), - COMMAND_STUCK_TELEPORT("Teleported safely to %1$d, %2$d, %3$d."), - COMMAND_STUCK_TOSTUCK("to safely teleport %1$s out"), - COMMAND_STUCK_FORSTUCK("for %1$s initiating a safe teleport out"), - COMMAND_STUCK_DESCRIPTION("Safely teleports you out of enemy faction"), - - COMMAND_SEECHUNK_ENABLED("&cSeechunk enabled!"), - COMMAND_SEECHUNK_DISABLED("&cSeechunk disabled!"), - - - COMMAND_TAG_TAKEN("That tag is already taken"), - COMMAND_TAG_TOCHANGE("to change the faction tag"), - COMMAND_TAG_FORCHANGE("for changing the faction tag"), - COMMAND_TAG_FACTION("%1$s changed your faction tag to %2$s"), - COMMAND_TAG_CHANGED("The faction %1$s changed their name to %2$s."), - COMMAND_TAG_DESCRIPTION("Change the faction tag"), - - COMMAND_TITLE_TOCHANGE("to change a players title"), - COMMAND_TITLE_FORCHANGE("for changing a players title"), - COMMAND_TITLE_CHANGED("%1$s changed a title: %2$s"), - COMMAND_TITLE_DESCRIPTION("Set or remove a players title"), - - COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION("Toggles whether or not you will see alliance chat"), - COMMAND_TOGGLEALLIANCECHAT_IGNORE("Alliance chat is now ignored"), - COMMAND_TOGGLEALLIANCECHAT_UNIGNORE("Alliance chat is no longer ignored"), - - COMMAND_TOGGLESB_DISABLED("You can't toggle scoreboards while they are disabled."), - - COMMAND_TOP_DESCRIPTION("Sort Factions to see the top of some criteria."), - COMMAND_TOP_TOP("Top Factions by %s. Page %d/%d"), - COMMAND_TOP_LINE("%d. &6%s: &c%s"), // Rank. Faction: Value - COMMAND_TOP_INVALID("Could not sort by %s. Try balance, online, members, power or land."), - - COMMAND_TNT_DISABLED_MSG("&cThis command is disabled!"), - COMMAND_TNT_INVALID_NUM("The amount needs to be a number!"), - COMMAND_TNT_DEPOSIT_SUCCESS("&cSuccessfully deposited tnt."), - COMMAND_TNT_EXCEEDLIMIT("&cThis exceeds the bank limit!"), - COMMAND_TNT_WIDTHDRAW_SUCCESS("&cSuccessfully withdrew tnt."), - COMMAND_TNT_WIDTHDRAW_NOTENOUGH("&cNot enough tnt in bank."), - COMMAND_TNT_DEPOSIT_NOTENOUGH("&cNot enough tnt in tnt inventory."), - COMMAND_TNT_AMOUNT("&cYour faction has {amount} tnt in the tnt bank."), - COMMAND_TNT_POSITIVE("&cPlease use positive numbers!"), - COMMAND_TNT_DESCRIPTION("add/widthraw from faction's tnt bank"), - COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE("&cNot enough space in your inventory."), - COMMAND_TNT_ADD_DESCRIPTION("&b/f tnt add&3 "), - COMMAND_TNT_TAKE_DESCRIPTION("&b/f tnt take&3 "), - - COMMAND_TNTFILL_HEADER("&c&l[!] &7Filling tnt in dispensers..."), - COMMAND_TNTFILL_SUCCESS("&c&l[!] &7Filled &c{amount}&7 Tnt in &c{dispensers} &7dispensers"), - COMMAND_TNTFILL_NOTENOUGH("&c&l[!] &7Not enough tnt in inventory."), - COMMAND_TNTFILL_RADIUSMAX("&c&l[!] &7The max radius is {max}"), - COMMAND_TNTFILL_AMOUNTMAX("&c&l[!] &7The max amount is {max}"), - COMMAND_TNTFILL_MOD("&c&l[!] &7Tnt will be used from the faction bank because you dont have the specified amount in your inventory and you are a {role}"), - COMMAND_TNTFILL_DESCRIPTION("Fill tnt into dispensers around you"), - - COMMAND_UNBAN_DESCRIPTION("Unban someone from your Faction"), - COMMAND_UNBAN_NOTBANNED("&7%s &cisn't banned. Not doing anything."), - COMMAND_UNBAN_UNBANNED("&e%1$s &cunbanned &7%2$s"), - COMMAND_UNBAN_TARGET("&aYou were unbanned from &r%s"), - - COMMAND_UNCLAIM_SAFEZONE_SUCCESS("Safe zone was unclaimed."), - COMMAND_UNCLAIM_SAFEZONE_NOPERM("This is a safe zone. You lack permissions to unclaim."), - COMMAND_UNCLAIM_WARZONE_SUCCESS("War zone was unclaimed."), - COMMAND_UNCLAIM_WARZONE_NOPERM("This is a war zone. You lack permissions to unclaim."), - COMMAND_UNCLAIM_UNCLAIMED("%1$s unclaimed some of your land."), - COMMAND_UNCLAIM_UNCLAIMS("You unclaimed this land."), - COMMAND_UNCLAIM_LOG("%1$s unclaimed land at (%2$s) from the faction: %3$s"), - COMMAND_UNCLAIM_WRONGFACTION("You don't own this land."), - COMMAND_UNCLAIM_TOUNCLAIM("to unclaim this land"), - COMMAND_UNCLAIM_FORUNCLAIM("for unclaiming this land"), - COMMAND_UNCLAIM_FACTIONUNCLAIMED("%1$s unclaimed some land."), - COMMAND_UNCLAIM_DESCRIPTION("Unclaim the land where you are standing"), - - COMMAND_UNCLAIMALL_TOUNCLAIM("to unclaim all faction land"), - COMMAND_UNCLAIMALL_FORUNCLAIM("for unclaiming all faction land"), - COMMAND_UNCLAIMALL_UNCLAIMED("%1$s unclaimed ALL of your faction's land."), - COMMAND_UNCLAIMALL_LOG("%1$s unclaimed everything for the faction: %2$s"), - COMMAND_UNCLAIMALL_DESCRIPTION("Unclaim all of your factions land"), - COMMAND_UNCLAIM_CLICKTOUNCLAIM("Click to unclaim &2(%1$d, %2$d)"), - - COMMAND_VERSION_NAME("&c&l[!]&7 &c&k||| &r&4SavageFactions&7 &c&k|||&r &c» &7By ProSavage"), - COMMAND_VERSION_VERSION("&7Version &c» &7%1$s"), - COMMAND_VERSION_DESCRIPTION("Show plugin and translation version information"), - - COMMAND_WARUNCLAIMALL_DESCRIPTION("Unclaim all warzone land"), - COMMAND_WARUNCLAIMALL_SUCCESS("You unclaimed ALL war zone land."), - COMMAND_WARUNCLAIMALL_LOG("%1$s unclaimed all war zones."), - - COMMAND_RULES_DISABLED_MSG("&cThis command is disabled!"), - COMMAND_RULES_DESCRIPTION("set/remove/add rules!"), - COMMAND_RULES_ADD_INVALIDARGS("Please include a rule!"), - COMMAND_RULES_SET_INVALIDARGS("Please include a line number & rule!"), - COMMAND_RULES_REMOVE_INVALIDARGS("Please include a line number!"), - COMMAND_RULES_ADD_SUCCESS("&cRule added successfully!"), - COMMAND_RULES_REMOVE_SUCCESS("&cRule removed successfully!"), - COMMAND_RULES_SET_SUCCESS("&cRule set successfully!"), - COMMAND_RULES_CLEAR_SUCCESS("&cRule cleared successfully!"), - - /** - * Leaving - This is accessed through a command, and so it MAY need a COMMAND_* slug :s - */ - LEAVE_PASSADMIN("You must give the admin role to someone else first."), - LEAVE_NEGATIVEPOWER("You cannot leave until your power is positive."), - LEAVE_TOLEAVE("to leave your faction."), - LEAVE_FORLEAVE("for leaving your faction."), - LEAVE_LEFT("%s left faction %s."), - LEAVE_DISBANDED("%s was disbanded."), - LEAVE_DISBANDEDLOG("The faction %s (%s) was disbanded due to the last player (%s) leaving."), - LEAVE_DESCRIPTION("\\n &a&l» &7Leave your faction"), - - /** - * Claiming - Same as above basically. No COMMAND_* because it's not in a command class, but... - */ - CLAIM_PROTECTED("This land is protected"), - CLAIM_DISABLED("Sorry, this world has land claiming disabled."), - CLAIM_CANTCLAIM("You can't claim land for %s."), - CLAIM_ALREADYOWN("%s already own this land."), - CLAIM_MUSTBE("You must be %s to claim land."), - CLAIM_MEMBERS("Factions must have at least %s members to claim land."), - CLAIM_SAFEZONE("You can not claim a Safe Zone."), - CLAIM_WARZONE("You can not claim a War Zone."), - CLAIM_POWER("You can't claim more land!You need more power!"), - CLAIM_LIMIT("Limit reached. You can't claim more land!"), - CLAIM_ALLY("You can't claim the land of your allies."), - CLAIM_CONTIGIOUS("You can only claim additional land which is connected to your first claim or controlled by another faction!"), - CLAIM_FACTIONCONTIGUOUS("You can only claim additional land which is connected to your first claim!"), - CLAIM_PEACEFUL("%s owns this land. Your faction is peaceful, so you cannot claim land from other factions."), - CLAIM_PEACEFULTARGET("%s owns this land, and is a peaceful faction. You cannot claim land from them."), - CLAIM_THISISSPARTA("%s owns this land and is strong enough to keep it."), - CLAIM_BORDER("You must start claiming land at the border of the territory."), - CLAIM_TOCLAIM("to claim this land"), - CLAIM_FORCLAIM("for claiming this land"), - CLAIM_TOOVERCLAIM("to overclaim this land"), - CLAIM_FOROVERCLAIM("for over claiming this land"), - CLAIM_CLAIMED("%s claimed land for %s from %s."), - CLAIM_CLAIMEDLOG("%s claimed land at (%s) for the faction: %s"), - CLAIM_OVERCLAIM_DISABLED("Over claiming is disabled on this server."), - CLAIM_TOOCLOSETOOTHERFACTION("Your claim is too close to another Faction. Buffer required is %d"), - CLAIM_OUTSIDEWORLDBORDER("Your claim is outside the border."), - CLAIM_OUTSIDEBORDERBUFFER("Your claim is outside the border. %d chunks away world edge required."), - CLAIM_CLICK_TO_CLAIM("Click to try to claim &2(%1$d, %2$d)"), - CLAIM_MAP_OUTSIDEBORDER("&cThis claim is outside the worldborder!"), - CLAIM_YOUAREHERE("You are here"), - CLAIM_NO_TERRITORY_PERM("You do not have permission from your faction leader to do this!"), - - /** - * More generic, or less easily categorisable translations, which may apply to more than one class - */ - GENERIC_YOU("you"), - GENERIC_YOURFACTION("your faction"), - GENERIC_NOPERMISSION("You don't have permission to %1$s."), - GENERIC_FPERM_NOPERMISSION("&7The faction leader does not allow you to &c%1$s."), - GENERIC_DOTHAT("do that"), //Ugh nuke this from high orbit - GENERIC_NOPLAYERMATCH("No player match found for \"%1$s\"."), - GENERIC_NOPLAYERFOUND("No player \"%1$s\" could not be found."), - GENERIC_ARGS_TOOFEW("Too few arguments. Use like this:"), - GENERIC_ARGS_TOOMANY("Strange argument \"%1$s\". Use the command like this:"), - GENERIC_DEFAULTDESCRIPTION("Default faction description :("), - GENERIC_OWNERS("Owner(s): %1$s"), - GENERIC_PUBLICLAND("Public faction land."), - GENERIC_FACTIONLESS("factionless"), - GENERIC_SERVERADMIN("A server admin"), - GENERIC_DISABLED("disabled"), - GENERIC_ENABLED("enabled"), - GENERIC_INFINITY("∞"), - GENERIC_CONSOLEONLY("This command cannot be run as a player."), - GENERIC_PLAYERONLY("This command can only be used by ingame players."), - GENERIC_ASKYOURLEADER(" Ask your leader to:"), - GENERIC_YOUSHOULD("You should:"), - GENERIC_YOUMAYWANT("You may want to: "), - GENERIC_TRANSLATION_VERSION("Translation: %1$s(%2$s,%3$s) State: %4$s"), - GENERIC_TRANSLATION_CONTRIBUTORS("Translation contributors: %1$s"), - GENERIC_TRANSLATION_RESPONSIBLE("Responsible for translation: %1$s"), - GENERIC_FACTIONTAG_TOOSHORT("The faction tag can't be shorter than %1$s chars."), - GENERIC_FACTIONTAG_TOOLONG("The faction tag can't be longer than %s chars."), - GENERIC_FACTIONTAG_ALPHANUMERIC("Faction tag must be alphanumeric. \"%s\" is not allowed."), - GENERIC_PLACEHOLDER(""), - GENERIC_NOTENOUGHMONEY("&cYou dont have enough money!"), - GENERIC_MONEYTAKE("&c{amount} has been taken from your account."), - - - WARBANNER_NOFACTION("&cYou need a faction to use a warbanner!"), - WARBANNER_COOLDOWN("&cThe warbanner is on cooldown for your faction!"), - WARBANNER_INVALIDLOC("&cYou can only use warbanners in enemy land or the warzone"), - - /** - * ASCII compass (for chat map) - */ - COMPASS_SHORT_NORTH("N"), - COMPASS_SHORT_EAST("E"), - COMPASS_SHORT_SOUTH("S"), - COMPASS_SHORT_WEST("W"), - - /** - * Chat modes - */ - CHAT_MOD("mod chat"), - CHAT_FACTION("faction chat"), - CHAT_ALLIANCE("alliance chat"), - CHAT_TRUCE("truce chat"), - CHAT_PUBLIC("public chat"), - - /** - * Economy stuff - */ - - ECON_OFF("no %s"), // no balance, no value, no refund, etc - ECON_FORMAT("###,###.###"), - - /** - * Relations - */ - RELATION_MEMBER_SINGULAR("member"), - RELATION_MEMBER_PLURAL("members"), - RELATION_ALLY_SINGULAR("ally"), - RELATION_ALLY_PLURAL("allies"), - RELATION_TRUCE_SINGULAR("truce"), - RELATION_TRUCE_PLURAL("truces"), - RELATION_NEUTRAL_SINGULAR("neutral"), - RELATION_NEUTRAL_PLURAL("neutrals"), - RELATION_ENEMY_SINGULAR("enemy"), - RELATION_ENEMY_PLURAL("enemies"), - - /** - * Roles - */ - ROLE_LEADER("leader"), - ROLE_COLEADER("coleader"), - ROLE_MODERATOR("moderator"), - ROLE_NORMAL("normal member"), - ROLE_RECRUIT("recruit"), - - /** - * Region types. - */ - REGION_SAFEZONE("safezone"), - REGION_WARZONE("warzone"), - REGION_WILDERNESS("wilderness"), - - REGION_PEACEFUL("peaceful territory"), - /** - * In the player and entity listeners - */ - PLAYER_CANTHURT("You may not harm other players in %s"), - PLAYER_SAFEAUTO("This land is now a safe zone."), - PLAYER_WARAUTO("This land is now a war zone."), - PLAYER_OUCH("Ouch, that is starting to hurt. You should give it a rest."), - PLAYER_USE_WILDERNESS("You can't use %s in the wilderness."), - PLAYER_USE_SAFEZONE("You can't use %s in a safe zone."), - PLAYER_USE_WARZONE("You can't use %s in a war zone."), - PLAYER_USE_TERRITORY("You can't %s in the territory of %s."), - PLAYER_USE_OWNED("You can't use %s in this territory, it is owned by: %s."), - PLAYER_COMMAND_WARZONE("You can't use the command '%s' in warzone."), - PLAYER_COMMAND_NEUTRAL("You can't use the command '%s' in neutral territory."), - PLAYER_COMMAND_ENEMY("You can't use the command '%s' in enemy territory."), - PLAYER_COMMAND_PERMANENT("You can't use the command '%s' because you are in a permanent faction."), - PLAYER_COMMAND_ALLY("You can't use the command '%s' in ally territory."), - PLAYER_COMMAND_WILDERNESS("You can't use the command '%s' in the wilderness."), - - PLAYER_POWER_NOLOSS_PEACEFUL("You didn't lose any power since you are in a peaceful faction."), - PLAYER_POWER_NOLOSS_WORLD("You didn't lose any power due to the world you died in."), - PLAYER_POWER_NOLOSS_WILDERNESS("You didn't lose any power since you were in the wilderness."), - PLAYER_POWER_NOLOSS_WARZONE("You didn't lose any power since you were in a war zone."), - PLAYER_POWER_LOSS_WARZONE("The world you are in has power loss normally disabled, but you still lost power since you were in a war zone.\nYour power is now %d / %d"), - PLAYER_POWER_NOW("Your power is now %d / %d"), - - PLAYER_PVP_LOGIN("You can't hurt other players for %d seconds after logging in."), - PLAYER_PVP_REQUIREFACTION("You can't hurt other players until you join a faction."), - PLAYER_PVP_FACTIONLESS("You can't hurt players who are not currently in a faction."), - PLAYER_PVP_PEACEFUL("Peaceful players cannot participate in combat."), - PLAYER_PVP_NEUTRAL("You can't hurt neutral factions. Declare them as an enemy."), - PLAYER_PVP_CANTHURT("You can't hurt %s."), - - PLAYER_PVP_NEUTRALFAIL("You can't hurt %s in their own territory unless you declare them as an enemy."), - PLAYER_PVP_TRIED("%s tried to hurt you."), - - /** - * Strings lying around in other bits of the plugins - */ - NOPAGES("Sorry. No Pages available."), - INVALIDPAGE("Invalid page. Must be between 1 and %1$d"), - - /** - * The ones here before I started messing around with this - */ - TITLE("title", "&bFactions &0|&r"), - WILDERNESS("wilderness", "&2Wilderness"), - WILDERNESS_DESCRIPTION("wilderness-description", ""), - WARZONE("warzone", "&4Warzone"), - WARZONE_DESCRIPTION("warzone-description", "Not the safest place to be."), - SAFEZONE("safezone", "&6Safezone"), - SAFEZONE_DESCRIPTION("safezone-description", "Free from pvp and monsters."), - TOGGLE_SB("toggle-sb", "You now have scoreboards set to {value}"), - FACTION_LEAVE("faction-leave", "Leaving %1$s, Entering %2$s"), - FACTIONS_ANNOUNCEMENT_TOP("faction-announcement-top", "&d--Unread Faction Announcements--"), - FACTIONS_ANNOUNCEMENT_BOTTOM("faction-announcement-bottom", "&d--Unread Faction Announcements--"), - DEFAULT_PREFIX("default-prefix", "{relationcolor}[{faction}]"), - FACTION_LOGIN("faction-login", "&e%1$s &9logged in."), - FACTION_LOGOUT("faction-logout", "&e%1$s &9logged out.."), - NOFACTION_PREFIX("nofactions-prefix", "&6[&a4-&6]&r"), - DATE_FORMAT("date-format", "MM/d/yy h:ma"), // 3/31/15 07:49AM - - /** - * Raidable is used in multiple places. Allow more than just true/false. - */ - RAIDABLE_TRUE("raidable-true", "true"), - RAIDABLE_FALSE("raidable-false", "false"), - /** - * Warmups - */ - WARMUPS_NOTIFY_FLIGHT("&eFlight will enable in &d%2$d &eseconds."), - WARMUPS_NOTIFY_TELEPORT("&eYou will teleport to &d%1$s &ein &d%2$d &eseconds."), - WARMUPS_ALREADY("&cYou are already warming up."), - WARMUPS_CANCELLED("&cYou have cancelled your warmup."); - - public static SimpleDateFormat sdf; - private static YamlConfiguration LANG; - private String path; - private String def; - - /** - * Lang enum constructor. - * - * @param path The string path. - * @param start The default string. - */ - TL(String path, String start) { - this.path = path; - this.def = start; - } - - /** - * Lang enum constructor. Use this when your desired path simply exchanges '_' for '.' - * - * @param start The default string. - */ - TL(String start) { - this.path = this.name().replace('_', '.'); - if (this.path.startsWith(".")) { - path = "root" + path; - } - this.def = start; - } - - /** - * Set the {@code YamlConfiguration} to use. - * - * @param config The config to set. - */ - public static void setFile(YamlConfiguration config) { - LANG = config; - sdf = new SimpleDateFormat(DATE_FORMAT.toString()); - } - - @Override - public String toString() { - return ChatColor.translateAlternateColorCodes('&', LANG.getString(this.path, def)) + (this == TITLE ? " " : ""); - } - - public String format(Object... args) { - return String.format(toString(), args); - } - - /** - * Get the default value of the path. - * - * @return The default value of the path. - */ - public String getDefault() { - return this.def; - } - - /** - * Get the path to the string. - * - * @return The path to the string. - */ - public String getPath() { - return this.path; - } + /** + * Translation meta + */ + _AUTHOR("misc"), + _RESPONSIBLE("misc"), + _LANGUAGE("English"), + _ENCODING("UTF-8"), + _LOCALE("en_US"), + _REQUIRESUNICODE("false"), + _DEFAULT("true"), + _STATE("complete"), //incomplete, limited, partial, majority, complete + + /** + * Localised translation meta + */ + _LOCAL_AUTHOR("misc"), + _LOCAL_RESPONSIBLE("misc"), + _LOCAL_LANGUAGE("English"), + _LOCAL_REGION("US"), + _LOCAL_STATE("complete"), //And this is the English version. It's not ever going to be not complete. + + /** + * Command translations + */ + + /** + * Messsges for /f help + */ + COMMAND_HELP_NEXTCREATE("Learn how to create a faction on the next page."), + COMMAND_HELP_INVITATIONS("command.help.invitations", "You might want to close it and use invitations:"), + COMMAND_HELP_HOME("And don't forget to set your home:"), + COMMAND_HELP_404("&c&l» &7This page does &cnot &7exist"), + COMMAND_HELP_BANK_1("Your faction has a bank which is used to pay for certain"), //Move to last /f help page + COMMAND_HELP_BANK_2("things, so it will need to have money deposited into it."), //Move to last /f help page + COMMAND_HELP_BANK_3("To learn more, use the money command."), //Move to last /f help page + COMMAND_HELP_PLAYERTITLES("Player titles are just for fun. No rules connected to them."), //Move to last /f help page + COMMAND_HELP_OWNERSHIP_1("Claimed land with ownership set is further protected so"), //Move to last /f help page + COMMAND_HELP_OWNERSHIP_2("that only the owner(s), faction admin, and possibly the"), //Move to last /f help page + COMMAND_HELP_OWNERSHIP_3("faction moderators have full access."), //Move to last /f help page + COMMAND_HELP_RELATIONS_1("Set the relation you WISH to have with another faction."), //Move to last /f help page + COMMAND_HELP_RELATIONS_2("Your default relation with other factions will be neutral."), //Move to last /f help page + COMMAND_HELP_RELATIONS_3("If BOTH factions choose \"ally\" you will be allies."), //Move to last /f help page + COMMAND_HELP_RELATIONS_4("If ONE faction chooses \"enemy\" you will be enemies."), //Move to last /f help page + COMMAND_HELP_RELATIONS_5("You can never hurt members or allies."), //Move to last /f help page + COMMAND_HELP_RELATIONS_6("You can not hurt neutrals in their own territory."), //Move to last /f help page + COMMAND_HELP_RELATIONS_7("You can always hurt enemies and players without faction."), //Move to last /f help page + COMMAND_HELP_RELATIONS_8(""), + COMMAND_HELP_RELATIONS_9("Damage from enemies is reduced in your own territory."), //Move to last /f help page + COMMAND_HELP_RELATIONS_10("When you die you lose power. It is restored over time."), //Move to last /f help page + COMMAND_HELP_RELATIONS_11("The power of a faction is the sum of all member power."), //Move to last /f help page + COMMAND_HELP_RELATIONS_12("The power of a faction determines how much land it can hold."), //Move to last /f help page + COMMAND_HELP_RELATIONS_13("You can claim land from factions with too little power."), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_1("Only faction members can build and destroy in their own"), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_2("territory. Usage of the following items is also restricted:"), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_3("Door, Chest, Furnace, Dispenser, Diode."), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_4(""), + COMMAND_HELP_PERMISSIONS_5("Make sure to put pressure plates in front of doors for your"), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_6("guest visitors. Otherwise they can't get through. You can"), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_7("also use this to create member only areas."), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_8("As dispensers are protected, you can create traps without"), //Move to last /f help page + COMMAND_HELP_PERMISSIONS_9("worrying about those arrows getting stolen."), //Move to last /f help page + COMMAND_HELP_ADMIN_1("&a&l» &a/f claim safezone \n &7claim land for the Safe Zone"), + COMMAND_HELP_ADMIN_2("&a&l» &a/f claim warzone \n &7claim land for the War Zone"), + COMMAND_HELP_ADMIN_3("&a&l» &a/f autoclaim [safezone|warzone] \n &7take a guess"), + COMMAND_HELP_MOAR_1("Finally some commands for the server admins:"), + COMMAND_HELP_MOAR_2("More commands for server admins:"), + COMMAND_HELP_MOAR_3("Even more commands for server admins:"), + COMMAND_HELP_DESCRIPTION("\n &a&l» &7Display a &ahelp &7page"), + + COMMAND_NEAR_DESCRIPTION("Get nearby faction players in a radius."), + COMMAND_NEAR_DISABLED_MSG("&cThis command is disabled!"), + COMMAND_NEAR_FORMAT("{playername} &c({distance}m)"), + COMMAND_NEAR_USE_MSG("&cFaction members nearby"), + + /** + * Messsges for Faction Admins/Mods + */ + + COMMAND_UPGRADES_DESCRIPTION("&cOpen the Upgrades Menu"), + + COMMAND_ADMIN_NOTMEMBER("&c&l[!] &7%1$s &cis not a member in your faction."), + COMMAND_ADMIN_NOTADMIN("&c&l[!] &cYou are not the faction admin."), + COMMAND_ADMIN_TARGETSELF("'&c&l[!] &cThe target player musn''t be yourself."), + COMMAND_ADMIN_DEMOTES("&c&l[!] &cYou have demoted &7%1$s &cfrom the position of faction admin."), + COMMAND_ADMIN_DEMOTED("&c&l[!] &cYou have been demoted from the position of faction admin by &7%1$s&c"), + COMMAND_ADMIN_PROMOTES("&e&l[!] &eYou have promoted &6%1$s &eto the position of faction admin."), + COMMAND_ADMIN_PROMOTED("&e&l[!] &6%1$s &egave &6%2$s ðe leadership of &6%3$s&e."), + COMMAND_ADMIN_DESCRIPTION("Hand over your admin rights"), + COMMAND_ADMIN_NOMEMBERS("&e&l[!] &cNo one else to promote, please disband faction."), + + COMMAND_AHOME_DESCRIPTION("Send a player to their f home no matter what."), + COMMAND_AHOME_NOHOME("%1$s doesn't have an f home."), + COMMAND_AHOME_SUCCESS("$1%s was sent to their f home."), + COMMAND_AHOME_OFFLINE("%1$s is offline."), + COMMAND_AHOME_TARGET("You were sent to your f home."), + + COMMAND_ANNOUNCE_DESCRIPTION("Announce a message to players in faction."), + + COMMAND_FREECAM_ENEMYINRADIUS("Freecam disabled, An enemy is closeby!"), + COMMAND_FREECAM_OUTSIDEFLIGHT("Please dont leave the flight radius!"), + COMMAND_FREECAM_ENABLED("Freecam is now enabled!"), + COMMAND_FREECAM_DISABLED("Freecam is now disabled"), + COMMAND_FREECAM_DESCRIPTION("Go into spectator mode"), + + + COMMAND_AUTOCLAIM_ENABLED("&c&l[!] &7Now &cauto-claiming&7 land for %1$s."), + COMMAND_AUTOCLAIM_DISABLED("&c&l[!] Auto-claiming&7 of land is now &cdisabled."), + COMMAND_AUTOCLAIM_REQUIREDRANK("&c&l[!] &7You must be &c%1$s&7 to claim land."), + COMMAND_AUTOCLAIM_OTHERFACTION("&c&l[!]&7 You &ccan't &7claim land for &c%1$s&7."), + COMMAND_AUTOCLAIM_DESCRIPTION("Auto-claim land as you walk around"), + + COMMAND_AUTOHELP_HELPFOR("Help for command \""), + + COMMAND_BAN_DESCRIPTION("Ban players from joining your Faction."), + COMMAND_BAN_TARGET("&c&l[!] &7You were &cbanned &7from &c%1$s"), // banned player perspective + COMMAND_BAN_BANNED("&c&l[!] &7%1$s &cbanned &7%2$s"), + COMMAND_BAN_SELF("&c&l[!] &7You may &cnot &7ban &cyourself&7."), + COMMAND_BAN_INSUFFICIENTRANK("&c&l[!] &7Your &crank &7is too low to&c ban &7%1$s"), + COMMAND_BAN_ALREADYBANNED("&c&l[!] &7This player is &calready banned&7!"), + + COMMAND_BANLIST_DESCRIPTION("View a Faction's ban list"), + COMMAND_BANLIST_HEADER("&c&l[!] &7There are &c%d&7 bans for &c%s"), + COMMAND_BANLIST_ENTRY("&7%d. &c%s &r&7// &c%s &r&7// &c%s"), + COMMAND_BANLIST_NOFACTION("&c&l[!] &7You are &cnot &7in a Faction."), + COMMAND_BANLIST_INVALID("&c&l[!] &7The faction &c%s &7does not exist"), + + COMMAND_BOOM_PEACEFULONLY("&c&l[!] &7This command is &conly &7usable by factions which are &cspecifically &7designated as &cpeaceful&7."), + COMMAND_BOOM_TOTOGGLE("to toggle explosions"), + COMMAND_BOOM_FORTOGGLE("for toggling explosions"), + COMMAND_BOOM_ENABLED("&c&l[!] &c%1$s&7 has&c %2$s&7 explosions in your faction's territory."), + COMMAND_BOOM_DESCRIPTION("Toggle explosions (peaceful factions only)"), + + + COMMAND_BYPASS_ENABLE("&e&l[!] &eYou have enabled admin bypass mode. You will be able to build or destroy anywhere."), + COMMAND_BYPASS_ENABLELOG(" has ENABLED admin bypass mode."), + COMMAND_BYPASS_DISABLE("&c&l[!] &cYou have disabled admin bypass mode."), + COMMAND_BYPASS_DISABLELOG(" has DISABLED admin bypass mode."), + COMMAND_BYPASS_DESCRIPTION("Enable admin bypass mode"), + + COMMAND_BANNER_DESCRIPTION("Turn a held banner into a war banner"), + COMMAND_BANNER_NOTENOUGHMONEY("&c&l[!] &7You do&c not&7 have enough money"), + COMMAND_BANNER_MONEYTAKE("&c&l[!] $&c{amount} &7has been taken from your account."), + COMMAND_BANNER_SUCCESS("&c&l[!] &7You have created a &c&lWarBanner!"), + COMMAND_BANNER_DISABLED("&c&l[!] &7Buying&c warbanners&7 is &cdisabled!"), + + COMMAND_TPBANNER_NOTSET("&c&l[!] &7Your faction &cdoes not &7have a &c&lWarBanner &7placed!"), + COMMAND_TPBANNER_SUCCESS("&c&l[!] &cTeleporting &7to your factions's &c&lWarBanner"), + COMMAND_TPBANNER_DESCRIPTION("Teleport to your faction banner"), + + + COMMAND_CHAT_DISABLED("&c&l[!] &7The built in chat channels are &cdisabled &7on this server."), + COMMAND_CHAT_INVALIDMODE("&c&l[!] &cUnrecognised &7chat mode. Please enter either '&da&7','&af&7','&6m&7' or '&fp&7'"), + COMMAND_CHAT_DESCRIPTION("Change chat mode"), + + COMMAND_CHAT_MODE_PUBLIC("&c&l[!] &fPublic &7chat mode."), + COMMAND_CHAT_MODE_ALLIANCE("&c&l[!] &dAlliance &7only chat mode."), + COMMAND_CHAT_MODE_TRUCE("&c&l[!] &5Truce &7only chat mode."), + COMMAND_CHAT_MODE_FACTION("&c&l[!] &aFaction&7 only chat mode."), + COMMAND_CHAT_MODE_MOD("&c&l[!] &dMod &7only chat mode."), + COMMAND_CHAT_MOD_ONLY("&c&l[!] &7Only Mods can talk through this chat mode."), + + COMMAND_CHATSPY_ENABLE("&c&l[!] &7You have &cenabled &7chat spying mode."), + COMMAND_CHATSPY_ENABLELOG(" has ENABLED chat spying mode."), + COMMAND_CHATSPY_DISABLE("&c&l[!] &7You have &cdisabled &7chat spying mode."), + COMMAND_CHATSPY_DISABLELOG(" has DISABLED chat spying mode."), + COMMAND_CHATSPY_DESCRIPTION("Enable admin chat spy mode"), + + COMMAND_CLAIM_INVALIDRADIUS("&c&l[!]&7 If you specify a &cradius&7, it must be at least &c1&7."), + COMMAND_CLAIM_DENIED("&c&l[!]&7 You &cdo not &7have &cpermission&7 to &cclaim&7 in a radius."), + COMMAND_CLAIM_DESCRIPTION("Claim land from where you are standing"), + + COMMAND_CLAIMLINE_INVALIDRADIUS("&c&l[!]&7 If you &cspecify&7 a distance, it must be at least &c1&7."), + COMMAND_CLAIMLINE_DENIED("&c&l[!]&7 You &cdo not &7have&c permission&7 to claim in a line."), + COMMAND_CLAIMLINE_DESCRIPTION("Claim land in a straight line."), + COMMAND_CLAIMLINE_ABOVEMAX("&c&l[!]&7 The &cmaximum&7 limit for claim line is &c%s&7."), + COMMAND_CLAIMLINE_NOTVALID("&c&l[!]&7 &c%s&7 is not a &ccardinal &7direction. You may use &cnorth&7, &ceast&7, &csouth &7or &cwest&7."), + + COMMAND_CONFIG_NOEXIST("&c&l[!]&7 No configuration setting \"&c%1$s&7\" exists."), + COMMAND_CONFIG_SET_TRUE("\" option set to true (enabled)."), + COMMAND_CONFIG_SET_FALSE("\" option set to false (disabled)."), + COMMAND_CONFIG_OPTIONSET("\" option set to "), + COMMAND_CONFIG_COLOURSET("\" color option set to \""), + COMMAND_CONFIG_INTREQUIRED("Cannot set \"%1$s\": An integer (whole number) value required."), + COMMAND_CONFIG_LONGREQUIRED("Cannot set \"%1$s\": A long integer (whole number) value required."), + COMMAND_CONFIG_DOUBLEREQUIRED("Cannot set \"%1$s\": A double (numeric) value required."), + COMMAND_CONFIG_FLOATREQUIRED("Cannot set \"%1$s\": A float (numeric) value required."), + COMMAND_CONFIG_INVALID_COLOUR("Cannot set \"%1$s\": \"%2$s\" is not a valid color."), + COMMAND_CONFIG_INVALID_COLLECTION("\"%1$s\" is not a data collection type which can be modified with this command."), + COMMAND_CONFIG_INVALID_MATERIAL("Cannot change \"%1$s\" set: \"%2$s\" is not a valid material."), + COMMAND_CONFIG_INVALID_TYPESET("\"%1$s\" is not a data type set which can be modified with this command."), + COMMAND_CONFIG_MATERIAL_ADDED("\"%1$s\" set: Material \"%2$s\" added."), + COMMAND_CONFIG_MATERIAL_REMOVED("\"%1$s\" set: Material \"%2$s\" removed."), + COMMAND_CONFIG_SET_ADDED("\"%1$s\" set: \"%2$s\" added."), + COMMAND_CONFIG_SET_REMOVED("\"%1$s\" set: \"%2$s\" removed."), + COMMAND_CONFIG_LOG(" (Command was run by %1$s.)"), + COMMAND_CONFIG_ERROR_SETTING("Error setting configuration setting \"%1$s\" to \"%2$s\"."), + COMMAND_CONFIG_ERROR_MATCHING("Configuration setting \"%1$s\" couldn't be matched, though it should be... please report this error."), + COMMAND_CONFIG_ERROR_TYPE("'%1$s' is of type '%2$s', which cannot be modified with this command."), + COMMAND_CONFIG_DESCRIPTION("Change a conf.json setting"), + + COMMAND_CONVERT_BACKEND_RUNNING("&c&l[!]&7 Already running that backend."), + COMMAND_CONVERT_BACKEND_INVALID("&c&l[!]&7 Invalid backend"), + COMMAND_CONVERT_DESCRIPTION("Convert the plugin backend"), + + COMMAND_COORDS_MESSAGE("&c&l[!] &7{player}&7's coords are &c{x}&7,&c{y}&7,&c{z}&7 in &c{world}"), + COMMAND_COORDS_DESCRIPTION("broadcast your coords to your faction"), + + COMMAND_CHECKPOINT_DISABLED("&c&l[!]&7 You &ccannot&7 use checkpoint while its&c disabled&7!"), + COMMAND_CHECKPOINT_SET("&c&l[!]&7 You have &cset&7 the &cfaction checkpoint&7 at your &cLocation&7."), + COMMAND_CHECKPOINT_GO("&c&l[!]&7 &cTeleporting&7 to &cfaction checkpoint"), + COMMAND_CHECKPOINT_INVALIDLOCATION("&c&l[!]&7 &cInvalid Location!&7 You can &cset&7 checkpoints in &cyour claims&7 or &2wilderness&7."), + COMMAND_CHECKPOINT_NOT_SET("&c&l[!]&7 You have to &cset &7the &cfaction checkpoint&7 first."), + COMMAND_CHECKPOINT_CLAIMED("&c&l[!]&7 Your current &cfaction checkpoint&7 is claimed, set a &cnew &7one!"), + COMMAND_CHECKPOINT_DESCRIPTION("Set or go to your faction checkpoint!"), + + COMMAND_CREATE_MUSTLEAVE("&c&l[!]&7 You must &cleave &7your &ccurrent faction &7first."), + COMMAND_CREATE_INUSE("&c&l[!]&7 That tag is &calready &7in use."), + COMMAND_CREATE_TOCREATE("to create a new faction"), + COMMAND_CREATE_FORCREATE("for creating a new faction"), + COMMAND_CREATE_ERROR("&c&l[!]&7 There was an &cinternal error&7 while trying to create your faction. &cPlease try again&7."), + COMMAND_CREATE_CREATED("&c&l[!]&7 &c%1$s &7created a new faction &c&l%2$s"), + COMMAND_CREATE_YOUSHOULD("&c&l[!]&7 You should now: &c%1$s"), + COMMAND_CREATE_CREATEDLOG(" created a new faction: "), + COMMAND_CREATE_DESCRIPTION("Create a new faction"), + + COMMAND_DEINVITE_CANDEINVITE("&c&l[!]&7 Players you can &cdeinvite: "), + COMMAND_DEINVITE_CLICKTODEINVITE("&c&l[!]&7 Click to &crevoke&7 invite for &c%1$s"), + COMMAND_DEINVITE_ALREADYMEMBER("&c&l[!]&7 &c%1$s&7 is already a member of &c%2$s"), + COMMAND_DEINVITE_MIGHTWANT("&c&l[!]&7 You might want to: &c%1$s"), + COMMAND_DEINVITE_REVOKED("&c&l[!]&7 &7%1$s &crevoked&7 your invitation to &c%2$s&7."), + COMMAND_DEINVITE_REVOKES("&c&l[!]&7 %1$s&c revoked &7%2$s's&c invitation."), + COMMAND_DEINVITE_DESCRIPTION("Remove a pending invitation"), + + COMMAND_DELFWARP_DELETED("&c&l[!]&7 Deleted warp &c%1$s"), + COMMAND_DELFWARP_INVALID("&c&l[!]&7 Couldn't &cfind&7 warp &c%1$s"), + COMMAND_DELFWARP_TODELETE("to delete warp"), + COMMAND_DELFWARP_FORDELETE("for deleting warp"), + COMMAND_DELFWARP_DESCRIPTION("Delete a faction warp"), + + COMMAND_DESCRIPTION_CHANGES("&c&l[!]&7 You have &cchanged&7 the &cdescription&7 for &c%1$s&7 to:"), + COMMAND_DESCRIPTION_CHANGED("&c&l[!]&7 The faction&c %1$s&7 changed their &cdescription &7to:"), + COMMAND_DESCRIPTION_TOCHANGE("to change faction description"), + COMMAND_DESCRIPTION_FORCHANGE("for changing faction description"), + COMMAND_DESCRIPTION_DESCRIPTION("Change the faction description"), + + COMMAND_DISBAND_IMMUTABLE("&c&l[!]&7 &7You &ccannot&7 disband &2Wilderness&7,&e SafeZone&7, or &4WarZone."), + COMMAND_DISBAND_MARKEDPERMANENT("&c&l[!]&7 This faction is designated as&c permanent&7, so you cannot disband it."), + COMMAND_DISBAND_BROADCAST_YOURS("&c&l[!]&7 &c%1$s&7 disbanded your &cfaction."), + COMMAND_DISBAND_BROADCAST_NOTYOURS("&c&l[!]&7 &c%1$s &7disbanded the faction &c%2$s."), + COMMAND_DISBAND_HOLDINGS("&c&l[!]&7 &7You have been given the disbanded &cfaction's bank&7, totaling &c%1$s."), + COMMAND_DISBAND_PLAYER("&c&l[!] &7You have disbanded your &cfaction"), + COMMAND_DISBAND_CONFIRM("&c&l[!]&7 Your Faction has&c {tnt} &7tnt left in the bank, it will be &clost&7 if the faction is &cdisbanded&7. Type&c /f disband &7again within &c10&7 seconds to&c disband&7."), + COMMAND_DISBAND_DESCRIPTION("Disband a faction"), + + COMMAND_FLY_DISABLED("&c&l[!]&7 Sorry, Faction flight is &cdisabled &7on this server"), + COMMAND_FLY_DESCRIPTION("Enter or leave Faction flight mode"), + COMMAND_FLY_CHANGE("&c&l[!]&7 Faction flight &c%1$s"), + COMMAND_FLY_COOLDOWN("&c&l[!]&7 You will &cnot&7 take fall damage for &c{amount}&7 seconds"), + COMMAND_FLY_DAMAGE("&c&l[!]&7 Faction flight &cdisabled&7 due to entering combat"), + COMMAND_FLY_NO_ACCESS("&c&l[!]&7 &cCannot fly &7in territory of %1$s"), + COMMAND_FLY_ENEMY_NEAR("&c&l[!]&7 Flight has been&c disabled&7 an enemy is nearby"), + COMMAND_FLY_CHECK_ENEMY("&c&l[!]&7 Cannot fly here, an enemy is &cnearby"), + COMMAND_FLY_NO_EPEARL("&c&l[!] &7You &ccannot&7 throw enderpearls while flying!"), + + COMMAND_FOCUS_SAMEFACTION("&c[!] You may not focus players in your faction!"), + COMMAND_FOCUS_FOCUSING("&c&l[!] &7Your faction is now focusing &c%s"), + COMMAND_FOCUS_NO_LONGER("&c&l[!] &7Your faction is no longer focusing &c%s"), + COMMAND_FOCUS_DESCRIPTION("Focus a Specific Player"), + + + COMMAND_FWARP_CLICKTOWARP("&c&l[!]&7 Click to &cwarp!"), + COMMAND_FWARP_COMMANDFORMAT("&c&l[!]&7 /f warp &c[password]"), + COMMAND_FWARP_WARPED("&c&l[!]&7 Warped to &c%1$s"), + COMMAND_FWARP_INVALID_WARP("&c&l[!]&7 Couldn't find warp &c%1$s"), + COMMAND_FWARP_TOWARP("to warp"), + COMMAND_FWARP_FORWARPING("for warping"), + COMMAND_FWARP_WARPS("Warps: "), + COMMAND_FWARP_DESCRIPTION("Teleport to a faction warp"), + COMMAND_FWARP_INVALID_PASSWORD("&c&l[!]&7 &cInvalid password!"), + COMMAND_FWARP_PASSWORD_REQUIRED("&c&l[!]&c Warp Password:"), + COMMAND_FWARP_PASSWORD_TIMEOUT("&c&l[!]&7 Warp password &ccanceled"), + + COMMAND_HINT_PERMISSION("&aYou can manage your factions permissions using &7/f perms"), + + COMMAND_HOME_DISABLED("&c&l[!]&7 Sorry, Faction homes are &cdisabled on this server."), + COMMAND_HOME_TELEPORTDISABLED("&c&l[!]&7 Sorry, the ability to &cteleport &7to Faction homes is &cdisabled &7on this server."), + COMMAND_HOME_NOHOME("&c&l[!]&7 Your faction does &cnot &7have a home. "), + COMMAND_HOME_INENEMY("&c&l[!]&7 You &ccannot teleport &7to your &cfaction home&7 while in the territory of an &cenemy faction&7."), + COMMAND_HOME_WRONGWORLD("&c&l[!]&7 You &ccannot &7teleport to your &cfaction home&7 while in a different world."), + COMMAND_HOME_ENEMYNEAR("&c&l[!]&7 You &ccannot teleport&7 to your faction home while an enemy is within &c%s&7 blocks of you."), + COMMAND_HOME_TOTELEPORT("to teleport to your faction home"), + COMMAND_HOME_FORTELEPORT("for teleporting to your faction home"), + COMMAND_HOME_DESCRIPTION("Teleport to the faction home"), + COMMAND_HOME_BLOCKED("&c&l[!] You may not teleport to a home that is claimed by &b%1$s"), + + COMMAND_INSPECT_DISABLED_MSG("&c&l[!]&7 Inspect mode is now &cdisabled."), + COMMAND_INSPECT_DISABLED_NOFAC("&c&l[!]&7 Inspect mode is now &cdisabled,&7 because you &cdo not have a faction!"), + COMMAND_INSPECT_ENABLED("&c&l[!]&7 Inspect mode is now &aEnabled."), + COMMAND_INSPECT_HEADER("&c&m---&7Inspect Data&c&m---&c//&7x:{x},y:{y},z:{z}"), + COMMAND_INSPECT_ROW("&c{time} &7// &c{action} &7// &c{player} &7// &c{block-type}"), + COMMAND_INSPECT_NODATA("&c&l[!]&7 &7No Data was found!"), + COMMAND_INSPECT_NOTINCLAIM("&c&l[!]&7 &7You can &conly&7 inspect in &cyour &7claims!"), + COMMAND_INSPECT_BYPASS("&c&l[!]&7 Inspecting in &cbypass&7 mode"), + COMMAND_INSPECT_DESCRIPTION("Inspect blocks!"), + + COMMAND_INVITE_TOINVITE("to invite someone"), + COMMAND_INVITE_FORINVITE("for inviting someone"), + COMMAND_INVITE_CLICKTOJOIN("Click to join!"), + COMMAND_INVITE_INVITEDYOU(" &chas invited you to join "), + COMMAND_INVITE_INVITED("&c&l[!]&7 &c%1$s&7 invited &c%2$s&7 to your faction."), + COMMAND_INVITE_ALREADYMEMBER("&c&l[!]&7 &c%1$s&7 is already a member of&c %2$s"), + COMMAND_INVITE_ALREADYINVITED("&c&l[!]&7 &c%1$s&7 has already been invited"), + COMMAND_INVITE_DESCRIPTION("Invite a player to your faction"), + COMMAND_INVITE_BANNED("&c&l[!]&7 &7%1$s &cis banned &7from your Faction. &cNot &7sending an invite."), + + COMMAND_JOIN_CANNOTFORCE("&c&l[!]&7 You&c do not&7 have permission to &cmove other players&7 into a faction."), + COMMAND_JOIN_SYSTEMFACTION("&c&l[!]&7 Players may only join &cnormal factions&7. This is a &c&lsystem faction&7."), + COMMAND_JOIN_ALREADYMEMBER("&c&l[!]&7 &c%1$s %2$s already a member of&c %3$s"), + COMMAND_JOIN_ATLIMIT(" &c&l[!]&7 The faction &c%1$s &7is at the limit of&c %2$d&7 members, so&c %3$s&7 cannot currently join."), + COMMAND_JOIN_INOTHERFACTION("&c&l[!]&7 &c%1$s &7must leave&c %2$s &7current faction first."), + COMMAND_JOIN_NEGATIVEPOWER("&c&l[!]&7 &c%1$s &7cannot join a faction with a &cnegative power&7 level."), + COMMAND_JOIN_REQUIRESINVITATION("&c&l[!]&7 This faction &crequires&7 an invitation."), + COMMAND_JOIN_ATTEMPTEDJOIN("&c&l[!]&7 &c%1$s&7 tried to join your faction."), + COMMAND_JOIN_TOJOIN("to join a faction"), + COMMAND_JOIN_FORJOIN("for joining a faction"), + COMMAND_JOIN_SUCCESS("&c&l[!]&7 &c%1$s &7successfully joined &c%2$s."), + COMMAND_JOIN_MOVED("&c&l[!]&7 &c%1$s &7moved you into the faction&c %2$s."), + COMMAND_JOIN_JOINED("&c&l[!]&7 &c%1$s &7joined your faction."), + COMMAND_JOIN_JOINEDLOG("&c&l[!]&7 &c%1$s&7 joined the faction&c %2$s."), + COMMAND_JOIN_MOVEDLOG("&c&l[!]&7 &c%1$s &7moved the player&c %2$s &7into the faction&c %3$s&7."), + COMMAND_JOIN_DESCRIPTION("&a&l» &7Join a faction"), + COMMAND_JOIN_BANNED("&c&l[!]&7 You are &cbanned &7from &c%1$s."), + + COMMAND_KICK_CANDIDATES("&c&l[!]&7 Players you can kick: "), + COMMAND_KICK_CLICKTOKICK("Click to kick "), + COMMAND_KICK_SELF("&c&l[!]&7 You &ccannot &7kick&c yourself&7."), + COMMAND_KICK_NONE("&c&l[!]&7 That player&c is not&7 in a faction."), + COMMAND_KICK_NOTMEMBER("&c&l[!]&7 &c%1$s is not a member of %2$s"), + COMMAND_KICK_INSUFFICIENTRANK("&c&l[!]&7 Your rank is &ctoo low &7to kick this player."), + COMMAND_KICK_NEGATIVEPOWER("&c&l[!]&7 You &ccannot &7kick that member until their power is &apositive&7."), + COMMAND_KICK_TOKICK("to kick someone from the faction"), + COMMAND_KICK_FORKICK("for kicking someone from the faction"), + COMMAND_KICK_FACTION("&c&l[!]&7 %1$s&7 kicked %2$s&c from the faction!"), //message given to faction members + COMMAND_KICK_KICKS("&c&l[!]&7 You kicked &c%1$s&7 from the faction&c %2$s&7!"), //kicker perspective + COMMAND_KICK_KICKED("&c&l[!]&7 &c%1$s &7kicked you from&c %2$s&7!"), //kicked player perspective + COMMAND_KICK_DESCRIPTION("Kick a player from the faction"), + + COMMAND_LIST_FACTIONLIST("&c&l[!]&7 Faction List "), + COMMAND_LIST_TOLIST("to list the factions"), + COMMAND_LIST_FORLIST("for listing the factions"), + COMMAND_LIST_ONLINEFACTIONLESS("Online factionless: "), + COMMAND_LIST_DESCRIPTION("&a&l» &7See a list of the factions"), + + COMMAND_LOCK_LOCKED("&c&l[!]&7 Factions is now&c locked"), + COMMAND_LOCK_UNLOCKED("&c&l[!]&7 Factions in now&a unlocked"), + COMMAND_LOCK_DESCRIPTION("Lock all write stuff. Apparently."), + + COMMAND_LOGINS_TOGGLE("&c&l[!]&7 Set login / logout notifications for Faction members to: &c%s"), + COMMAND_LOGINS_DESCRIPTION("Toggle(?) login / logout notifications for Faction members"), + + COMMAND_LOWPOWER_HEADER("&8&m--------&8&8&m---------"), + COMMAND_LOWPOWER_FORMAT("&c{player} &8(&c{player_power}&8/&c{maxpower}&8)"), + COMMAND_LOWPOWER_DESCRIPTION("Shows a list of players in your faction with lower power levels"), + + COMMAND_MAP_TOSHOW("to show the map"), + COMMAND_MAP_FORSHOW("for showing the map"), + COMMAND_MAP_UPDATE_ENABLED("&c&l[!]&7 Map auto update &aENABLED."), + COMMAND_MAP_UPDATE_DISABLED("&c&l[!]&7 Map auto update &cDISABLED."), + COMMAND_MAP_DESCRIPTION("Show the territory map, and set optional auto update"), + + COMMAND_MAPHEIGHT_DESCRIPTION("&eUpdate the lines that /f map sends"), + COMMAND_MAPHEIGHT_SET("&c&l[!]&7 Set /f map lines to &c&a%1$d"), + COMMAND_MAPHEIGHT_CURRENT("&c&l[!]&7 Current &cmapheight: &a%1$d"), + + COMMAND_MOD_CANDIDATES("&c&l[!]&7 Players you can promote: "), + COMMAND_MOD_CLICKTOPROMOTE("Click to promote "), + COMMAND_MOD_NOTMEMBER("&c&l[!]&7 &c%1$s7 is not a member in your faction."), + COMMAND_MOD_NOTADMIN("&c&l[!]&7 You &care not&7 the faction admin."), + COMMAND_MOD_SELF("&c&l[!]&7 The target player&c musn't&7 be yourself."), + COMMAND_MOD_TARGETISADMIN("&c&l[!]&7 The target player is a &cfaction admin.&7 Demote them first."), + COMMAND_MOD_REVOKES("&c&l[!]&7 &7You have &cremoved&7 moderator status from &c%1$s."), + COMMAND_MOD_REVOKED("&c&l[!]&7 &c%1$s&7 is &cno longer&7 moderator in your faction."), + COMMAND_MOD_PROMOTES("&c&l[!]&7 &c%1$s&7 was &cpromoted&7 to moderator in your faction."), + COMMAND_MOD_PROMOTED("&c&l[!]&7 You have promoted&c %1$s&7 to moderator."), + COMMAND_MOD_DESCRIPTION("Give or revoke moderator rights"), + + COMMAND_COLEADER_CANDIDATES("&c&l[!]&7 Players you can promote: "), + COMMAND_COLEADER_CLICKTOPROMOTE("Click to promote "), + COMMAND_COLEADER_NOTMEMBER("&c&l[!]&7 &c%1$s&7 is &cnot a member&7 in your faction."), + COMMAND_COLEADER_NOTADMIN("&c&l[!]&7 You are&c not&7 the faction admin."), + COMMAND_COLEADER_SELF("&c&l[!]&7 The target player&c musn't&7 be yourself."), + COMMAND_COLEADER_TARGETISADMIN("&c&l[!]&7 The target player is a &cfaction admin&7. Demote them first."), + COMMAND_COLEADER_REVOKES("&c&l[!]&7 You have removed &ccoleader &7status from&c %1$s&7."), + COMMAND_COLEADER_REVOKED("&c&l[!]&7 &c%1$s&7 is no longer&c coleader &7in your faction."), + COMMAND_COLEADER_PROMOTES("&c&l[!]&7 &c%1$s&7 was promoted to &ccoleader &7in your faction."), + COMMAND_COLEADER_PROMOTED("&c&l[!]&7 You have &cpromoted &7%1$s to &ccoleader."), + COMMAND_COLEADER_DESCRIPTION("Give or revoke coleader rights"), + + COMMAND_MODIFYPOWER_ADDED("&c&l[!]&7 Added &c%1$f &7power to &c%2$s. &7New total rounded power: &c%3$d"), + COMMAND_MODIFYPOWER_DESCRIPTION("Modify the power of a faction/player"), + + COMMAND_MONEY_LONG("&c&l[!]&7 The faction money commands."), + COMMAND_MONEY_DESCRIPTION("Faction money commands"), + + COMMAND_MONEYBALANCE_SHORT("show faction balance"), + COMMAND_MONEYBALANCE_DESCRIPTION("Show your factions current money balance"), + + COMMAND_MONEYDEPOSIT_DESCRIPTION("Deposit money"), + COMMAND_MONEYDEPOSIT_DEPOSITED("&c&l[!]&7 &c%1$s &7deposited&c %2$s&7 in the faction bank:&c %3$s"), + + COMMAND_MONEYTRANSFERFF_DESCRIPTION("Transfer f -> f"), + COMMAND_MONEYTRANSFERFF_TRANSFER("&c&l[!]&7 &c%1$s&7 transferred&c %2$s &7from the faction &c\"%3$s\"&7 to the faction&c \"%4$s\"&7"), + + COMMAND_MONEYTRANSFERFP_DESCRIPTION("Transfer f -> plugin"), + COMMAND_MONEYTRANSFERFP_TRANSFER("&c&l[!]&7 &c%1$s &7transferred&c %2$s &7from the faction&c \"%3$s\" &7to the player &c\"%4$s\""), + + COMMAND_MONEYTRANSFERPF_DESCRIPTION("Transfer plugin -> f"), + COMMAND_MONEYTRANSFERPF_TRANSFER("&c&l[!]&7 &c%1$s&7 transferred &c%2$s&7 from the player &c\"%3$s\" &7to the faction&c \"%4$s\""), + + COMMAND_MONEYWITHDRAW_DESCRIPTION("Withdraw money"), + COMMAND_MONEYWITHDRAW_WITHDRAW("&c&l[!]&7 &c%1$s&7 withdrew&c %2$s &7from the faction bank:&c %3$s"), + + COMMAND_OPEN_TOOPEN("to open or close the faction"), + COMMAND_OPEN_FOROPEN("for opening or closing the faction"), + COMMAND_OPEN_OPEN("open"), + COMMAND_OPEN_CLOSED("closed"), + COMMAND_OPEN_CHANGES("&c&l[!]&7 &c%1$s&7 changed the faction to &c%2$s&7."), + COMMAND_OPEN_CHANGED("&c&l[!]&7 The faction &c%1$s&7 is now &c%2$s"), + COMMAND_OPEN_DESCRIPTION("Switch if invitation is required to join"), + + COMMAND_OWNER_DISABLED("&c&l[!]&7 Sorry, but &cowned areas &7are &cdisabled &7on this server."), + COMMAND_OWNER_LIMIT("&c&l[!]&7 Sorry, but you have reached the server's &climit&7 of &c%1$d&7 owned areas per faction."), + COMMAND_OWNER_WRONGFACTION("&c&l[!]&7 &7This land is &cnot claimed &7by your faction, so you &ccan't set&7 ownership of it."), + COMMAND_OWNER_NOTCLAIMED("&c&l[!]&7 This land&c is not &7claimed by a faction. Ownership &cis not &7possible."), + COMMAND_OWNER_NOTMEMBER("&c&l[!]&7 &c%1$s&7 is &cnot a member &7of this faction."), + COMMAND_OWNER_CLEARED("&c&l[!]&7 You have &ccleared &7ownership for this claimed area."), + COMMAND_OWNER_REMOVED("&c&l[!]&7 You have&c removed ownership &7of this &cclaimed land&7 from &c%1$s&7."), + COMMAND_OWNER_TOSET("to set ownership of claimed land"), + COMMAND_OWNER_FORSET("for setting ownership of claimed land"), + COMMAND_OWNER_ADDED("&c&l[!]&7 You have added &c%1$s&7 to the &cowner list&7 for this claimed land."), + COMMAND_OWNER_DESCRIPTION("Set ownership of claimed land"), + + COMMAND_KILLHOLOGRAMS_DESCRIPTION("Kill holograms in a radius, admin command"), + + COMMAND_OWNERLIST_DISABLED("&c&l[!]&7 &cSorry, &7but owned areas are &cdisabled&7 on this server."),//dup-> + COMMAND_OWNERLIST_WRONGFACTION("&c&l[!]&7 This land &cis not&7 claimed by your faction."),//eq + COMMAND_OWNERLIST_NOTCLAIMED("&c&l[!]&7 This land is not claimed by any faction, thus no owners."),//eq + COMMAND_OWNERLIST_NONE("&c&l[!]&7 No owners are set here; everyone in the faction has access."), + COMMAND_OWNERLIST_OWNERS("&c&l[!]&7 Current owner(s) of this land: %1$s"), + COMMAND_OWNERLIST_DESCRIPTION("List owner(s) of this claimed land"), + + COMMAND_PAYPALSET_DESCRIPTION("&c&l[!] &7Set the email of your faction to claim rewards."), + COMMAND_PAYPALSEE_DESCRIPTION("&c&l[!] &7View a specific factions paypal email with &b/f &b."), + COMMAND_PAYPALSET_CREATED("&c&l[!] &7Make sure to type &b/f &7!"), + COMMAND_PAYPALSET_SUCCESSFUL("&c&l[!] &7Successfully set your factions email - &b%1$s&7."), + COMMAND_PAYPALSEE_FACTION_PAYPAL("&c&l[!] &b%1$s's &7faction has their paypal set to &b%2$s&7."), + COMMAND_PAYPALSEE_FACTION_NOTSET("&c&l[!] &b%1$s's &7paypal has not yet been set!"), + COMMAND_PAYPALSEE_FACTION_NOFACTION("&c&l[!] &b%1$s &7does not have a faction!"), + + COMMAND_PEACEFUL_DESCRIPTION("&c&l[!]&7Set a faction to peaceful"), + COMMAND_PEACEFUL_YOURS("&c&l[!]&7%1$s has %2$s your faction"), + COMMAND_PEACEFUL_OTHER("&c&l[!]&7%s has %s the faction '%s'."), + COMMAND_PEACEFUL_GRANT("&c&l[!]&7 granted peaceful status to"), + COMMAND_PEACEFUL_REVOKE("removed peaceful status from"), + + COMMAND_PERM_DESCRIPTION("&c&l[!]&7&6Edit or list your Faction's permissions."), + COMMAND_PERM_INVALID_RELATION("&c&l[!]&7Invalid relation defined. Try something like&c 'ally'"), + COMMAND_PERM_INVALID_ACCESS("&c&l[!]&7 Invalid access defined. Try something like &c'allow'"), + COMMAND_PERM_INVALID_ACTION("&c&l[!]&7 Invalid action defined. Try something like &c'build'"), + COMMAND_PERM_SET("&c&l[!]&7 Set permission&c %1$s &7to &c%2$s &7for relation&c %3$s"), + COMMAND_PERM_TOP("RCT MEM OFF ALLY TRUCE NEUT ENEMY"), + + COMMAND_PERMANENT_DESCRIPTION("Toggles a permanent faction option"), + COMMAND_PERMANENT_GRANT("&c&l[!]&7 added permanent status to"), + COMMAND_PERMANENT_REVOKE("&c&l[!]&7 removed permanent status from"), + COMMAND_PERMANENT_YOURS("&c&l[!]&7 &c%1$s&7 has &c%2$s&7 your faction"), + COMMAND_PERMANENT_OTHER("&c&l[!]&7 &c%s &7has &c%s &7the faction &c'%s'."), + COMMAND_PROMOTE_TARGET("&c&l[!]&7 You've been &c%1$s&7 to &c%2$s"), + COMMAND_PROMOTE_SUCCESS("&c&l[!]&7 You successfully&c %1$s %2$s &cto&7 %3$s"), + COMMAND_PROMOTE_PROMOTED("promoted"), + COMMAND_PROMOTE_DEMOTED("demoted"), + COMMAND_PROMOTE_COLEADER_ADMIN("&c&l[!]&7 &cColeaders cant promote players to Admin!"), + + COMMAND_PERMANENTPOWER_DESCRIPTION("Toggle permanent faction power option"), + COMMAND_PERMANENTPOWER_GRANT("added permanentpower status to"), + COMMAND_PERMANENTPOWER_REVOKE("removed permanentpower status from"), + COMMAND_PERMANENTPOWER_SUCCESS("&c&l[!]&7 You&c %s &7%s."), + COMMAND_PERMANENTPOWER_FACTION("&c&l[!]&7 &c%s %s &7your faction"), + + COMMAND_PROMOTE_DESCRIPTION("/f promote "), + COMMAND_PROMOTE_WRONGFACTION("&c&l[!]&7 &c%1$s&7 is &cnot&7 part of your faction."), + COMMAND_NOACCESS("&c&l[!]&7 You don't have access to that."), + COMMAND_PROMOTE_NOTTHATPLAYER("&c&l[!]&7 That player &ccannot&7 be promoted."), + COMMAND_PROMOTE_NOT_ALLOWED("&c&l[!]&7 You cannot promote to the same rank as yourself!"), + COMMAND_PROMOTE_NOTSELF("&c&l[!]&7 You cannot manage your own rank."), + COMMAND_PROMOTE_NOT_SAME("&c&l[!]&7 You cannot promote to the same rank as yourself!"), + + + COMMAND_POWER_TOSHOW("to show player power info"), + COMMAND_POWER_FORSHOW("for showing player power info"), + COMMAND_POWER_POWER("&c&l[!]&7 &c%1$s » &cPower &7/ &cMaxpower&a » &c%2$d &7/&c%3$d %4$s"), + COMMAND_POWER_BONUS(" (bonus: "), + COMMAND_POWER_PENALTY(" (penalty: "), + COMMAND_POWER_DESCRIPTION("&a&l» &7Show player &apower &7info"), + + COMMAND_POWERBOOST_HELP_1("&c&l[!]&7 You must specify \"plugin\" or \"player\" to target a player or \"f\" or \"faction\" to target a faction."), + COMMAND_POWERBOOST_HELP_2("&c&l[!]&7 ex. /f powerboost plugin SomePlayer 0.5 -or- /f powerboost f SomeFaction -5"), + COMMAND_POWERBOOST_INVALIDNUM("You must specify a valid numeric value for the power bonus/penalty amount."), + COMMAND_POWERBOOST_PLAYER("Player \"%1$s\""), + COMMAND_POWERBOOST_FACTION("Faction \"%1$s\""), + COMMAND_POWERBOOST_BOOST("%1$s now has a power bonus/penalty of %2$d to min and max power levels."), + COMMAND_POWERBOOST_BOOSTLOG("%1$s has set the power bonus/penalty for %2$s to %3$d."), + COMMAND_POWERBOOST_DESCRIPTION("Apply permanent power bonus/penalty to specified player or faction"), + + COMMAND_RELATIONS_ALLTHENOPE("&c&l[!]&7 &cNope!You can't."), + COMMAND_RELATIONS_MORENOPE("&c&l[!]&7 &cNope!&7You can't declare a relation to &cyourself"), + COMMAND_RELATIONS_ALREADYINRELATIONSHIP("&c&l[!]&7 You &calready&7 have that relation wish set with&c %1$s."), + COMMAND_RELATIONS_TOMARRY("to change a relation wish"), + COMMAND_RELATIONS_FORMARRY("for changing a relation wish"), + COMMAND_RELATIONS_MUTUAL("&c&l[!]&7 Your faction is now %1$s to %2$s"), + COMMAND_RELATIONS_PEACEFUL("&c&l[!]&7 This will have no effect while your faction is peaceful."), + COMMAND_RELATIONS_PEACEFULOTHER("&c&l[!]&7 This will have &cno effect&7 while their faction is peaceful."), + COMMAND_RELATIONS_DESCRIPTION("Set relation wish to another faction"), + COMMAND_RELATIONS_EXCEEDS_ME("&c&l[!]&7 Failed to set relation wish. You can only have %1$s %2$s."), + COMMAND_RELATIONS_EXCEEDS_THEY("&c&l[!]&7 Failed to set relation wish. They can only have %1$s %2$s."), + + COMMAND_RELATIONS_PROPOSAL_1("&c&l[!]&7&c %1$s &7wishes to be your&c %2$s"), + COMMAND_RELATIONS_PROPOSAL_2("&c&l[!]&7 Type &c/%1$s %2$s %3$s&7 to accept."), + COMMAND_RELATIONS_PROPOSAL_SENT("&c&l[!]&7 &c%1$s&7 were informed that you wish to be &c%2$s"), + + COMMAND_RELOAD_TIME("&c&l[!]&7 Reloaded &call &7configuration files from disk, took &c%1$d ms."), + COMMAND_RELOAD_DESCRIPTION("Reload data file(s) from disk"), + + COMMAND_SAFEUNCLAIMALL_DESCRIPTION("Unclaim all safezone land"), + COMMAND_SAFEUNCLAIMALL_UNCLAIMED("&c&l[!]&7 You unclaimed&c ALL&7 safe zone land."), + COMMAND_SAFEUNCLAIMALL_UNCLAIMEDLOG("&c&l[!]&7 &c%1$s&7 unclaimed all safe zones."), + + COMMAND_SAVEALL_SUCCESS("&c&l[!]&7 &cFactions saved to disk!"), + COMMAND_SAVEALL_DESCRIPTION("Save all data to disk"), + + COMMAND_SCOREBOARD_DESCRIPTION("Scoreboardy things"), + + COMMAND_SETBANNER_SUCCESS("&c&l[!] &7Banner Pattern Set!"), + COMMAND_SETBANNER_NOTBANNER("&c&l[!] &7The item is &cnot&7 a banner!"), + COMMAND_SETBANNER_DESCRIPTION("set banner pattern for your faction"), + + + COMMAND_SETDEFAULTROLE_DESCRIPTION("/f defaultrole - set your Faction's default role."), + COMMAND_SETDEFAULTROLE_NOTTHATROLE("&c&l[!]&7 You cannot set the default to admin."), + COMMAND_SETDEFAULTROLE_SUCCESS("Set default role of your faction to %1$s"), + COMMAND_SETDEFAULTROLE_INVALIDROLE("Couldn't find matching role for %1$s"), + + COMMAND_SETFWARP_NOTCLAIMED("&c&l[!]&7 You can &conly&7 set warps in your faction territory."), + COMMAND_SETFWARP_LIMIT("&c&l[!]&7 Your Faction already has the &cmax amount&7 of warps set &c(%1$d)."), + COMMAND_SETFWARP_SET("&c&l[!]&7 Set warp &c%1$s&7 and password &c'%2$s' &7to your location."), + COMMAND_SETFWARP_TOSET("to set warp"), + COMMAND_SETFWARP_FORSET("for setting warp"), + COMMAND_SETFWARP_DESCRIPTION("Set a faction warp"), + + COMMAND_SETHOME_DISABLED("&c&l[!]&7 &cSorry&7, Faction homes are disabled on this server."), + COMMAND_SETHOME_NOTCLAIMED("&c&l[!]&c Sorry&7, your faction home can only be set inside your &cown &7claimed territory."), + COMMAND_SETHOME_TOSET("to set the faction home"), + COMMAND_SETHOME_FORSET("for setting the faction home"), + COMMAND_SETHOME_SET("&c&l[!]&c %1$s&7 set the home for your faction. You can now use:"), + COMMAND_SETHOME_SETOTHER("&c&l[!]&7 You have set the home for the &c%1$s&7 faction."), + COMMAND_SETHOME_DESCRIPTION("Set the faction home"), + + COMMAND_SETMAXVAULTS_DESCRIPTION("Set max vaults for a Faction."), + COMMAND_SETMAXVAULTS_SUCCESS("&aSet max vaults for &e%s &ato &b%d"), + + COMMAND_VAULT_DESCRIPTION("Open your placed faction vault!"), + COMMAND_VAULT_INVALID("&c&l[!]&7 Your vault was either&c claimed&7, &cbroken&7, or has&c not been&7 placed yet."), + COMMAND_VAULT_OPENING("&c&l[!]&7 Opening faction vault."), + COMMAND_VAULT_NO_HOPPER("&c&l[!] &7You cannot place a hopper near a vault!"), + + COMMAND_GETVAULT_ALREADYSET("&c&l[!]&7 Vault has already been set!"), + COMMAND_GETVAULT_ALREADYHAVE("&c&l[!]&7 You already have a vault in your inventory!"), + COMMAND_GETVAULT_CHESTNEAR("&c&l[!]&7 &7There is a chest or hopper &cnearby"), + COMMAND_GETVAULT_SUCCESS("&cSucessfully set vault."), + COMMAND_GETVAULT_INVALIDLOCATION("&cVault can only be placed in faction land!"), + COMMAND_GETVAULT_DESCRIPTION("Get the faction vault item!"), + COMMAND_GETVAULT_RECEIVE("&cYou have recieved a faction vault!"), + COMMAND_GETVAULT_NOMONEY("&cYou do not have enough money"), + COMMAND_GETVAULT_MONEYTAKE("&c{amount} has been taken from your account"), + + COMMAND_SHOW_NOFACTION_SELF("You are not in a faction"), + COMMAND_SHOW_NOFACTION_OTHER("That's not a faction"), + COMMAND_SHOW_TOSHOW("to show faction information"), + COMMAND_SHOW_FORSHOW("for showing faction information"), + COMMAND_SHOW_DESCRIPTION("Description: %1$s"), + COMMAND_SHOW_PEACEFUL("This faction is Peaceful"), + COMMAND_SHOW_PERMANENT("This faction is permanent, remaining even with no members."), + COMMAND_SHOW_JOINING("Joining: %1$s "), + COMMAND_SHOW_INVITATION("invitation is required"), + COMMAND_SHOW_UNINVITED("no invitation is needed"), + COMMAND_SHOW_NOHOME("n/a"), + COMMAND_SHOW_POWER("Land / Power / Maxpower: %1$d/%2$d/%3$d %4$s."), + COMMAND_SHOW_BONUS(" (bonus: "), + COMMAND_SHOW_PENALTY(" (penalty: "), + COMMAND_SHOW_DEPRECIATED("(%1$s depreciated)"), //This is spelled correctly. + COMMAND_SHOW_LANDVALUE("Total land value: %1$s %2$s"), + COMMAND_SHOW_BANKCONTAINS("Bank contains: %1$s"), + COMMAND_SHOW_ALLIES("Allies: "), + COMMAND_SHOW_ENEMIES("Enemies: "), + COMMAND_SHOW_MEMBERSONLINE("Members online: "), + COMMAND_SHOW_MEMBERSOFFLINE("Members offline: "), + COMMAND_SHOW_COMMANDDESCRIPTION("Show faction information"), + COMMAND_SHOW_DEATHS_TIL_RAIDABLE("DTR: %1$d"), + COMMAND_SHOW_EXEMPT("This faction is exempt and cannot be seen."), + COMMAND_SHOW_NEEDFACTION("&cYou need to join a faction to view your own!"), + + COMMAND_SHOWCLAIMS_HEADER("&8&m-------------&8<{faction}'s claims&8>&8&m-------------"), + COMMAND_SHOWCLAIMS_FORMAT("&8[{world}]:"), + COMMAND_SHOWCLAIMS_CHUNKSFORMAT("&8(&c{x}&8,&c{z}&8)"), + COMMAND_SHOWCLAIMS_DESCRIPTION("show your factions claims!"), + + COMMAND_SHOWINVITES_PENDING("Players with pending invites: "), + COMMAND_SHOWINVITES_CLICKTOREVOKE("Click to revoke invite for %1$s"), + COMMAND_SHOWINVITES_DESCRIPTION("Show pending faction invites"), + + COMMAND_STATUS_FORMAT("%1$s Power: %2$s Last Seen: %3$s"), + COMMAND_STATUS_ONLINE("Online"), + COMMAND_STATUS_AGOSUFFIX(" ago."), + COMMAND_STATUS_DESCRIPTION("Show the status of a player"), + + COMMAND_STEALTH_DESCRIPTION("Enable and Disable Stealth Mode"), + COMMAND_STEALTH_ENABLE("&cStealth &7» &7You will no longer disable nearby players in /f fly."), + COMMAND_STEALTH_DISABLE("&cStealth &8» &7You will now disable other nearby players in /f fly."), + COMMAND_STEALTH_MUSTBEMEMBER("&cStealth &8» &4You must be in a faction to use this command"), + + COMMAND_STUCK_TIMEFORMAT("m 'minutes', s 'seconds.'"), + COMMAND_STUCK_CANCELLED("Teleport cancelled because you were damaged"), + COMMAND_STUCK_OUTSIDE("Teleport cancelled because you left %1$d block radius"), + COMMAND_STUCK_EXISTS("You are already teleporting, you must wait %1$s"), + COMMAND_STUCK_START("Teleport will commence in %s. Don't take or deal damage. "), + COMMAND_STUCK_TELEPORT("Teleported safely to %1$d, %2$d, %3$d."), + COMMAND_STUCK_TOSTUCK("to safely teleport %1$s out"), + COMMAND_STUCK_FORSTUCK("for %1$s initiating a safe teleport out"), + COMMAND_STUCK_DESCRIPTION("Safely teleports you out of enemy faction"), + + COMMAND_SEECHUNK_ENABLED("&cSeechunk enabled!"), + COMMAND_SEECHUNK_DISABLED("&cSeechunk disabled!"), + + + COMMAND_TAG_TAKEN("That tag is already taken"), + COMMAND_TAG_TOCHANGE("to change the faction tag"), + COMMAND_TAG_FORCHANGE("for changing the faction tag"), + COMMAND_TAG_FACTION("%1$s changed your faction tag to %2$s"), + COMMAND_TAG_CHANGED("The faction %1$s changed their name to %2$s."), + COMMAND_TAG_DESCRIPTION("Change the faction tag"), + + COMMAND_TITLE_TOCHANGE("to change a players title"), + COMMAND_TITLE_FORCHANGE("for changing a players title"), + COMMAND_TITLE_CHANGED("%1$s changed a title: %2$s"), + COMMAND_TITLE_DESCRIPTION("Set or remove a players title"), + + COMMAND_TOGGLEALLIANCECHAT_DESCRIPTION("Toggles whether or not you will see alliance chat"), + COMMAND_TOGGLEALLIANCECHAT_IGNORE("Alliance chat is now ignored"), + COMMAND_TOGGLEALLIANCECHAT_UNIGNORE("Alliance chat is no longer ignored"), + + COMMAND_TOGGLESB_DISABLED("You can't toggle scoreboards while they are disabled."), + + COMMAND_TOP_DESCRIPTION("Sort Factions to see the top of some criteria."), + COMMAND_TOP_TOP("Top Factions by %s. Page %d/%d"), + COMMAND_TOP_LINE("%d. &6%s: &c%s"), // Rank. Faction: Value + COMMAND_TOP_INVALID("Could not sort by %s. Try balance, online, members, power or land."), + + COMMAND_TNT_DISABLED_MSG("&cThis command is disabled!"), + COMMAND_TNT_INVALID_NUM("The amount needs to be a number!"), + COMMAND_TNT_DEPOSIT_SUCCESS("&cSuccessfully deposited tnt."), + COMMAND_TNT_EXCEEDLIMIT("&cThis exceeds the bank limit!"), + COMMAND_TNT_WIDTHDRAW_SUCCESS("&cSuccessfully withdrew tnt."), + COMMAND_TNT_WIDTHDRAW_NOTENOUGH("&cNot enough tnt in bank."), + COMMAND_TNT_DEPOSIT_NOTENOUGH("&cNot enough tnt in tnt inventory."), + COMMAND_TNT_AMOUNT("&cYour faction has {amount} tnt in the tnt bank."), + COMMAND_TNT_POSITIVE("&cPlease use positive numbers!"), + COMMAND_TNT_DESCRIPTION("add/widthraw from faction's tnt bank"), + COMMAND_TNT_WIDTHDRAW_NOTENOUGH_SPACE("&cNot enough space in your inventory."), + COMMAND_TNT_ADD_DESCRIPTION("&b/f tnt add&3 "), + COMMAND_TNT_TAKE_DESCRIPTION("&b/f tnt take&3 "), + + COMMAND_TNTFILL_HEADER("&c&l[!] &7Filling tnt in dispensers..."), + COMMAND_TNTFILL_SUCCESS("&c&l[!] &7Filled &c{amount}&7 Tnt in &c{dispensers} &7dispensers"), + COMMAND_TNTFILL_NOTENOUGH("&c&l[!] &7Not enough tnt in inventory."), + COMMAND_TNTFILL_RADIUSMAX("&c&l[!] &7The max radius is {max}"), + COMMAND_TNTFILL_AMOUNTMAX("&c&l[!] &7The max amount is {max}"), + COMMAND_TNTFILL_MOD("&c&l[!] &7Tnt will be used from the faction bank because you dont have the specified amount in your inventory and you are a {role}"), + COMMAND_TNTFILL_DESCRIPTION("Fill tnt into dispensers around you"), + + COMMAND_UNBAN_DESCRIPTION("Unban someone from your Faction"), + COMMAND_UNBAN_NOTBANNED("&7%s &cisn't banned. Not doing anything."), + COMMAND_UNBAN_UNBANNED("&e%1$s &cunbanned &7%2$s"), + COMMAND_UNBAN_TARGET("&aYou were unbanned from &r%s"), + + COMMAND_UNCLAIM_SAFEZONE_SUCCESS("Safe zone was unclaimed."), + COMMAND_UNCLAIM_SAFEZONE_NOPERM("This is a safe zone. You lack permissions to unclaim."), + COMMAND_UNCLAIM_WARZONE_SUCCESS("War zone was unclaimed."), + COMMAND_UNCLAIM_WARZONE_NOPERM("This is a war zone. You lack permissions to unclaim."), + COMMAND_UNCLAIM_UNCLAIMED("%1$s unclaimed some of your land."), + COMMAND_UNCLAIM_UNCLAIMS("You unclaimed this land."), + COMMAND_UNCLAIM_LOG("%1$s unclaimed land at (%2$s) from the faction: %3$s"), + COMMAND_UNCLAIM_WRONGFACTION("You don't own this land."), + COMMAND_UNCLAIM_TOUNCLAIM("to unclaim this land"), + COMMAND_UNCLAIM_FORUNCLAIM("for unclaiming this land"), + COMMAND_UNCLAIM_FACTIONUNCLAIMED("%1$s unclaimed some land."), + COMMAND_UNCLAIM_DESCRIPTION("Unclaim the land where you are standing"), + + COMMAND_UNCLAIMALL_TOUNCLAIM("to unclaim all faction land"), + COMMAND_UNCLAIMALL_FORUNCLAIM("for unclaiming all faction land"), + COMMAND_UNCLAIMALL_UNCLAIMED("%1$s unclaimed ALL of your faction's land."), + COMMAND_UNCLAIMALL_LOG("%1$s unclaimed everything for the faction: %2$s"), + COMMAND_UNCLAIMALL_DESCRIPTION("Unclaim all of your factions land"), + COMMAND_UNCLAIM_CLICKTOUNCLAIM("Click to unclaim &2(%1$d, %2$d)"), + + COMMAND_VERSION_NAME("&c&l[!]&7 &c&k||| &r&4SavageFactions&7 &c&k|||&r &c» &7By ProSavage"), + COMMAND_VERSION_VERSION("&7Version &c» &7%1$s"), + COMMAND_VERSION_DESCRIPTION("Show plugin and translation version information"), + + COMMAND_WARUNCLAIMALL_DESCRIPTION("Unclaim all warzone land"), + COMMAND_WARUNCLAIMALL_SUCCESS("You unclaimed ALL war zone land."), + COMMAND_WARUNCLAIMALL_LOG("%1$s unclaimed all war zones."), + + COMMAND_RULES_DISABLED_MSG("&cThis command is disabled!"), + COMMAND_RULES_DESCRIPTION("set/remove/add rules!"), + COMMAND_RULES_ADD_INVALIDARGS("Please include a rule!"), + COMMAND_RULES_SET_INVALIDARGS("Please include a line number & rule!"), + COMMAND_RULES_REMOVE_INVALIDARGS("Please include a line number!"), + COMMAND_RULES_ADD_SUCCESS("&cRule added successfully!"), + COMMAND_RULES_REMOVE_SUCCESS("&cRule removed successfully!"), + COMMAND_RULES_SET_SUCCESS("&cRule set successfully!"), + COMMAND_RULES_CLEAR_SUCCESS("&cRule cleared successfully!"), + + /** + * Leaving - This is accessed through a command, and so it MAY need a COMMAND_* slug :s + */ + LEAVE_PASSADMIN("You must give the admin role to someone else first."), + LEAVE_NEGATIVEPOWER("You cannot leave until your power is positive."), + LEAVE_TOLEAVE("to leave your faction."), + LEAVE_FORLEAVE("for leaving your faction."), + LEAVE_LEFT("%s left faction %s."), + LEAVE_DISBANDED("%s was disbanded."), + LEAVE_DISBANDEDLOG("The faction %s (%s) was disbanded due to the last player (%s) leaving."), + LEAVE_DESCRIPTION("\\n &a&l» &7Leave your faction"), + + /** + * Claiming - Same as above basically. No COMMAND_* because it's not in a command class, but... + */ + CLAIM_PROTECTED("This land is protected"), + CLAIM_DISABLED("Sorry, this world has land claiming disabled."), + CLAIM_CANTCLAIM("You can't claim land for %s."), + CLAIM_ALREADYOWN("%s already own this land."), + CLAIM_MUSTBE("You must be %s to claim land."), + CLAIM_MEMBERS("Factions must have at least %s members to claim land."), + CLAIM_SAFEZONE("You can not claim a Safe Zone."), + CLAIM_WARZONE("You can not claim a War Zone."), + CLAIM_POWER("You can't claim more land!You need more power!"), + CLAIM_LIMIT("Limit reached. You can't claim more land!"), + CLAIM_ALLY("You can't claim the land of your allies."), + CLAIM_CONTIGIOUS("You can only claim additional land which is connected to your first claim or controlled by another faction!"), + CLAIM_FACTIONCONTIGUOUS("You can only claim additional land which is connected to your first claim!"), + CLAIM_PEACEFUL("%s owns this land. Your faction is peaceful, so you cannot claim land from other factions."), + CLAIM_PEACEFULTARGET("%s owns this land, and is a peaceful faction. You cannot claim land from them."), + CLAIM_THISISSPARTA("%s owns this land and is strong enough to keep it."), + CLAIM_BORDER("You must start claiming land at the border of the territory."), + CLAIM_TOCLAIM("to claim this land"), + CLAIM_FORCLAIM("for claiming this land"), + CLAIM_TOOVERCLAIM("to overclaim this land"), + CLAIM_FOROVERCLAIM("for over claiming this land"), + CLAIM_CLAIMED("%s claimed land for %s from %s."), + CLAIM_CLAIMEDLOG("%s claimed land at (%s) for the faction: %s"), + CLAIM_OVERCLAIM_DISABLED("Over claiming is disabled on this server."), + CLAIM_TOOCLOSETOOTHERFACTION("Your claim is too close to another Faction. Buffer required is %d"), + CLAIM_OUTSIDEWORLDBORDER("Your claim is outside the border."), + CLAIM_OUTSIDEBORDERBUFFER("Your claim is outside the border. %d chunks away world edge required."), + CLAIM_CLICK_TO_CLAIM("Click to try to claim &2(%1$d, %2$d)"), + CLAIM_MAP_OUTSIDEBORDER("&cThis claim is outside the worldborder!"), + CLAIM_YOUAREHERE("You are here"), + CLAIM_NO_TERRITORY_PERM("You do not have permission from your faction leader to do this!"), + + /** + * More generic, or less easily categorisable translations, which may apply to more than one class + */ + GENERIC_YOU("you"), + GENERIC_YOURFACTION("your faction"), + GENERIC_NOPERMISSION("You don't have permission to %1$s."), + GENERIC_FPERM_NOPERMISSION("&7The faction leader does not allow you to &c%1$s."), + GENERIC_DOTHAT("do that"), //Ugh nuke this from high orbit + GENERIC_NOPLAYERMATCH("No player match found for \"%1$s\"."), + GENERIC_NOPLAYERFOUND("No player \"%1$s\" could not be found."), + GENERIC_ARGS_TOOFEW("Too few arguments. Use like this:"), + GENERIC_ARGS_TOOMANY("Strange argument \"%1$s\". Use the command like this:"), + GENERIC_DEFAULTDESCRIPTION("Default faction description :("), + GENERIC_OWNERS("Owner(s): %1$s"), + GENERIC_PUBLICLAND("Public faction land."), + GENERIC_FACTIONLESS("factionless"), + GENERIC_SERVERADMIN("A server admin"), + GENERIC_DISABLED("disabled"), + GENERIC_ENABLED("enabled"), + GENERIC_INFINITY("∞"), + GENERIC_CONSOLEONLY("This command cannot be run as a player."), + GENERIC_PLAYERONLY("This command can only be used by ingame players."), + GENERIC_ASKYOURLEADER(" Ask your leader to:"), + GENERIC_YOUSHOULD("You should:"), + GENERIC_YOUMAYWANT("You may want to: "), + GENERIC_TRANSLATION_VERSION("Translation: %1$s(%2$s,%3$s) State: %4$s"), + GENERIC_TRANSLATION_CONTRIBUTORS("Translation contributors: %1$s"), + GENERIC_TRANSLATION_RESPONSIBLE("Responsible for translation: %1$s"), + GENERIC_FACTIONTAG_TOOSHORT("The faction tag can't be shorter than %1$s chars."), + GENERIC_FACTIONTAG_TOOLONG("The faction tag can't be longer than %s chars."), + GENERIC_FACTIONTAG_ALPHANUMERIC("Faction tag must be alphanumeric. \"%s\" is not allowed."), + GENERIC_PLACEHOLDER(""), + GENERIC_NOTENOUGHMONEY("&cYou dont have enough money!"), + GENERIC_MONEYTAKE("&c{amount} has been taken from your account."), + + + WARBANNER_NOFACTION("&cYou need a faction to use a warbanner!"), + WARBANNER_COOLDOWN("&cThe warbanner is on cooldown for your faction!"), + WARBANNER_INVALIDLOC("&cYou can only use warbanners in enemy land or the warzone"), + + /** + * ASCII compass (for chat map) + */ + COMPASS_SHORT_NORTH("N"), + COMPASS_SHORT_EAST("E"), + COMPASS_SHORT_SOUTH("S"), + COMPASS_SHORT_WEST("W"), + + /** + * Chat modes + */ + CHAT_MOD("mod chat"), + CHAT_FACTION("faction chat"), + CHAT_ALLIANCE("alliance chat"), + CHAT_TRUCE("truce chat"), + CHAT_PUBLIC("public chat"), + + /** + * Economy stuff + */ + + ECON_OFF("no %s"), // no balance, no value, no refund, etc + ECON_FORMAT("###,###.###"), + + /** + * Relations + */ + RELATION_MEMBER_SINGULAR("member"), + RELATION_MEMBER_PLURAL("members"), + RELATION_ALLY_SINGULAR("ally"), + RELATION_ALLY_PLURAL("allies"), + RELATION_TRUCE_SINGULAR("truce"), + RELATION_TRUCE_PLURAL("truces"), + RELATION_NEUTRAL_SINGULAR("neutral"), + RELATION_NEUTRAL_PLURAL("neutrals"), + RELATION_ENEMY_SINGULAR("enemy"), + RELATION_ENEMY_PLURAL("enemies"), + + /** + * Roles + */ + ROLE_LEADER("leader"), + ROLE_COLEADER("coleader"), + ROLE_MODERATOR("moderator"), + ROLE_NORMAL("normal member"), + ROLE_RECRUIT("recruit"), + + /** + * Region types. + */ + REGION_SAFEZONE("safezone"), + REGION_WARZONE("warzone"), + REGION_WILDERNESS("wilderness"), + + REGION_PEACEFUL("peaceful territory"), + /** + * In the player and entity listeners + */ + PLAYER_CANTHURT("You may not harm other players in %s"), + PLAYER_SAFEAUTO("This land is now a safe zone."), + PLAYER_WARAUTO("This land is now a war zone."), + PLAYER_OUCH("Ouch, that is starting to hurt. You should give it a rest."), + PLAYER_USE_WILDERNESS("You can't use %s in the wilderness."), + PLAYER_USE_SAFEZONE("You can't use %s in a safe zone."), + PLAYER_USE_WARZONE("You can't use %s in a war zone."), + PLAYER_USE_TERRITORY("You can't %s in the territory of %s."), + PLAYER_USE_OWNED("You can't use %s in this territory, it is owned by: %s."), + PLAYER_COMMAND_WARZONE("You can't use the command '%s' in warzone."), + PLAYER_COMMAND_NEUTRAL("You can't use the command '%s' in neutral territory."), + PLAYER_COMMAND_ENEMY("You can't use the command '%s' in enemy territory."), + PLAYER_COMMAND_PERMANENT("You can't use the command '%s' because you are in a permanent faction."), + PLAYER_COMMAND_ALLY("You can't use the command '%s' in ally territory."), + PLAYER_COMMAND_WILDERNESS("You can't use the command '%s' in the wilderness."), + + PLAYER_POWER_NOLOSS_PEACEFUL("You didn't lose any power since you are in a peaceful faction."), + PLAYER_POWER_NOLOSS_WORLD("You didn't lose any power due to the world you died in."), + PLAYER_POWER_NOLOSS_WILDERNESS("You didn't lose any power since you were in the wilderness."), + PLAYER_POWER_NOLOSS_WARZONE("You didn't lose any power since you were in a war zone."), + PLAYER_POWER_LOSS_WARZONE("The world you are in has power loss normally disabled, but you still lost power since you were in a war zone.\nYour power is now %d / %d"), + PLAYER_POWER_NOW("Your power is now %d / %d"), + + PLAYER_PVP_LOGIN("You can't hurt other players for %d seconds after logging in."), + PLAYER_PVP_REQUIREFACTION("You can't hurt other players until you join a faction."), + PLAYER_PVP_FACTIONLESS("You can't hurt players who are not currently in a faction."), + PLAYER_PVP_PEACEFUL("Peaceful players cannot participate in combat."), + PLAYER_PVP_NEUTRAL("You can't hurt neutral factions. Declare them as an enemy."), + PLAYER_PVP_CANTHURT("You can't hurt %s."), + + PLAYER_PVP_NEUTRALFAIL("You can't hurt %s in their own territory unless you declare them as an enemy."), + PLAYER_PVP_TRIED("%s tried to hurt you."), + + /** + * Strings lying around in other bits of the plugins + */ + NOPAGES("Sorry. No Pages available."), + INVALIDPAGE("Invalid page. Must be between 1 and %1$d"), + + /** + * The ones here before I started messing around with this + */ + TITLE("title", "&bFactions &0|&r"), + WILDERNESS("wilderness", "&2Wilderness"), + WILDERNESS_DESCRIPTION("wilderness-description", ""), + WARZONE("warzone", "&4Warzone"), + WARZONE_DESCRIPTION("warzone-description", "Not the safest place to be."), + SAFEZONE("safezone", "&6Safezone"), + SAFEZONE_DESCRIPTION("safezone-description", "Free from pvp and monsters."), + TOGGLE_SB("toggle-sb", "You now have scoreboards set to {value}"), + FACTION_LEAVE("faction-leave", "Leaving %1$s, Entering %2$s"), + FACTIONS_ANNOUNCEMENT_TOP("faction-announcement-top", "&d--Unread Faction Announcements--"), + FACTIONS_ANNOUNCEMENT_BOTTOM("faction-announcement-bottom", "&d--Unread Faction Announcements--"), + DEFAULT_PREFIX("default-prefix", "{relationcolor}[{faction}]"), + FACTION_LOGIN("faction-login", "&e%1$s &9logged in."), + FACTION_LOGOUT("faction-logout", "&e%1$s &9logged out.."), + NOFACTION_PREFIX("nofactions-prefix", "&6[&a4-&6]&r"), + DATE_FORMAT("date-format", "MM/d/yy h:ma"), // 3/31/15 07:49AM + + /** + * Raidable is used in multiple places. Allow more than just true/false. + */ + RAIDABLE_TRUE("raidable-true", "true"), + RAIDABLE_FALSE("raidable-false", "false"), + /** + * Warmups + */ + WARMUPS_NOTIFY_FLIGHT("&eFlight will enable in &d%2$d &eseconds."), + WARMUPS_NOTIFY_TELEPORT("&eYou will teleport to &d%1$s &ein &d%2$d &eseconds."), + WARMUPS_ALREADY("&cYou are already warming up."), + WARMUPS_CANCELLED("&cYou have cancelled your warmup."); + + public static SimpleDateFormat sdf; + private static YamlConfiguration LANG; + private String path; + private String def; + + /** + * Lang enum constructor. + * + * @param path The string path. + * @param start The default string. + */ + TL(String path, String start) { + this.path = path; + this.def = start; + } + + /** + * Lang enum constructor. Use this when your desired path simply exchanges '_' for '.' + * + * @param start The default string. + */ + TL(String start) { + this.path = this.name().replace('_', '.'); + if (this.path.startsWith(".")) { + path = "root" + path; + } + this.def = start; + } + + /** + * Set the {@code YamlConfiguration} to use. + * + * @param config The config to set. + */ + public static void setFile(YamlConfiguration config) { + LANG = config; + sdf = new SimpleDateFormat(DATE_FORMAT.toString()); + } + + @Override + public String toString() { + return ChatColor.translateAlternateColorCodes('&', LANG.getString(this.path, def)) + (this == TITLE ? " " : ""); + } + + public String format(Object... args) { + return String.format(toString(), args); + } + + /** + * Get the default value of the path. + * + * @return The default value of the path. + */ + public String getDefault() { + return this.def; + } + + /** + * Get the path to the string. + * + * @return The path to the string. + */ + public String getPath() { + return this.path; + } } 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 6d726ab6..3392ec7d 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagReplacer.java @@ -17,284 +17,284 @@ import java.util.UUID; */ public enum TagReplacer { - /** - * Fancy variables, used by f show - */ - ALLIES_LIST(TagType.FANCY, "{allies-list}"), - ONLINE_LIST(TagType.FANCY, "{online-list}"), - ENEMIES_LIST(TagType.FANCY, "{enemies-list}"), - TRUCES_LIST(TagType.FANCY, "{truces-list}"), - OFFLINE_LIST(TagType.FANCY, "{offline-list}"), + /** + * Fancy variables, used by f show + */ + ALLIES_LIST(TagType.FANCY, "{allies-list}"), + ONLINE_LIST(TagType.FANCY, "{online-list}"), + ENEMIES_LIST(TagType.FANCY, "{enemies-list}"), + TRUCES_LIST(TagType.FANCY, "{truces-list}"), + OFFLINE_LIST(TagType.FANCY, "{offline-list}"), - /** - * Player variables, require a player - */ - PLAYER_GROUP(TagType.PLAYER, "{group}"), - LAST_SEEN(TagType.PLAYER, "{lastSeen}"), - PLAYER_BALANCE(TagType.PLAYER, "{balance}"), - PLAYER_POWER(TagType.PLAYER, "{player-power}"), - PLAYER_MAXPOWER(TagType.PLAYER, "{player-maxpower}"), - PLAYER_KILLS(TagType.PLAYER, "{player-kills}"), - PLAYER_DEATHS(TagType.PLAYER, "{player-deaths}"), + /** + * Player variables, require a player + */ + PLAYER_GROUP(TagType.PLAYER, "{group}"), + LAST_SEEN(TagType.PLAYER, "{lastSeen}"), + PLAYER_BALANCE(TagType.PLAYER, "{balance}"), + PLAYER_POWER(TagType.PLAYER, "{player-power}"), + PLAYER_MAXPOWER(TagType.PLAYER, "{player-maxpower}"), + PLAYER_KILLS(TagType.PLAYER, "{player-kills}"), + PLAYER_DEATHS(TagType.PLAYER, "{player-deaths}"), - /** - * Faction variables, require at least a player - */ - HOME_X(TagType.FACTION, "{x}"), - HOME_Y(TagType.FACTION, "{y}"), - HOME_Z(TagType.FACTION, "{z}"), - CHUNKS(TagType.FACTION, "{chunks}"), - WARPS(TagType.FACTION, "{warps}"), - HEADER(TagType.FACTION, "{header}"), - POWER(TagType.FACTION, "{power}"), - MAX_POWER(TagType.FACTION, "{maxPower}"), - POWER_BOOST(TagType.FACTION, "{power-boost}"), - LEADER(TagType.FACTION, "{leader}"), - JOINING(TagType.FACTION, "{joining}"), - FACTION(TagType.FACTION, "{faction}"), - PLAYER_NAME(TagType.FACTION, "{name}"), - HOME_WORLD(TagType.FACTION, "{world}"), - RAIDABLE(TagType.FACTION, "{raidable}"), - PEACEFUL(TagType.FACTION, "{peaceful}"), - PERMANENT(TagType.FACTION, "permanent"), // no braces needed - TIME_LEFT(TagType.FACTION, "{time-left}"), - LAND_VALUE(TagType.FACTION, "{land-value}"), - DESCRIPTION(TagType.FACTION, "{description}"), - CREATE_DATE(TagType.FACTION, "{create-date}"), - LAND_REFUND(TagType.FACTION, "{land-refund}"), - BANK_BALANCE(TagType.FACTION, "{faction-balance}"), - ALLIES_COUNT(TagType.FACTION, "{allies}"), - ENEMIES_COUNT(TagType.FACTION, "{enemies}"), - TRUCES_COUNT(TagType.FACTION, "{truces}"), - ONLINE_COUNT(TagType.FACTION, "{online}"), - OFFLINE_COUNT(TagType.FACTION, "{offline}"), - FACTION_SIZE(TagType.FACTION, "{members}"), - FACTION_KILLS(TagType.FACTION, "{faction-kills}"), - FACTION_DEATHS(TagType.FACTION, "{faction-deaths}"), - FACTION_BANCOUNT(TagType.FACTION, "{faction-bancount}"), + /** + * Faction variables, require at least a player + */ + HOME_X(TagType.FACTION, "{x}"), + HOME_Y(TagType.FACTION, "{y}"), + HOME_Z(TagType.FACTION, "{z}"), + CHUNKS(TagType.FACTION, "{chunks}"), + WARPS(TagType.FACTION, "{warps}"), + HEADER(TagType.FACTION, "{header}"), + POWER(TagType.FACTION, "{power}"), + MAX_POWER(TagType.FACTION, "{maxPower}"), + POWER_BOOST(TagType.FACTION, "{power-boost}"), + LEADER(TagType.FACTION, "{leader}"), + JOINING(TagType.FACTION, "{joining}"), + FACTION(TagType.FACTION, "{faction}"), + PLAYER_NAME(TagType.FACTION, "{name}"), + HOME_WORLD(TagType.FACTION, "{world}"), + RAIDABLE(TagType.FACTION, "{raidable}"), + PEACEFUL(TagType.FACTION, "{peaceful}"), + PERMANENT(TagType.FACTION, "permanent"), // no braces needed + TIME_LEFT(TagType.FACTION, "{time-left}"), + LAND_VALUE(TagType.FACTION, "{land-value}"), + DESCRIPTION(TagType.FACTION, "{description}"), + CREATE_DATE(TagType.FACTION, "{create-date}"), + LAND_REFUND(TagType.FACTION, "{land-refund}"), + BANK_BALANCE(TagType.FACTION, "{faction-balance}"), + ALLIES_COUNT(TagType.FACTION, "{allies}"), + ENEMIES_COUNT(TagType.FACTION, "{enemies}"), + TRUCES_COUNT(TagType.FACTION, "{truces}"), + ONLINE_COUNT(TagType.FACTION, "{online}"), + OFFLINE_COUNT(TagType.FACTION, "{offline}"), + FACTION_SIZE(TagType.FACTION, "{members}"), + FACTION_KILLS(TagType.FACTION, "{faction-kills}"), + FACTION_DEATHS(TagType.FACTION, "{faction-deaths}"), + FACTION_BANCOUNT(TagType.FACTION, "{faction-bancount}"), - /** - * General variables, require no faction or player - */ - MAX_WARPS(TagType.GENERAL, "{max-warps}"), - MAX_ALLIES(TagType.GENERAL, "{max-allies}"), - MAX_ENEMIES(TagType.GENERAL, "{max-enemies}"), - MAX_TRUCES(TagType.GENERAL, "{max-truces}"), - FACTIONLESS(TagType.GENERAL, "{factionless}"), - TOTAL_ONLINE(TagType.GENERAL, "{total-online}"); + /** + * General variables, require no faction or player + */ + MAX_WARPS(TagType.GENERAL, "{max-warps}"), + MAX_ALLIES(TagType.GENERAL, "{max-allies}"), + MAX_ENEMIES(TagType.GENERAL, "{max-enemies}"), + MAX_TRUCES(TagType.GENERAL, "{max-truces}"), + FACTIONLESS(TagType.GENERAL, "{factionless}"), + TOTAL_ONLINE(TagType.GENERAL, "{total-online}"); - private TagType type; - private String tag; + private TagType type; + private String tag; - TagReplacer(TagType type, String tag) { - this.type = type; - this.tag = tag; - } + TagReplacer(TagType type, String tag) { + this.type = type; + this.tag = tag; + } - /** - * Returns a list of all the variables we can use for this type
- * - * @param type the type we want - * @return a list of all the variables with this type - */ - protected static List getByType(TagType type) { - List tagReplacers = new ArrayList<>(); - for (TagReplacer tagReplacer : TagReplacer.values()) { - if (type == TagType.FANCY) { - if (tagReplacer.type == TagType.FANCY) { - tagReplacers.add(tagReplacer); - } - } else if (tagReplacer.type.id >= type.id) { - tagReplacers.add(tagReplacer); - } - } - return tagReplacers; - } + /** + * Returns a list of all the variables we can use for this type
+ * + * @param type the type we want + * @return a list of all the variables with this type + */ + protected static List getByType(TagType type) { + List tagReplacers = new ArrayList<>(); + for (TagReplacer tagReplacer : TagReplacer.values()) { + if (type == TagType.FANCY) { + if (tagReplacer.type == TagType.FANCY) { + tagReplacers.add(tagReplacer); + } + } else if (tagReplacer.type.id >= type.id) { + tagReplacers.add(tagReplacer); + } + } + return tagReplacers; + } - /** - * Protected access to this generic server related variable - * - * @return value for this generic server related variable
- */ - protected String getValue() { - switch (this) { - case TOTAL_ONLINE: - return String.valueOf(Bukkit.getOnlinePlayers().size()); - case FACTIONLESS: - return String.valueOf(Factions.getInstance().getWilderness().getFPlayersWhereOnline(true).size()); - case MAX_ALLIES: - if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-relations.ally", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_ENEMIES: - if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-relations.enemy", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_TRUCES: - if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", true)) { - return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-relations.truce", 10)); - } - return TL.GENERIC_INFINITY.toString(); - case MAX_WARPS: - return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-warps", 5)); - default: - } - return null; - } + /** + * Protected access to this generic server related variable + * + * @return value for this generic server related variable
+ */ + protected String getValue() { + switch (this) { + case TOTAL_ONLINE: + return String.valueOf(Bukkit.getOnlinePlayers().size()); + case FACTIONLESS: + return String.valueOf(Factions.getInstance().getWilderness().getFPlayersWhereOnline(true).size()); + case MAX_ALLIES: + if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-relations.ally", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_ENEMIES: + if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-relations.enemy", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_TRUCES: + if (SavageFactions.plugin.getConfig().getBoolean("max-relations.enabled", true)) { + return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-relations.truce", 10)); + } + return TL.GENERIC_INFINITY.toString(); + case MAX_WARPS: + return String.valueOf(SavageFactions.plugin.getConfig().getInt("max-warps", 5)); + default: + } + return null; + } - /** - * Gets the value for this (as in the instance this is called from) variable! - * - * @param fac Target faction - * @param fp Target player (can be null) - * @return the value for this enum! - */ - protected String getValue(Faction fac, FPlayer fp) { - if (this.type == TagType.GENERAL) { - return getValue(); - } + /** + * Gets the value for this (as in the instance this is called from) variable! + * + * @param fac Target faction + * @param fp Target player (can be null) + * @return the value for this enum! + */ + protected String getValue(Faction fac, FPlayer fp) { + if (this.type == TagType.GENERAL) { + return getValue(); + } - boolean minimal = SavageFactions.plugin.getConfig().getBoolean("minimal-show", false); + boolean minimal = SavageFactions.plugin.getConfig().getBoolean("minimal-show", false); - if (fp != null) { - switch (this) { - case HEADER: - return SavageFactions.plugin.txt.titleize(fac.getTag(fp)); - case PLAYER_NAME: - return fp.getName(); - case FACTION: - return !fac.isWilderness() ? fac.getTag(fp) : TL.GENERIC_FACTIONLESS.toString(); - case LAST_SEEN: - 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); - case PLAYER_GROUP: - return SavageFactions.plugin.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))); - case PLAYER_BALANCE: - return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance"); - case PLAYER_POWER: - return String.valueOf(fp.getPowerRounded()); - case PLAYER_MAXPOWER: - return String.valueOf(fp.getPowerMaxRounded()); - case PLAYER_KILLS: - return String.valueOf(fp.getKills()); - case PLAYER_DEATHS: - return String.valueOf(fp.getDeaths()); - default: - } - } + if (fp != null) { + switch (this) { + case HEADER: + return SavageFactions.plugin.txt.titleize(fac.getTag(fp)); + case PLAYER_NAME: + return fp.getName(); + case FACTION: + return !fac.isWilderness() ? fac.getTag(fp) : TL.GENERIC_FACTIONLESS.toString(); + case LAST_SEEN: + 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); + case PLAYER_GROUP: + return SavageFactions.plugin.getPrimaryGroup(Bukkit.getOfflinePlayer(UUID.fromString(fp.getId()))); + case PLAYER_BALANCE: + return Econ.isSetup() ? Econ.getFriendlyBalance(fp) : TL.ECON_OFF.format("balance"); + case PLAYER_POWER: + return String.valueOf(fp.getPowerRounded()); + case PLAYER_MAXPOWER: + return String.valueOf(fp.getPowerMaxRounded()); + case PLAYER_KILLS: + return String.valueOf(fp.getKills()); + case PLAYER_DEATHS: + return String.valueOf(fp.getDeaths()); + default: + } + } - switch (this) { - case DESCRIPTION: - return fac.getDescription(); - case FACTION: - return fac.getTag(); - case JOINING: - return (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); - case PEACEFUL: - return fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; - case PERMANENT: - return fac.isPermanent() ? "permanent" : "{notPermanent}"; - case CHUNKS: - return String.valueOf(fac.getLandRounded()); - case POWER: - return String.valueOf(fac.getPowerRounded()); - case MAX_POWER: - return String.valueOf(fac.getPowerMaxRounded()); - case POWER_BOOST: - double powerBoost = fac.getPowerBoost(); - return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); - case LEADER: - FPlayer fAdmin = fac.getFPlayerAdmin(); - return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); - case WARPS: - return String.valueOf(fac.getWarps().size()); - case CREATE_DATE: - return TL.sdf.format(fac.getFoundedDate()); - case RAIDABLE: - boolean raid = SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && fac.getLandRounded() >= fac.getPowerRounded(); - return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); - case HOME_WORLD: - return fac.hasHome() ? fac.getHome().getWorld().getName() : minimal ? null : "{ig}"; - case HOME_X: - return fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : minimal ? null : "{ig}"; - case HOME_Y: - return fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : minimal ? null : "{ig}"; - case HOME_Z: - return fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : minimal ? null : "{ig}"; - case LAND_VALUE: - return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("value"); - case LAND_REFUND: - 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.moneyString(Econ.getBalance(fac.getAccountId())) : minimal ? null : TL.ECON_OFF.format("balance"); - } - return minimal ? null : TL.ECON_OFF.format("balance"); - case ALLIES_COUNT: - return String.valueOf(fac.getRelationCount(Relation.ALLY)); - case ENEMIES_COUNT: - return String.valueOf(fac.getRelationCount(Relation.ENEMY)); - case TRUCES_COUNT: - return String.valueOf(fac.getRelationCount(Relation.TRUCE)); - case ONLINE_COUNT: - if (fp != null && fp.isOnline()) { - return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); - } else { - // Only console should ever get here. - return String.valueOf(fac.getFPlayersWhereOnline(true).size()); - } - case OFFLINE_COUNT: - return String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size()); - case FACTION_SIZE: - return String.valueOf(fac.getFPlayers().size()); - case FACTION_KILLS: - return String.valueOf(fac.getKills()); - case FACTION_DEATHS: - return String.valueOf(fac.getDeaths()); - case FACTION_BANCOUNT: - return String.valueOf(fac.getBannedPlayers().size()); - default: - } - return null; - } + switch (this) { + case DESCRIPTION: + return fac.getDescription(); + case FACTION: + return fac.getTag(); + case JOINING: + return (fac.getOpen() ? TL.COMMAND_SHOW_UNINVITED.toString() : TL.COMMAND_SHOW_INVITATION.toString()); + case PEACEFUL: + return fac.isPeaceful() ? Conf.colorNeutral + TL.COMMAND_SHOW_PEACEFUL.toString() : ""; + case PERMANENT: + return fac.isPermanent() ? "permanent" : "{notPermanent}"; + case CHUNKS: + return String.valueOf(fac.getLandRounded()); + case POWER: + return String.valueOf(fac.getPowerRounded()); + case MAX_POWER: + return String.valueOf(fac.getPowerMaxRounded()); + case POWER_BOOST: + double powerBoost = fac.getPowerBoost(); + return (powerBoost == 0.0) ? "" : (powerBoost > 0.0 ? TL.COMMAND_SHOW_BONUS.toString() : TL.COMMAND_SHOW_PENALTY.toString() + powerBoost + ")"); + case LEADER: + FPlayer fAdmin = fac.getFPlayerAdmin(); + return fAdmin == null ? "Server" : fAdmin.getName().substring(0, fAdmin.getName().length() > 14 ? 13 : fAdmin.getName().length()); + case WARPS: + return String.valueOf(fac.getWarps().size()); + case CREATE_DATE: + return TL.sdf.format(fac.getFoundedDate()); + case RAIDABLE: + boolean raid = SavageFactions.plugin.getConfig().getBoolean("hcf.raidable", false) && fac.getLandRounded() >= fac.getPowerRounded(); + return raid ? TL.RAIDABLE_TRUE.toString() : TL.RAIDABLE_FALSE.toString(); + case HOME_WORLD: + return fac.hasHome() ? fac.getHome().getWorld().getName() : minimal ? null : "{ig}"; + case HOME_X: + return fac.hasHome() ? String.valueOf(fac.getHome().getBlockX()) : minimal ? null : "{ig}"; + case HOME_Y: + return fac.hasHome() ? String.valueOf(fac.getHome().getBlockY()) : minimal ? null : "{ig}"; + case HOME_Z: + return fac.hasHome() ? String.valueOf(fac.getHome().getBlockZ()) : minimal ? null : "{ig}"; + case LAND_VALUE: + return Econ.shouldBeUsed() ? Econ.moneyString(Econ.calculateTotalLandValue(fac.getLandRounded())) : minimal ? null : TL.ECON_OFF.format("value"); + case LAND_REFUND: + 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.moneyString(Econ.getBalance(fac.getAccountId())) : minimal ? null : TL.ECON_OFF.format("balance"); + } + return minimal ? null : TL.ECON_OFF.format("balance"); + case ALLIES_COUNT: + return String.valueOf(fac.getRelationCount(Relation.ALLY)); + case ENEMIES_COUNT: + return String.valueOf(fac.getRelationCount(Relation.ENEMY)); + case TRUCES_COUNT: + return String.valueOf(fac.getRelationCount(Relation.TRUCE)); + case ONLINE_COUNT: + if (fp != null && fp.isOnline()) { + return String.valueOf(fac.getFPlayersWhereOnline(true, fp).size()); + } else { + // Only console should ever get here. + return String.valueOf(fac.getFPlayersWhereOnline(true).size()); + } + case OFFLINE_COUNT: + return String.valueOf(fac.getFPlayers().size() - fac.getOnlinePlayers().size()); + case FACTION_SIZE: + return String.valueOf(fac.getFPlayers().size()); + case FACTION_KILLS: + return String.valueOf(fac.getKills()); + case FACTION_DEATHS: + return String.valueOf(fac.getDeaths()); + case FACTION_BANCOUNT: + return String.valueOf(fac.getBannedPlayers().size()); + default: + } + return null; + } - /** - * @param original raw line with variables - * @param value what to replace var in raw line with - * @return the string with the new value - */ - public String replace(String original, String value) { - return original.replace(tag, value); - } + /** + * @param original raw line with variables + * @param value what to replace var in raw line with + * @return the string with the new value + */ + public String replace(String original, String value) { + return original.replace(tag, value); + } - /** - * @param toSearch raw line with variables - * @return if the raw line contains this enums variable - */ - public boolean contains(String toSearch) { - if (tag == null) { - return false; - } - return toSearch.contains(tag); - } + /** + * @param toSearch raw line with variables + * @return if the raw line contains this enums variable + */ + public boolean contains(String toSearch) { + if (tag == null) { + return false; + } + return toSearch.contains(tag); + } - /** - * Gets the tag associated with this enum that we should replace - * - * @return the {....} variable that is located in config - */ - public String getTag() { - return this.tag; - } + /** + * Gets the tag associated with this enum that we should replace + * + * @return the {....} variable that is located in config + */ + public String getTag() { + return this.tag; + } - protected enum TagType { - FANCY(0), PLAYER(1), FACTION(2), GENERAL(3); - public int id; + protected enum TagType { + FANCY(0), PLAYER(1), FACTION(2), GENERAL(3); + public int id; - TagType(int id) { - this.id = id; - } - } + TagType(int id) { + this.id = id; + } + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java index da621d69..e0639037 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TagUtil.java @@ -19,250 +19,250 @@ import static com.massivecraft.factions.zcore.util.TagReplacer.TagType; public class TagUtil { - private static final int ARBITRARY_LIMIT = 25000; + private static final int ARBITRARY_LIMIT = 25000; - /** - * Replaces all variables in a plain raw line for a faction - * - * @param faction for faction - * @param line raw line from config with variables to replace for - * @return clean line - */ - public static String parsePlain(Faction faction, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FACTION)) { - if (tagReplacer.contains(line)) { - line = tagReplacer.replace(line, tagReplacer.getValue(faction, null)); - } - } - return line; - } + /** + * Replaces all variables in a plain raw line for a faction + * + * @param faction for faction + * @param line raw line from config with variables to replace for + * @return clean line + */ + public static String parsePlain(Faction faction, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FACTION)) { + if (tagReplacer.contains(line)) { + line = tagReplacer.replace(line, tagReplacer.getValue(faction, null)); + } + } + return line; + } - /** - * Replaces all variables in a plain raw line for a player - * - * @param fplayer for player - * @param line raw line from config with variables to replace for - * @return clean line - */ - public static String parsePlain(FPlayer fplayer, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { - if (tagReplacer.contains(line)) { - String rep = tagReplacer.getValue(fplayer.getFaction(), fplayer); - if (rep == null) { - rep = ""; // this should work, but it's not a good way to handle whatever is going wrong - } - line = tagReplacer.replace(line, rep); - } - } - return line; - } + /** + * Replaces all variables in a plain raw line for a player + * + * @param fplayer for player + * @param line raw line from config with variables to replace for + * @return clean line + */ + public static String parsePlain(FPlayer fplayer, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { + if (tagReplacer.contains(line)) { + String rep = tagReplacer.getValue(fplayer.getFaction(), fplayer); + if (rep == null) { + rep = ""; // this should work, but it's not a good way to handle whatever is going wrong + } + line = tagReplacer.replace(line, rep); + } + } + return line; + } - /** - * Replaces all variables in a plain raw line for a faction, using relations from fplayer - * - * @param faction for faction - * @param fplayer from player - * @param line raw line from config with variables to replace for - * @return clean line - */ - public static String parsePlain(Faction faction, FPlayer fplayer, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { - if (tagReplacer.contains(line)) { - String value = tagReplacer.getValue(faction, fplayer); - if (value != null) { - line = tagReplacer.replace(line, value); - } else { - return null; // minimal show, entire line to be ignored - } - } - } - return line; - } + /** + * Replaces all variables in a plain raw line for a faction, using relations from fplayer + * + * @param faction for faction + * @param fplayer from player + * @param line raw line from config with variables to replace for + * @return clean line + */ + public static String parsePlain(Faction faction, FPlayer fplayer, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.PLAYER)) { + if (tagReplacer.contains(line)) { + String value = tagReplacer.getValue(faction, fplayer); + if (value != null) { + line = tagReplacer.replace(line, value); + } else { + return null; // minimal show, entire line to be ignored + } + } + } + return line; + } - /** - * Scan a line and parse the fancy variable into a fancy list - * - * @param faction for faction (viewers faction) - * @param fme for player (viewer) - * @param line fancy message prefix - * @return list of fancy msgs - */ - public static List parseFancy(Faction faction, FPlayer fme, String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { - if (tagReplacer.contains(line)) { - String clean = line.replace(tagReplacer.getTag(), ""); // remove tag - return getFancy(faction, fme, tagReplacer, clean); - } - } - return null; - } + /** + * Scan a line and parse the fancy variable into a fancy list + * + * @param faction for faction (viewers faction) + * @param fme for player (viewer) + * @param line fancy message prefix + * @return list of fancy msgs + */ + public static List parseFancy(Faction faction, FPlayer fme, String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { + if (tagReplacer.contains(line)) { + String clean = line.replace(tagReplacer.getTag(), ""); // remove tag + return getFancy(faction, fme, tagReplacer, clean); + } + } + return null; + } - public static String parsePlaceholders(Player player, String line) { - if (SavageFactions.plugin.isClipPlaceholderAPIHooked() && player.isOnline()) { - line = PlaceholderAPI.setPlaceholders(player, line); - } + public static String parsePlaceholders(Player player, String line) { + if (SavageFactions.plugin.isClipPlaceholderAPIHooked() && player.isOnline()) { + line = PlaceholderAPI.setPlaceholders(player, line); + } - if (SavageFactions.plugin.isMVdWPlaceholderAPIHooked() && player.isOnline()) { - line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); - } + if (SavageFactions.plugin.isMVdWPlaceholderAPIHooked() && player.isOnline()) { + line = be.maximvdw.placeholderapi.PlaceholderAPI.replacePlaceholders(player, line); + } - return line; - } + return line; + } - /** - * Checks if a line has fancy variables - * - * @param line raw line from config with variables - * @return if the line has fancy variables - */ - public static boolean hasFancy(String line) { - for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { - if (tagReplacer.contains(line)) { - return true; - } - } - return false; - } + /** + * Checks if a line has fancy variables + * + * @param line raw line from config with variables + * @return if the line has fancy variables + */ + public static boolean hasFancy(String line) { + for (TagReplacer tagReplacer : TagReplacer.getByType(TagType.FANCY)) { + if (tagReplacer.contains(line)) { + return true; + } + } + return false; + } - /** - * Lets get fancy. - * - * @param target Faction to get relate from - * @param fme Player to relate to - * @param prefix First part of the fancy message - * @return list of fancy messages to send - */ - protected static List getFancy(Faction target, FPlayer fme, TagReplacer type, String prefix) { - List fancyMessages = new ArrayList<>(); - boolean minimal = SavageFactions.plugin.getConfig().getBoolean("minimal-show", false); + /** + * Lets get fancy. + * + * @param target Faction to get relate from + * @param fme Player to relate to + * @param prefix First part of the fancy message + * @return list of fancy messages to send + */ + protected static List getFancy(Faction target, FPlayer fme, TagReplacer type, String prefix) { + List fancyMessages = new ArrayList<>(); + boolean minimal = SavageFactions.plugin.getConfig().getBoolean("minimal-show", false); - switch (type) { - case ALLIES_LIST: - FancyMessage currentAllies = SavageFactions.plugin.txt.parseFancy(prefix); - boolean firstAlly = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; - } - String s = otherFaction.getTag(fme); - if (otherFaction.getRelationTo(target).isAlly()) { - currentAllies.then(firstAlly ? s : ", " + s); - currentAllies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); - firstAlly = false; - if (currentAllies.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentAllies); - currentAllies = new FancyMessage(""); - } - } - } - fancyMessages.add(currentAllies); - return firstAlly && minimal ? null : fancyMessages; // we must return here and not outside the switch - case ENEMIES_LIST: - FancyMessage currentEnemies = SavageFactions.plugin.txt.parseFancy(prefix); - boolean firstEnemy = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; - } - String s = otherFaction.getTag(fme); - if (otherFaction.getRelationTo(target).isEnemy()) { - currentEnemies.then(firstEnemy ? s : ", " + s); - currentEnemies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); - firstEnemy = false; - if (currentEnemies.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentEnemies); - currentEnemies = new FancyMessage(""); - } - } - } - fancyMessages.add(currentEnemies); - return firstEnemy && minimal ? null : fancyMessages; // we must return here and not outside the switch - case TRUCES_LIST: - FancyMessage currentTruces = SavageFactions.plugin.txt.parseFancy(prefix); - boolean firstTruce = true; - for (Faction otherFaction : Factions.getInstance().getAllFactions()) { - if (otherFaction == target) { - continue; - } - String s = otherFaction.getTag(fme); - if (otherFaction.getRelationTo(target).isTruce()) { - currentTruces.then(firstTruce ? s : ", " + s); - currentTruces.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); - firstTruce = false; - if (currentTruces.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentTruces); - currentTruces = new FancyMessage(""); - } - } - } - fancyMessages.add(currentTruces); - return firstTruce && minimal ? null : fancyMessages; // we must return here and not outside the switch - case ONLINE_LIST: - FancyMessage currentOnline = SavageFactions.plugin.txt.parseFancy(prefix); - boolean firstOnline = true; - for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { - if (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { - continue; // skip - } - String name = p.getNameAndTitle(); - currentOnline.then(firstOnline ? name : ", " + name); - currentOnline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); - firstOnline = false; - if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentOnline); - currentOnline = new FancyMessage(""); - } - } - fancyMessages.add(currentOnline); - return firstOnline && minimal ? null : fancyMessages; // we must return here and not outside the switch - case OFFLINE_LIST: - FancyMessage currentOffline = SavageFactions.plugin.txt.parseFancy(prefix); - boolean firstOffline = true; - for (FPlayer p : MiscUtil.rankOrder(target.getFPlayers())) { - String name = p.getNameAndTitle(); - // Also make sure to add players that are online BUT can't be seen. - if (!p.isOnline() || (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer()))) { - currentOffline.then(firstOffline ? name : ", " + name); - currentOffline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); - firstOffline = false; - if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { - fancyMessages.add(currentOffline); - currentOffline = new FancyMessage(""); - } - } - } - fancyMessages.add(currentOffline); - return firstOffline && minimal ? null : fancyMessages; // we must return here and not outside the switch - default: - } - return null; - } + switch (type) { + case ALLIES_LIST: + FancyMessage currentAllies = SavageFactions.plugin.txt.parseFancy(prefix); + boolean firstAlly = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == target) { + continue; + } + String s = otherFaction.getTag(fme); + if (otherFaction.getRelationTo(target).isAlly()) { + currentAllies.then(firstAlly ? s : ", " + s); + currentAllies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); + firstAlly = false; + if (currentAllies.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentAllies); + currentAllies = new FancyMessage(""); + } + } + } + fancyMessages.add(currentAllies); + return firstAlly && minimal ? null : fancyMessages; // we must return here and not outside the switch + case ENEMIES_LIST: + FancyMessage currentEnemies = SavageFactions.plugin.txt.parseFancy(prefix); + boolean firstEnemy = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == target) { + continue; + } + String s = otherFaction.getTag(fme); + if (otherFaction.getRelationTo(target).isEnemy()) { + currentEnemies.then(firstEnemy ? s : ", " + s); + currentEnemies.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); + firstEnemy = false; + if (currentEnemies.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentEnemies); + currentEnemies = new FancyMessage(""); + } + } + } + fancyMessages.add(currentEnemies); + return firstEnemy && minimal ? null : fancyMessages; // we must return here and not outside the switch + case TRUCES_LIST: + FancyMessage currentTruces = SavageFactions.plugin.txt.parseFancy(prefix); + boolean firstTruce = true; + for (Faction otherFaction : Factions.getInstance().getAllFactions()) { + if (otherFaction == target) { + continue; + } + String s = otherFaction.getTag(fme); + if (otherFaction.getRelationTo(target).isTruce()) { + currentTruces.then(firstTruce ? s : ", " + s); + currentTruces.tooltip(tipFaction(otherFaction)).color(fme != null ? fme.getColorTo(otherFaction) : Relation.NEUTRAL.getColor()); + firstTruce = false; + if (currentTruces.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentTruces); + currentTruces = new FancyMessage(""); + } + } + } + fancyMessages.add(currentTruces); + return firstTruce && minimal ? null : fancyMessages; // we must return here and not outside the switch + case ONLINE_LIST: + FancyMessage currentOnline = SavageFactions.plugin.txt.parseFancy(prefix); + boolean firstOnline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayersWhereOnline(true, fme))) { + if (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer())) { + continue; // skip + } + String name = p.getNameAndTitle(); + currentOnline.then(firstOnline ? name : ", " + name); + currentOnline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); + firstOnline = false; + if (currentOnline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOnline); + currentOnline = new FancyMessage(""); + } + } + fancyMessages.add(currentOnline); + return firstOnline && minimal ? null : fancyMessages; // we must return here and not outside the switch + case OFFLINE_LIST: + FancyMessage currentOffline = SavageFactions.plugin.txt.parseFancy(prefix); + boolean firstOffline = true; + for (FPlayer p : MiscUtil.rankOrder(target.getFPlayers())) { + String name = p.getNameAndTitle(); + // Also make sure to add players that are online BUT can't be seen. + if (!p.isOnline() || (fme != null && fme.getPlayer() != null && !fme.getPlayer().canSee(p.getPlayer()))) { + currentOffline.then(firstOffline ? name : ", " + name); + currentOffline.tooltip(tipPlayer(p)).color(fme != null ? fme.getColorTo(p) : Relation.NEUTRAL.getColor()); + firstOffline = false; + if (currentOffline.toJSONString().length() > ARBITRARY_LIMIT) { + fancyMessages.add(currentOffline); + currentOffline = new FancyMessage(""); + } + } + } + fancyMessages.add(currentOffline); + return firstOffline && minimal ? null : fancyMessages; // we must return here and not outside the switch + default: + } + return null; + } - /** - * Parses tooltip variables from config
Supports variables for factions only (type 2) - * - * @param faction faction to tooltip for - * @return list of tooltips for a fancy message - */ - private static List tipFaction(Faction faction) { - List lines = new ArrayList<>(); - for (String line : SavageFactions.plugin.getConfig().getStringList("tooltips.list")) { - lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line))); - } - return lines; - } + /** + * Parses tooltip variables from config
Supports variables for factions only (type 2) + * + * @param faction faction to tooltip for + * @return list of tooltips for a fancy message + */ + private static List tipFaction(Faction faction) { + List lines = new ArrayList<>(); + for (String line : SavageFactions.plugin.getConfig().getStringList("tooltips.list")) { + lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(faction, line))); + } + return lines; + } - /** - * Parses tooltip variables from config
Supports variables for players and factions (types 1 and 2) - * - * @param fplayer player to tooltip for - * @return list of tooltips for a fancy message - */ - private static List tipPlayer(FPlayer fplayer) { - List lines = new ArrayList<>(); - for (String line : SavageFactions.plugin.getConfig().getStringList("tooltips.show")) { - lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line))); - } - return lines; - } + /** + * Parses tooltip variables from config
Supports variables for players and factions (types 1 and 2) + * + * @param fplayer player to tooltip for + * @return list of tooltips for a fancy message + */ + private static List tipPlayer(FPlayer fplayer) { + List lines = new ArrayList<>(); + for (String line : SavageFactions.plugin.getConfig().getStringList("tooltips.show")) { + lines.add(ChatColor.translateAlternateColorCodes('&', TagUtil.parsePlain(fplayer, line))); + } + return lines; + } } diff --git a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java index 6b58ff69..1c6a4045 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/TextUtil.java @@ -10,223 +10,223 @@ import java.util.regex.Pattern; public class TextUtil { - public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); - private final static String titleizeLine = repeat("-", 52); + public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>"); + private final static String titleizeLine = repeat("-", 52); - // -------------------------------------------- // - // Top-level parsing functions. - // -------------------------------------------- // - private final static int titleizeBalance = -1; - public Map tags; + // -------------------------------------------- // + // Top-level parsing functions. + // -------------------------------------------- // + private final static int titleizeBalance = -1; + public Map tags; - // -------------------------------------------- // - // Tag parsing - // -------------------------------------------- // + // -------------------------------------------- // + // Tag parsing + // -------------------------------------------- // - public TextUtil() { - this.tags = new HashMap<>(); - } + public TextUtil() { + this.tags = new HashMap<>(); + } - public static String replaceTags(String str, Map tags) { - StringBuffer ret = new StringBuffer(); - Matcher matcher = patternTag.matcher(str); - while (matcher.find()) { - String tag = matcher.group(1); - String repl = tags.get(tag); - if (repl == null) { - matcher.appendReplacement(ret, "<" + tag + ">"); - } else { - matcher.appendReplacement(ret, repl); - } - } - matcher.appendTail(ret); - return ret.toString(); - } + public static String replaceTags(String str, Map tags) { + StringBuffer ret = new StringBuffer(); + Matcher matcher = patternTag.matcher(str); + while (matcher.find()) { + String tag = matcher.group(1); + String repl = tags.get(tag); + if (repl == null) { + matcher.appendReplacement(ret, "<" + tag + ">"); + } else { + matcher.appendReplacement(ret, repl); + } + } + matcher.appendTail(ret); + return ret.toString(); + } - public static FancyMessage toFancy(String first) { - String text = ""; - FancyMessage message = new FancyMessage(text); - ChatColor color = null; - char[] chars = first.toCharArray(); + public static FancyMessage toFancy(String first) { + String text = ""; + FancyMessage message = new FancyMessage(text); + ChatColor color = null; + char[] chars = first.toCharArray(); - for (int i = 0; i < chars.length; i++) { - // changed this so javadocs wont throw an error - String compareChar = chars[i] + ""; - if (compareChar.equals("§")) { - if (color != null) { - if (color.isColor()) { - message.then(text).color(color); - } else { - message.then(text).style(color); - } - text = ""; - color = ChatColor.getByChar(chars[i + 1]); - } else { - color = ChatColor.getByChar(chars[i + 1]); - } - i++; // skip color char - } else { - text += chars[i]; - } - } - if (text.length() > 0) { - if (color != null) { - if (color.isColor()) { - message.then(text).color(color); - } else { - message.then(text).style(color); - } - } else { - message.text(text); - } - } - return message; - } + for (int i = 0; i < chars.length; i++) { + // changed this so javadocs wont throw an error + String compareChar = chars[i] + ""; + if (compareChar.equals("§")) { + if (color != null) { + if (color.isColor()) { + message.then(text).color(color); + } else { + message.then(text).style(color); + } + text = ""; + color = ChatColor.getByChar(chars[i + 1]); + } else { + color = ChatColor.getByChar(chars[i + 1]); + } + i++; // skip color char + } else { + text += chars[i]; + } + } + if (text.length() > 0) { + if (color != null) { + if (color.isColor()) { + message.then(text).color(color); + } else { + message.then(text).style(color); + } + } else { + message.text(text); + } + } + return message; + } - // -------------------------------------------- // - // Fancy parsing - // -------------------------------------------- // + // -------------------------------------------- // + // Fancy parsing + // -------------------------------------------- // - public static String parseColor(String string) { - string = parseColorAmp(string); - string = parseColorAcc(string); - string = parseColorTags(string); - return ChatColor.translateAlternateColorCodes('&', string); - } + public static String parseColor(String string) { + string = parseColorAmp(string); + string = parseColorAcc(string); + string = parseColorTags(string); + return ChatColor.translateAlternateColorCodes('&', string); + } - public static String parseColorAmp(String string) { - string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); - string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); - string = string.replace("&&", "&"); - return string; - } + public static String parseColorAmp(String string) { + string = string.replaceAll("(§([a-z0-9]))", "\u00A7$2"); + string = string.replaceAll("(&([a-z0-9]))", "\u00A7$2"); + string = string.replace("&&", "&"); + return string; + } - // -------------------------------------------- // - // Color parsing - // -------------------------------------------- // + // -------------------------------------------- // + // Color parsing + // -------------------------------------------- // - public static String parseColorAcc(String string) { - return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`plugin", ChatColor.LIGHT_PURPLE.toString()).replace("`SavageFactions", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); - } + public static String parseColorAcc(String string) { + return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`plugin", ChatColor.LIGHT_PURPLE.toString()).replace("`SavageFactions", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); + } - public static String parseColorTags(String string) { - return string.replace("", "").replace("", "\u00A70").replace("", "\u00A71").replace("", "\u00A72").replace("", "\u00A73").replace("", "\u00A74").replace("", "\u00A75").replace("", "\u00A76").replace("", "\u00A77").replace("", "\u00A78").replace("", "\u00A79").replace("", "\u00A7a").replace("", "\u00A7b").replace("", "\u00A7c").replace("", "\u00A7d").replace("", "\u00A7e").replace("", "\u00A7f"); - } + public static String parseColorTags(String string) { + return string.replace("", "").replace("", "\u00A70").replace("", "\u00A71").replace("", "\u00A72").replace("", "\u00A73").replace("", "\u00A74").replace("", "\u00A75").replace("", "\u00A76").replace("", "\u00A77").replace("", "\u00A78").replace("", "\u00A79").replace("", "\u00A7a").replace("", "\u00A7b").replace("", "\u00A7c").replace("", "\u00A7d").replace("", "\u00A7e").replace("", "\u00A7f"); + } - public static String upperCaseFirst(String string) { - return string.substring(0, 1).toUpperCase() + string.substring(1); - } + public static String upperCaseFirst(String string) { + return string.substring(0, 1).toUpperCase() + string.substring(1); + } - public static String implode(List list, String glue) { - StringBuilder ret = new StringBuilder(); - for (int i = 0; i < list.size(); i++) - ret.append(glue).append(list.get(i)); + public static String implode(List list, String glue) { + StringBuilder ret = new StringBuilder(); + for (int i = 0; i < list.size(); i++) + ret.append(glue).append(list.get(i)); - return ret.length() > 0 ? ret.toString().substring(glue.length()) : ""; - } + return ret.length() > 0 ? ret.toString().substring(glue.length()) : ""; + } - // -------------------------------------------- // - // Standard utils like UCFirst, implode and repeat. - // -------------------------------------------- // + // -------------------------------------------- // + // Standard utils like UCFirst, implode and repeat. + // -------------------------------------------- // - public static String repeat(String s, int times) { - return times > 0 ? s + repeat(s, times - 1) : ""; - } + public static String repeat(String s, int times) { + return times > 0 ? s + repeat(s, times - 1) : ""; + } - public static String getMaterialName(Material material) { - return material.toString().replace('_', ' ').toLowerCase(); - } + public static String getMaterialName(Material material) { + return material.toString().replace('_', ' ').toLowerCase(); + } - // -------------------------------------------- // - // Material name tools - // -------------------------------------------- // + // -------------------------------------------- // + // Material name tools + // -------------------------------------------- // - public static String getBestStartWithCI(Collection candidates, String start) { - String ret = null; - int best = 0; + public static String getBestStartWithCI(Collection candidates, String start) { + String ret = null; + int best = 0; - start = start.toLowerCase(); - int minlength = start.length(); - for (String candidate : candidates) { - if (candidate.length() < minlength) { - continue; - } - if (!candidate.toLowerCase().startsWith(start)) { - continue; - } + start = start.toLowerCase(); + int minlength = start.length(); + for (String candidate : candidates) { + if (candidate.length() < minlength) { + continue; + } + if (!candidate.toLowerCase().startsWith(start)) { + continue; + } - // The closer to zero the better - int lendiff = candidate.length() - minlength; - if (lendiff == 0) { - return candidate; - } - if (lendiff < best || best == 0) { - best = lendiff; - ret = candidate; - } - } - return ret; - } + // The closer to zero the better + int lendiff = candidate.length() - minlength; + if (lendiff == 0) { + return candidate; + } + if (lendiff < best || best == 0) { + best = lendiff; + ret = candidate; + } + } + return ret; + } - public String parse(String str, Object... args) { - return String.format(this.parse(str), args); - } + public String parse(String str, Object... args) { + return String.format(this.parse(str), args); + } - // -------------------------------------------- // - // Paging and chrome-tools like titleize - // -------------------------------------------- // + // -------------------------------------------- // + // Paging and chrome-tools like titleize + // -------------------------------------------- // - public String parse(String str) { - return this.parseTags(parseColor(str)); - } + public String parse(String str) { + return this.parseTags(parseColor(str)); + } - public String parseTags(String str) { - return replaceTags(str, this.tags); - } + public String parseTags(String str) { + return replaceTags(str, this.tags); + } - public FancyMessage parseFancy(String prefix) { - return toFancy(parse(prefix)); - } + public FancyMessage parseFancy(String prefix) { + return toFancy(parse(prefix)); + } - public String titleize(String str) { - String center = ChatColor.DARK_GRAY + "< " + parseTags("") + str + parseTags("
") + ChatColor.DARK_GRAY + " >"; - int centerlen = ChatColor.stripColor(center).length(); - int pivot = titleizeLine.length() / 2; - int eatLeft = (centerlen / 2) - titleizeBalance; - int eatRight = (centerlen - eatLeft) + titleizeBalance; + public String titleize(String str) { + String center = ChatColor.DARK_GRAY + "< " + parseTags("") + str + parseTags("") + ChatColor.DARK_GRAY + " >"; + int centerlen = ChatColor.stripColor(center).length(); + int pivot = titleizeLine.length() / 2; + int eatLeft = (centerlen / 2) - titleizeBalance; + int eatRight = (centerlen - eatLeft) + titleizeBalance; - if (eatLeft < pivot) { - return parseTags("") + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(0, pivot - eatLeft) + center + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(pivot + eatRight); - } else { - return parseTags("") + center; - } - } + if (eatLeft < pivot) { + return parseTags("") + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(0, pivot - eatLeft) + center + ChatColor.DARK_GRAY + ChatColor.STRIKETHROUGH + titleizeLine.substring(pivot + eatRight); + } else { + return parseTags("") + center; + } + } - public ArrayList getPage(List lines, int pageHumanBased, String title) { - ArrayList ret = new ArrayList<>(); - int pageZeroBased = pageHumanBased - 1; - int pageheight = 9; - int pagecount = (lines.size() / pageheight) + 1; + public ArrayList getPage(List lines, int pageHumanBased, String title) { + ArrayList ret = new ArrayList<>(); + int pageZeroBased = pageHumanBased - 1; + int pageheight = 9; + int pagecount = (lines.size() / pageheight) + 1; - ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); + ret.add(this.titleize(title + " " + pageHumanBased + "/" + pagecount)); - if (pagecount == 0) { - ret.add(this.parseTags(TL.NOPAGES.toString())); - return ret; - } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { - ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount))); - return ret; - } + if (pagecount == 0) { + ret.add(this.parseTags(TL.NOPAGES.toString())); + return ret; + } else if (pageZeroBased < 0 || pageHumanBased > pagecount) { + ret.add(this.parseTags(TL.INVALIDPAGE.format(pagecount))); + return ret; + } - int from = pageZeroBased * pageheight; - int to = from + pageheight; - if (to > lines.size()) { - to = lines.size(); - } + int from = pageZeroBased * pageheight; + int to = from + pageheight; + if (to > lines.size()) { + to = lines.size(); + } - ret.addAll(lines.subList(from, to)); + ret.addAll(lines.subList(from, to)); - return ret; - } + return ret; + } } \ No newline at end of file diff --git a/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java b/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java index adf3e3a2..667d58b8 100644 --- a/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java +++ b/src/main/java/com/massivecraft/factions/zcore/util/UUIDFetcher.java @@ -18,83 +18,83 @@ import java.util.concurrent.Callable; */ public class UUIDFetcher implements Callable> { - private static final double PROFILES_PER_REQUEST = 100; - private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; - private final JSONParser jsonParser = new JSONParser(); - private final List names; - private final boolean rateLimiting; + private static final double PROFILES_PER_REQUEST = 100; + private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft"; + private final JSONParser jsonParser = new JSONParser(); + private final List names; + private final boolean rateLimiting; - public UUIDFetcher(List names, boolean rateLimiting) { - this.names = ImmutableList.copyOf(names); - this.rateLimiting = rateLimiting; - } + public UUIDFetcher(List names, boolean rateLimiting) { + this.names = ImmutableList.copyOf(names); + this.rateLimiting = rateLimiting; + } - public UUIDFetcher(List names) { - this(names, true); - } + public UUIDFetcher(List names) { + this(names, true); + } - private static void writeBody(HttpURLConnection connection, String body) throws Exception { - OutputStream stream = connection.getOutputStream(); - stream.write(body.getBytes()); - stream.flush(); - stream.close(); - } + private static void writeBody(HttpURLConnection connection, String body) throws Exception { + OutputStream stream = connection.getOutputStream(); + stream.write(body.getBytes()); + stream.flush(); + stream.close(); + } - private static HttpURLConnection createConnection() throws Exception { - URL url = new URL(PROFILE_URL); - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "application/json"); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setDoOutput(true); - return connection; - } + private static HttpURLConnection createConnection() throws Exception { + URL url = new URL(PROFILE_URL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "application/json"); + connection.setUseCaches(false); + connection.setDoInput(true); + connection.setDoOutput(true); + return connection; + } - private static UUID getUUID(String id) { - return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); - } + private static UUID getUUID(String id) { + return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32)); + } - public static byte[] toBytes(UUID uuid) { - ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); - byteBuffer.putLong(uuid.getMostSignificantBits()); - byteBuffer.putLong(uuid.getLeastSignificantBits()); - return byteBuffer.array(); - } + public static byte[] toBytes(UUID uuid) { + ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); + byteBuffer.putLong(uuid.getMostSignificantBits()); + byteBuffer.putLong(uuid.getLeastSignificantBits()); + return byteBuffer.array(); + } - public static UUID fromBytes(byte[] array) { - if (array.length != 16) { - throw new IllegalArgumentException("Illegal byte array length: " + array.length); - } - ByteBuffer byteBuffer = ByteBuffer.wrap(array); - long mostSignificant = byteBuffer.getLong(); - long leastSignificant = byteBuffer.getLong(); - return new UUID(mostSignificant, leastSignificant); - } + public static UUID fromBytes(byte[] array) { + if (array.length != 16) { + throw new IllegalArgumentException("Illegal byte array length: " + array.length); + } + ByteBuffer byteBuffer = ByteBuffer.wrap(array); + long mostSignificant = byteBuffer.getLong(); + long leastSignificant = byteBuffer.getLong(); + return new UUID(mostSignificant, leastSignificant); + } - public static UUID getUUIDOf(String name) throws Exception { - return new UUIDFetcher(Collections.singletonList(name)).call().get(name); - } + public static UUID getUUIDOf(String name) throws Exception { + return new UUIDFetcher(Collections.singletonList(name)).call().get(name); + } - public Map call() throws Exception { - Map uuidMap = new HashMap<>(); - int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); - for (int i = 0; i < requests; i++) { - HttpURLConnection connection = createConnection(); - String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); - writeBody(connection, body); - JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); - for (Object profile : array) { - JSONObject jsonProfile = (JSONObject) profile; - String id = (String) jsonProfile.get("id"); - String name = (String) jsonProfile.get("name"); - UUID uuid = UUIDFetcher.getUUID(id); - uuidMap.put(name, uuid); - } - if (rateLimiting && i != requests - 1) { - Thread.sleep(100L); - } - } - return uuidMap; - } + public Map call() throws Exception { + Map uuidMap = new HashMap<>(); + int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); + for (int i = 0; i < requests; i++) { + HttpURLConnection connection = createConnection(); + String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size()))); + writeBody(connection, body); + JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream())); + for (Object profile : array) { + JSONObject jsonProfile = (JSONObject) profile; + String id = (String) jsonProfile.get("id"); + String name = (String) jsonProfile.get("name"); + UUID uuid = UUIDFetcher.getUUID(id); + uuidMap.put(name, uuid); + } + if (rateLimiting && i != requests - 1) { + Thread.sleep(100L); + } + } + return uuidMap; + } }